Display Array Of String From Json Using Future Builder Flutter

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

Asynchronous operations let your program continue other operations while the current operation is being performed. Dart uses Future objects (futures) to represent the results of asynchronous operations. To handle these operations, we can use Async/await, but it is not possible to integrate async and await on widgets. So it is quite tricky to handle futures in widgets. To solve this problem flutter provided a widget called Future Builder.

Display Array Of String From Json Using Future Builder Flutter

 Display Array Of String Form Json Using Future Builder

Step 1 
We cannot directly remove the time stamp from Display Array Of String Form Json Using Future Builder  but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.1

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command.

flutter pub get



Complete Code For  Display Array Of String Form Json Using Future Builder In Flutter
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  final String title;
  MyHomePage({this.title});
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
  final String uri = 'https://jsonplaceholder.typicode.com/users';

  Future<List<dynamic>> _fetchStrings() async {
    var response = await http.get(uri);

    if (response.statusCode == 200) {
      final items = json.decode(response.body).cast<Map<String, dynamic>>();
      List<dynamic> listOfString = items.map((json) {
        return json['name'];
      }).toList();

      return listOfString;
    } else {
      throw Exception('Failed to load internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.indigo,
          title: Text("FutureBuilder & JSON")),
      body: FutureBuilder<List<dynamic>>(
        future: _fetchStrings(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
          }
          return ListView(
            children: snapshot.data.map((data) {
              return ListTile(
                title: Text(data.toString()),
              );
            }).toList(),
          );
        },
      ),
    );
  }
}

 

Related Post