Fabrício Carraro
Fabrício Carraro

Reputation: 11

Flutter - FutureBuilder not waiting for "future" to return

I check some similar topics regarding this, but couldn't find a solution to my problem.

I created a FutureBuilder on my Home screen, because I want to use the result of an asynchronous function (that reads a JSON) to build it. I'm calling this async function in the FutureBuilder's "future:", but apparently the program is continuing to build the screen before receiving the data from the "future" (which is coming up empty).

I debugged the function, and it retrieves the desired JSON data, but apparently it is not giving enough time to return to the FutureBuilder, because when I see the "snapshot.data", it is empty.

Is this the case? Doesn't FutureBuilder expect the result from "future:"? What to do then?

Here is my Home screen with the FutureBuilder:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Country Population Guesser"),
      ),
      backgroundColor: ThemeColors.primaryColor[900],
      **body: FutureBuilder<List<Country>>(
          future: CountryDAO().fetchJSON()**,
          builder: (context, snapshot) {
            List<Country>? countryList = snapshot.data;
            if (snapshot.connectionState != ConnectionState.done) {
              return Center(
                child: Column(
                  children: [
                    CircularProgressIndicator(),
                    Text('Loading'),
                  ],
                ),
              );
            }

            //print("${snapshot.hasData} + ${countryList}");
            if (snapshot.hasData && countryList != null) {
              if (countryList.isNotEmpty) {
              ...

And here's the function I'm calling:

class CountryDAO {

  **Future<List<Country>> fetchJSON() async** {
    final String response = await rootBundle.loadString('assets/database.json');
    final data = json.decode(response);
    
    final List<Country> countryList = convertToList(data["countries"]);

    return countryList;
  }

  List<Country> convertToList(List<Map<String, dynamic>> countryMap){
    List<Country> countryList = [];

    for(var country in countryMap){
      print(country);
      countryList.add(Country.fromMap(country));
    }
    return countryList;
  }
}

UPDATE: The problem was not the FutureBuilder, but the function creating a wrong type cast and was crashing without a proper error message.

Thanks!

Upvotes: 1

Views: 1371

Answers (2)

pmatatias
pmatatias

Reputation: 4404

try to follow this official example : https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

body: FutureBuilder<List<Country>>(
        future: CountryDAO().fetchJSON()**,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<Country>? countryList = snapshot.data;
            return ListView(); //display your data
          } else if (snapshot.hasError) {
            return Text(snapshot.error.toString()); // display error 
          }else {
            return CircularProgressIndicator(); // loader animation
          }

Upvotes: 2

sigmapie8
sigmapie8

Reputation: 467

countryList should be assigned value only after snapshot has data.

if (snapshot.connectionState == ConnectionState.done && snapshot.hasData){
  List<Country> countryList = snapshot.data!;
  if (countryList.isNotEmpty) {
  ...
} 

Upvotes: 1

Related Questions