TransWikia.com

Flutter/Dart - Suggestions for how to Troubleshoot a Future?

Stack Overflow Asked by Meggy on November 29, 2021

Though it was working previously, for some reason my code has now stopped working. Though it fetches the required json data, the build doesn’t render. The error on my app page which is supposed to display a page view was;

type String is not a subtype of 'Map<String,dynamic>' 

But after some tweaks, now the error is;

invalid arguments(s)

I think I may have narrowed it down to the Future;

FutureBuilder<List<SpeakContent>> futureStage() {
  return new FutureBuilder<List<SpeakContent>>(
    future: downloadJSON(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
       print("Snapshot has data.");
        List<SpeakContent> speakcrafts = snapshot.data;
        return new CustomPageView(speakcrafts);
      } else if (snapshot.hasError) {
        return Text('${snapshot.error}');
      }
      return new CircularProgressIndicator();
    },
  );
}

Future<List<SpeakContent>> downloadJSON() async {
  final jsonEndpoint =
      "http://example.com/getContent.php?";    
  final response = await get(jsonEndpoint);

  if (response.statusCode == 200) {    
    List speakcrafts = json.decode(response.body);
    debugPrint(speakcrafts.toString());
    return speakcrafts
        .map((speakcraft) => new SpeakContent.fromJson(speakcraft))
        .toList();
  } else
    throw Exception('We were not able to successfully download the json data.');
}

Although it doesn’t throw an error, I’ve noticed that it doesn’t print my test statement after the "if (snapshot.hasData)" line.

Shouldn’t I see "Snapshot has data." appear in my Android Studio console?

2 Answers

After performing the troubleshooting tips as suggested by Gazihan Alankus and scrimau, I've found the culprit which was a single null entry in the MYSQL Database. Scary... gotta find out how to prevent that problem in the future.

Answered by Meggy on November 29, 2021

Based on what you provided, this

type String is not a subtype of 'Map<String,dynamic>' 

must be this:

return Text('${snapshot.error}');

which means that your downloadJSON() threw an exception. In that case, print('Snapshot has data.'); never executes and the next case that I quoted above is executed.

Please put a breakpoint in the body of downloadJSON(), run it line by line and see what's thrown where.

ALSO, you are making an irrelevant but big mistake here. Do not call downloadJSON() like this. This function is executed at every re-render, which can be many times. You are initiating a JSON download at every redraw of your widget. This may stack up your backend bills... I explain it in this talk in more detail: https://youtu.be/vPHxckiSmKY?t=4771

Answered by Gazihan Alankus on November 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP