Mehdi Rezzag Hebla
Mehdi Rezzag Hebla

Reputation: 334

Flutter how to access the map from Future Function

New to dart, I want to access the value userId inside the Map object, but I keep getting an Error (See comment):

The method 'then' isn't defined for the type 'Function'.
Try correcting the name to the name of an existing method, or defining a method named 'then'.
  Future<Map> getData() async {
    Response load = await get('https://jsonplaceholder.typicode.com/todos/1');
    print(load.statusCode);
    print(load.body);
    Map map = jsonDecode(load.body);
    return map;
  }

  @override
  void initState() {
    var getit = getData;
    print('placeholder');
    getit.then((e){e['userId'];}); // I get an Error here
    super.initState();
  }

Upvotes: 1

Views: 6382

Answers (1)

loganrussell48
loganrussell48

Reputation: 1864

The issues arise from the line var getit = getData;

When you provide the method name with no parenthesis(getData), you're passing the method as an object rather than calling the method and retrieving its return value.

To fix the issue, simply call the method by providing parenthesis:

var getit = getData();

Upvotes: 2

Related Questions