0

What I want to do is get the json from API and make the buttons from the json content.

API response doesn't change, so I want to call this just one time.( not need to recall when reloading the widget)

So, my idea is simply call the API from initState

  Future<List> getSmartTags() async {
    var url = Uri.parse("http://localhost:8008/api/smarttags/");
    var resp = await http.get(url);
    return json.decode(resp.body);
  }

and want to confirm json is correctly returned.

  void initState() {
    super.initState();
    var temp = getSmartTags();
    print(temp);
  }

This error occurs.

[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>'
#0      _SmartTagState.getSmartTags (package:flutter_aic/main.dart:64:17)

I think this is the basic concept of Future though, I didn't get it.

whitebear
  • 11,200
  • 24
  • 114
  • 237
  • can you provide json response? – Behzod Faiziev May 19 '22 at 11:53
  • If you getting data from API and display it into Flutter. refer my answers [Answer 1](https://stackoverflow.com/a/68533647/13997210), [Answer 2](https://stackoverflow.com/a/68807671/13997210), [Answer 3](https://stackoverflow.com/a/69131277/13997210), [Answer 4](https://stackoverflow.com/a/68709502/13997210), [Answer 5](https://stackoverflow.com/a/68594656/13997210) and official documentation [here](https://docs.flutter.dev/cookbook/networking/fetch-data) – Ravindra S. Patil May 19 '22 at 11:53
  • 1
    Well, the error message is clear, you are receiving a Map type but your function returns a List, they are incompatible types. Moreover, your variable `temp` and `print` in `initState` cannot be used. – Ουιλιαμ Αρκευα May 19 '22 at 12:13
  • Thank you very much I checked the articles you mentioned and solved. Maybe the problem is I misunderstanding the Json and Map. – whitebear May 20 '22 at 05:22

1 Answers1

1

I think you're getting back a Map<String, dynamic> whenever you decode your html body with json, and not a List.

Furthermore, your return value is not a Future because of the await. Whenever the request is done, the final value is stored in your variable resp.

So, theoretically, it should work like this:

Map<String, dynamic> getSmartTags() async {
var url = Uri.parse("http://localhost:8008/api/smarttags/");
var resp = await http.get(url);
return json.decode(resp.body);

It would return a Future<Map<String, dynamic>> instead, when you write it without the wait.

And to avoid more errors because of your async function and the print() outside, I would recommend you to print the JSON output inside your function, not in initState.

C4s4r
  • 404
  • 3
  • 7