我有这门课
class Notes {
Map _notes = {};
Map get notes => _notes;
// Fetch notes from a json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
_notes = data;
}
}
在
Build()
函数中,在 return Scaffold()
之前我调用
// load notes when app starts
var myNotes = Notes();
myNotes.readJson();
print(myNotes.notes);
我对发生的事情感到困惑。我假设当我打电话时
myNotes.readJson()
response
字符串,data
变量,然后_notes
。如果我在
print(_notes)
中插入 readJson()
语句,我就会看到我所期望的内容——JSON 文件的内容。
此时,我认为
print(myNotes.notes)
(来自main()
)应该具有相同的内容,我最终可以在Build()
中使用。但该语句生成了一张空地图。
我对正在发生的事情感到困惑,我的想法是不正确的,并且不确定如何编写代码,以便在应用程序启动时加载 JSON 文件并可用于解码。
附注以防万一这看起来像是一种奇怪的处理本地文件的方式,最终程序将加载一个非本地的文件。
将 future 构建器用于异步方法:
FutureBuilder(
future: notes.readJson(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.hasData) {
final notes = snapshot.data as Map;
return Text(notes.length.toString()); //handle your UI here
} else {
return const Text('No data available');
}
},
)
并确保将 readJson() 中的返回类型更改为映射:
Future<Map> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
_notes = await json.decode(response);
return _notes;
}