Home > OS >  flutter futurebuilder asyncsnapshot to fetch data that is not list
flutter futurebuilder asyncsnapshot to fetch data that is not list

Time:09-13

Below is the list of data that i am fetching


[
  {
    "name": "kamchatka11111",
    "email": "[email protected]",
    "index": 1,
    "picture": "https://static.themoscowtimes.com/image/1360/73/TASS40183186.jpg",
    "imageFetchType": "networkImage"
  },
  {
    "name": "Valjakutse",
    "email": "[email protected]",
    "index": 2,
    "picture": "https://images.unsplash.com/photo-1561406636-b80293969660?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8YmxhY2slMjBsYWR5fGVufDB8fDB8fA==&w=1000&q=80",
    "imageFetchType": "imageNetwork"
  },
  {
    "name": "einstein",
    "email": "[email protected]",
    "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": "[email protected]",
    "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

CodePudding user response:

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/

CodePudding user response:

Hi Emmanuel hope you are well

A recommended practice would be to map your class, converting it from JSON to a class.

Profile class:

class Profile{
  final String name;
  final String image;


  Profile({
    @required this.name,
    @required this.image,
  });

  factory Profile.fromJson(Map<String, dynamic> json) {
    return Profile(
      name: json['name'] as String,
      image: json['image'] as String,
    );
  }
}

Your data request class

class HttpService {
  final String profilesURL = "https://sourceDataUrl.example";

  Future<List<Profile>> getProfiles() async {
    Response res = await get(profilesURL);

    if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);

      List<Profile> profiles = body
        .map(
          (dynamic item) => Profile.fromJson(item),
        )
        .toList();

      return profiles;
    } else {
      throw "Unable to retrieve profiles.";
    }
  }
}

and get the request data in a FutureBuilder

class ProfilesPage extends StatelessWidget {
  final HttpService httpService = HttpService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Profile"),
      ),
      body: FutureBuilder(
        future: httpService.getProfiles(),
        builder: (BuildContext context, AsyncSnapshot<List<Profile>> snapshot) {
          if (snapshot.hasData) {
            List<Profile> listProfile = snapshot.data;
            return ListView(
              children: listProfile
                  .map(
                    (Profile profile) => ListTile(
                      name: Text(profile.name),
                    ),
                  )
                  .toList(),
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

You can refer to this link for more information about http requests.

  • Related