正在尝试在我的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();
}

这工作正常..但是即使我转到另一页,该方法也将保持调用状态,并将一遍又一遍地打印出来:



我希望只调用一次..该怎么做?

最佳答案

正常后不会调用InitState。相反,您可以使用多种解决方案。
在组件中创建一个属性,以记住是否已经进行了这样的检查

class MyComponentState ... {
  bool hasChecked = false;
  bool isFileExists = false;

  @override
  initState() {
    super.initState();
    if(!hasChecked) {
      this.hasChecked = true;
      this.isFileExists = checkfileexist();
    }
  }
}

关于dart - future 的功能不断重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53280912/

10-09 04:23