[英]How to make my flutter app read upadated json file instead of old json file?
我制作了一个应用程序,我必须首先读取本地 json 文件并在应用程序内更新它的一些内容并保存该文件,并且在不关闭应用程序的情况下我想通过读取更新的 json 文件来显示更改。 我能够读取我的 json 文件,将更改保存在该文件中,但是当我尝试通过读取该 json 文件而不关闭应用程序来查看我的更改时,它总是显示我以前的数据。 但是,如果我关闭我的应用程序并再次打开它,它会显示读取新的更新文件。 如何在不关闭应用程序的情况下通过读取更新的 json 文件来显示更改?
这是我的代码:首先我在 initstate 中读取 json 文件:
Future<void> readJson() async {
final String response =
await rootBundle.loadString('jsonfile/primary_values.json');
final data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
setState(() {
if (primaryKey == 'Doctor SSN :') {
widget.primaryIndex = values.doc_ssn;
widget.primaryValue = 'DC0${widget.primaryIndex}';
print(widget.primaryValue);
print('this is readjson');
}
});
}
@override
void initState() {
super.initState();
print("I am doctor init screen");
readJson();
}
然后我将 Doc.ssn 增加 1 并通过单击按钮来编写它。 与该按钮关联的功能是:
_writeJson() async {
print("this is 1st line writejson: ${widget.primaryIndex}");
String response =
await rootBundle.loadString('jsonfile/primary_values.json');
File path = File('jsonfile/primary_values.json');
var data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
final PrimaryValueJson doctor = PrimaryValueJson(
doc_ssn: values.doc_ssn + 1,
phar_id: values.phar_id,
ssn: values.ssn,
);
final update = doctor.toJson();
path.writeAsStringSync(json.encode(update));
print('this is writejson:${doctor.doc_ssn}');
nameController.text = '';
specialityController.text = '';
experienceController.text = '';
widget.primaryIndex = doctor.doc_ssn;
widget.primaryValue = 'DC0${doctor.doc_ssn}';
}
Future<void> insertRecord(context) async {
count = count + 1;
if (nameController.text == '' ||
specialityController.text == '' ||
experienceController.text == '') {
print("Please fill all fields");
} else {
try {
String uri = "http://localhost/hospital_MS_api/insert_doctor.php";
var res = await http.post(Uri.parse(uri), body: {
"Doc_SSN": widget.primaryValue,
"name": nameController.text,
"speciality": specialityController.text,
"experience": experienceController.text,
});
setState(() {
_writeJson();
});
var response = jsonDecode(res.body);
if (response["success"] == "true") {
print("Record Inserted");
} else {
print("Record not inserted");
}
} catch (e) {
print(e);
}
}
}
资产是只读的。 将资产文件写入文件后,还要从该文件中读取。
File path = File('jsonfile/primary_values.json');
...
path.writeAsStringSync(json.encode(update));
...
var data = jsonDecode(path.readAsBytesSync());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.