首页 > 解决方案 > 如何使用“未来”的实例' 作为 json(地图)

问题描述

我通过 API 获取 json 数据并解码为 Map<String,dynamic>

Future fetchMix() async {
  final response = await http.get(Uri.http('localhost:8008', 'api/mixs'));

  if (response.statusCode == 200) {
    Map<String, dynamic> json = jsonDecode(response.body);
    print (json['items'][0]) // OK, it correctly shows the data
    return json['items'];

  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load API');
  }
}

然后调用并将数据fetchMix放入initStatemixItems

class _MyHomePageState extends State<MyHomePage> {
  Future<dynamic> mixItems;
  @override
  void initState() {
    super.initState();
    mixItems = fetchMix();
  }

然后使用它,FutureBuilder但它不起作用。

    child: FutureBuilder<dynamic>(
      future: mixItems,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          print("snapshot has arrived!");
          print(mixItems);
          print(mixItems[0]);// it shows error.
          return Text(mixItems[0]);
        }
        return CircularProgressIndicator();
      },
    )

但是 print(mixItems[0]) 显示错误

lib/main.dart:115:29:错误:未为“Future”类定义运算符“[]”。

我该如何解决?

标签: flutterdart

解决方案


推荐阅读