Home > front end >  How to get the json from API
How to get the json from API

Time:05-20

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.

CodePudding user response:

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.

  • Related