android - 加载异步地图时传递空值
问题描述
我正在尝试将此地图作为下一页路线的值传递,但 MaterialApp 内的jsonResult中的值变为空值。
调试,可以看到地图中包含了模型的信息。但是,在 MaterialApp 号中,它只显示为 null:
JjModel jmodel = JjModel();
dynamic jsonResult;
loadJson() async {
Map<String, dynamic> mapInicial = jmodel.informacoesIniciais();
final Directory _appDocDir = await getApplicationDocumentsDirectory();
final Directory _appDocDirFolder =
Directory('${_appDocDir.path}/fileSettings');
File jsonFile = File('${_appDocDirFolder.path}/Preferences.json');
if (await jsonFile.exists()) {
String data = jsonFile.readAsStringSync();
jsonResult = json.decode(data);
} else {
final Directory _appDocDirNewFolder =
await _appDocDirFolder.create(recursive: true);
File jsonFile = File('${_appDocDirNewFolder.path}/Preferences.json');
jsonResult = mapInicial;
}
return jsonResult;
}
@override
void initState() {
loadJson();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Menu de Serviços',
debugShowCheckedModeBanner: false,
theme: androidTheme(),
home: ServiceList(jsonResult: jsonResult),
);
}
}
解决方案
您标记loadJson
为async
这样它在 MaterialApp
创建后完成。MaterialApp
用包装FutureBuilder
,重构loadJson
为返回值并将其设置为future
prop。然后snapshot.data
用作ServiceList
.
PS 建议阅读更多关于异步的内容。阅读此内容以开始https://www.woolha.com/articles/dart-event-loop-microtask-event-queue
推荐阅读
- r - 交错两个向量
- angular - Angular 5:使用 ngFor 遍历 [object].Array[object].[object].property
- java - 传递变量时的 Java 多态性。
- python-3.x - Python - 使用 Tika 和 Gensim 提取文本并汇总目录中的多种文件类型
- r - 编写一个 tidyeval 函数来重命名 dplyr 中的因子级别
- hibernate - Grails 单元测试失败:此 GORM 实现目前不支持基于字符串的查询,如 [executeQuery]
- c++ - 了解 vtkSmartPointers
- php - 根据类型(文本、复选框、选择等)以适当的布局显示问题无法正常工作
- sql - SQL 运行总组与总阈值重置
- swift - 在方法中使用类作为泛型类型参数