写入/从文件和setstate -flutter写入/读取
有经验丰富的同事的问题。在我的应用程序中,我有一个从JSON文件加载的项目的列表视图。
itemBuilder: (context, index) => allRadioList(articles[index], context, _content, onPressing: () {
_writeDataFav(articles[index].id.toString(), _content);
_readData();
}),
用户可以通过单击“按钮”通过编写带有ID号的数字到本地文件,然后加载文件内容并将其保存到SetState,将项目添加到收藏夹中。
IconButton(
icon: Icon(LineIcons.heartAlt, size: 20, color: Colors.yellow),
onPressed: onPressing,
),
当用户从收藏夹中删除项目时,我加载文件的内容,对其进行修改并将其保存到文件中,然后加载并将其保存到SetState。
Future<void> _readData() async {
final dirPath = await _getDirPath();
final myFile = await File('$dirPath/fav.txt');
final data = await myFile.readAsString(encoding: utf8);
setState(() {
_content = data;
});
}
Future<void> _writeDataFav(newString, _content) async {
final _dirPath = await _getDirPath();
final _myFile = File('$_dirPath/fav.txt');
String res = '${_content}|${newString}|';
await _myFile.writeAsString(res);
}
这几乎可以完美地工作,但是有时在加载动作或空表之后,文件的内容不加载。刷新后,一切正常。在执行下一个操作之前,看来该文件无法加载。
仅在验证文件已保存后才可以执行函数吗?只有然后设置设置?
我考虑过使用共享Preferrences或本地数据库,但是对于如此少量的数据来说,这可能太多了。
Question for more experienced colleagues. In my application I have a listview of items loaded from a json file.
itemBuilder: (context, index) => allRadioList(articles[index], context, _content, onPressing: () {
_writeDataFav(articles[index].id.toString(), _content);
_readData();
}),
The user can add an item to the favorites by clicking on the button via writing an array with ID numbers to a local file, then loading the contents of the file and saving it to setState.
IconButton(
icon: Icon(LineIcons.heartAlt, size: 20, color: Colors.yellow),
onPressed: onPressing,
),
When a user removes an item from favorites, I load the contents of the file, modify it and save it to the file, and then load it and save it to setState.
Future<void> _readData() async {
final dirPath = await _getDirPath();
final myFile = await File('$dirPath/fav.txt');
final data = await myFile.readAsString(encoding: utf8);
setState(() {
_content = data;
});
}
Future<void> _writeDataFav(newString, _content) async {
final _dirPath = await _getDirPath();
final _myFile = File('$_dirPath/fav.txt');
String res = '${_content}|${newString}|';
await _myFile.writeAsString(res);
}
This works almost perfectly, but occasionally the contents of the file don't load, after action click or an empty table is loaded. After refreshing everything is ok. It looks like the file could not be loaded before the next operations were performed.
Is it possible to execute the function only after verifying that the file has been saved? Only then set setState?
I considered using sharedPreferrences or a local database, but that's probably too much for such a small array of data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
OnPressing
更改为async函数,因此_ReadData
才能在完成_WRETEDATAFAV
后才执行。Change the
onPressing
to async function so_readData
will only be executed after_writeDataFav
is completed.