Search code examples
flutterdarthashmapflutter-futurebuilder

flutter futurebuilder asyncsnapshot to fetch data that is not list


Below is the list of data that i am fetching


[
  {
    "name": "kamchatka11111",
    "email": "kamchatka@mail.com",
    "index": 1,
    "picture": "https://static.themoscowtimes.com/image/1360/73/TASS40183186.jpg",
    "imageFetchType": "networkImage"
  },
  {
    "name": "Valjakutse",
    "email": "valjakutse@mail.com",
    "index": 2,
    "picture": "https://images.unsplash.com/photo-1561406636-b80293969660?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8YmxhY2slMjBsYWR5fGVufDB8fDB8fA%3D%3D&w=1000&q=80",
    "imageFetchType": "imageNetwork"
  },
  {
    "name": "einstein",
    "email": "einstein@mail.com",
    "index": 12,
    "picture": "https://static.dw.com/image/45897958_303.jpg",
    "imageFetchType": "fadeInImage"
  }
]

Below is how i am populating this list in my flutter class

import 'package:flutter/material.dart';
import 'package:master_learn/classes/async_futures.dart';
import 'package:master_learn/classes/config.dart';
import 'package:master_learn/lists_grids_screens/user_details.dart';
import 'package:master_learn/widgets/marquee_widget.dart';

class FutureBuilderListUsingHashMap extends StatefulWidget {
  const FutureBuilderListUsingHashMap({Key? key}) : super(key: key);

  @override
  _FutureBuilderListUsingHashMapState createState() =>
      _FutureBuilderListUsingHashMapState();
}

class _FutureBuilderListUsingHashMapState
    extends State<FutureBuilderListUsingHashMap> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.white,
            )),
        title: const SizedBox(
          child: MarqueeWidget(
            direction: Axis.horizontal,
            child: Text(
                "Fetch"),
          ),
        ),
      ),
      body: SizedBox(
        child: FutureBuilder(
            future: AsyncFutures.fetchListsOfStringDynamicHashMap(),
            builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
              if (asyncSnapshot.data == null) {
                return const Center(child: CircularProgressIndicator());
              } else {

                return ListView.builder(
                      itemCount: asyncSnapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {

                        return ListTile(
                            contentPadding: const EdgeInsets.all(10),
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage(
                                  asyncSnapshot.data[index]["picture"] ??
                                      ""),
                            ),
                            title:
                                Text(asyncSnapshot.data[index]["name"] ?? ''),
                            subtitle: Text(
                                "Email: ${asyncSnapshot.data[index]["email"] ?? ''}"),
                            );
                      },
                      
                    );

              }
            }),
      ),
    );
  }
}

The problem i am having is how can i use AsyncSnapshot with FutureBuilder to populate data that is not of a list for example the data below


 {
    "name": "einstein",
    "email": "einstein@mail.com",
    "index": 12,
    "picture": "https://static.dw.com/image/45897958_303.jpg",
    "imageFetchType": "fadeInImage"
  }

This may be for example when i am fetching the information for a single profile instead of a list of information of all the profiles


Solution

  • Use the FutureBuilder instead of ListView.builder to fetch a single object. Refer to this awesome explanation in the flutter docs:

    https://docs.flutter.dev/cookbook/networking/fetch-data#1-add-the-http-package

    To encode your json data into proper flutter object you can visit this website

    https://app.quicktype.io/