在扑朔迷离中,我想从firebase实时数据库中获取数据并将其保存为json并保存在本地存储中,并从该json填充列表视图。如果数据库在firebase中进行了更新,那么Json应该会进行更新并反映在列表视图中。
DataSnapshot firebaseData;
File allnews_json;
Directory dir;
String allnews_filename = "allnews.json";
bool fileExists = false;
@override
void initState() {
super.initState();
getApplicationDocumentsDirectory().then((Directory directory) {
dir = directory;
allnews_json = new File(dir.path + "/" + allnews_filename);
fileExists = allnews_json.existsSync();
if (fileExists) this.setState(() => fileContent = JSON.decode(allnews_json.readAsStringSync()));
});
FirebaseDatabase.instance.reference().child('news')
.once()
.then((onValue) {
firebaseData = onValue.value;
write(firebaseData);
});
}
void write(DataSnapshot snapshot) async {
print("Creating file!");
File file = new File(dir.path + "/" + allnews_filename);
file.createSync();
final String key = snapshot.key;
final String headline = snapshot.value['title'];
final int news = snapshot.value['content'];
String content = '{"$key":{"headline":"$headline","news":"$news"}}';
file.writeAsStringSync(content);
}
这是我到目前为止的代码。但这也有问题。