2
votes

I've seen this already: https://stackoverflow.com/a/49146503/1757321

Followed the solution, but it is not working in my case.

Some enlightenment would do for me this afternoon

  Future<String> loadInterest() async {
    print('Going to load interests');

    final whenDone = new Completer();

    SharedPreferences prefs = await SharedPreferences.getInstance();

    final token = await prefs.getString('token');

    print('The token ${token}');

    await this.api.interests(token).then((res) {
      // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
      whenDone.complete(res['interests']);
    });

    return whenDone.future;
  }

Then I'm trying to use the above Future in a future builder like so:

new FutureBuilder(
  future: loadInterest(),
  builder: (BuildContext context, snapshot) {
     return snapshot.connectionState == ConnectionState.done
            ? new Wrap(
                 children: InterestChips(snapshot.data),
              )
            : Center(child: CircularProgressIndicator());
         },
     ),

Where InterestChips(...) is this:

  InterestChips(items) {
    print('Interest Chips ${items}');
    List chipList;

    for (Object item in items) {
      chipList.add(Text('${item}'));
    }

    return chipList;
  }

But, I always get null as the snapshot, which means the loadInterest() for the Future is not returning anything.

If I understand this answer correctly, then I'm doing mine along the lines of that: https://stackoverflow.com/a/49146503/1757321

1
Send the link to which your sending the HTTP request. - Son of Stackoverflow

1 Answers

1
votes

You don't need to use a Completer for this. Since your method is already async, you should just do this for your first code block:

Future<String> loadInterest() async {
  print('Going to load interests');

  final whenDone = new Completer();

  SharedPreferences prefs = await SharedPreferences.getInstance();

  final token = await prefs.getString('token');

  print('The token ${token}');

  final res = await this.api.interests(token).then((res) {
  // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
  return res['interests']);
}

You might also want to check for snapshot.hasError to make sure you're not getting any exceptions in there.