我试图在我的flutter应用程序中读取和写入文件..
Future<String> get _localPath async {
print('hi');
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
File f = File('$path/mypollshash.txt');
if (f.existsSync()) {
print('exists');
String contents = await f.readAsString();
content = contents;
fetchHash();
} else {
print('not exists');
fetch();
}
return f;
}
Future checkfileexist() async {
try {
final file = await _localFile;
String contents = await file.readAsString();
content = contents;
} catch (e) {
//return 'nothing';
}
}
Future<File> writehash(String hash) async {
final file = await _localFile;
return file.writeAsString('$hash', mode: FileMode.write);
}
Future<File> get _localjson async {
final path = await _localPath;
return File('$path/mypolls.json');
}
Future<File> writejson(String json) async {
final file = await _localjson;
return file.writeAsString('$json', mode: FileMode.write);
}
readjson() async {
try {
final file = await _localjson;
String contents = await file.readAsString();
content = contents;
setState(() {
polls = pollsFromJson(content);
isloading = false;
});
writejson(pollsToJson(polls));
writehash(polls.hash);
print('here');
// return contents;
} catch (e) {
fetch();
print('there');
print(e);
// If we encounter an error, return 0
//return 'nothing';
}
}
fetch() async {
String data =
await DefaultAssetBundle.of(context).loadString("assets/mypolls.json");
setState(() {
polls = pollsFromJson(data);
isloading = false;
});
writejson(pollsToJson(polls));
writehash(polls.hash);
}
fetchHash() async {
String data = await DefaultAssetBundle.of(context)
.loadString("assets/pollshash.json");
print(content);
final pollshash = pollshashFromJson(data);
if (content == pollshash.hash) {
print('take from the saved json');
readjson();
} else {
print('call api');
fetch();
}
}
然后在这里调用它:
@override
void initState() {
super.initState();
checkfileexist();
}
这很好..但是即使我转到另一页,该方法也将保持调用状态,并将一遍又一遍地打印出来:
I / flutter(17060):嗨 I /颤振(17060):在这里 I /颤振(17060):存在 I /颤振(17060):d1f4bd60f52991d100adafa416f48b52 I / flutter(17060):从保存的json中获取
我只希望调用一次。.该怎么做?
答案 0 :(得分:0)
通常不会调用InitState。相反,您可以使用多种解决方案。 在组件中创建一个属性以记住是否已经进行了这样的检查
class MyComponentState ... {
bool hasChecked = false;
bool isFileExists = false;
@override
initState() {
super.initState();
if(!hasChecked) {
this.hasChecked = true;
this.isFileExists = checkfileexist();
}
}
}