首页 > 解决方案 > Flutter 如何从 Future Function 访问地图

问题描述

飞镖新手,我想访问对象userId内部的值Map,但我不断收到错误(见评论):

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();
  }

标签: dictionaryflutterdartfuture

解决方案


问题源于线路var getit = getData;

当您提供不带括号 ( getData) 的方法名称时,您将方法作为对象传递,而不是调用该方法并检索其返回值。

要解决此问题,只需通过提供括号来调用该方法:

var getit = getData();


推荐阅读