flutter - 如何使用“未来”的实例' 作为 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
放入initState
mixItems
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”类定义运算符“[]”。
我该如何解决?
解决方案
推荐阅读
- flutter - FieldValue.increment 在颤动中无法离线工作
- c# - 如何使用多行正则表达式将模式与数字或数字和单个破折号匹配
- javascript - Splitchunks之后没有定义全局变量
- kubernetes - 如何在 containerd 中添加 Harbor 注册表
- python - 无法使用 pyodbc python 连接到 Access 数据库
- mongodb - 远程连接mongodb
- winapi - 为什么 32 位 Windows 应用程序“不需要释放使用 LoadResource 加载的资源”?
- powershell - Windows PowerShell:如何解析日志文件?
- python - 将字节转换为列表未按预期工作
- python - 参数范围和返回值的区别