我能够读取JSON文件,但似乎无法写入或更新JSON文件。我可以更新JSON字符串,但似乎无法将JSON字符串写入文件。下面的代码是我用来读取文件的代码。但是,我无法再写入同一文件。
new ListTile(
title: new Text("Close" ),
trailing: new Icon(Icons.cancel),
onTap: loadpos,
)
class NewPage {
final String title;
final Color color;
NewPage({this.title,this.color});
}
Future <String> _loadpos() async{
return await rootBundle.loadString('assets/button.json');
}
Future <String> loadpos() async{
String jsonword = await _loadpos();
// _parseJsonForPos(jsonword);
List data = json.decode(jsonword);
// data[0]["backgrndcolor"] = "black";
print(data[0]["navbar"]);
}
String _parseJsonForPos(String jsonString) {
List data = json.decode(jsonString);
print(data[0]["_value"]);
}
资产文件:(button.json)
[{“ navbar”:“ top”}]
印刷价值:
Performing hot reload...
Reloaded 5 of 430 libraries in 1,474ms.
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/flutter (15546): top
I/art (15546): Background sticky concurrent mark sweep GC freed 222431(11MB) AllocSpace objects, 0(0B) LOS objects, 93% free, 911KB/12MB, paused 553us total 113.423ms
I/art (15546): Background partial concurrent mark sweep GC freed 222396(11MB) AllocSpace objects, 0(0B) LOS objects, 92% free, 1027KB/13MB, paused 523us total 124.949ms
Lost connection to device.
为尝试尝试另一种读取和写入JSON文件的方法,我使用了另一种方法来创建和写入JSON文件,但是我发现该方法仅临时存储和读取而不写入JSON文件。 。
根据我在Android上的了解,getApplicationDocumentsDirectory()方法返回AppData目录。但是,当我在手机上的此目录中搜索时,找不到我的button.json文件。
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(new MaterialApp(
home: new Home(),
));
}
class Home extends StatefulWidget {
@override
State createState() => new HomeState();
}
class HomeState extends State<Home> {
TextEditingController keyInputController = new TextEditingController();
TextEditingController valueInputController = new TextEditingController();
File jsonFile;
Directory dir;
String fileName = "button.json";
bool fileExists = false;
Map<String, dynamic> fileContent;
@override
void initState() {
super.initState();
getApplicationDocumentsDirectory().then((Directory directory) {
dir = directory;
jsonFile = new File(dir.path + "/" + fileName);
fileExists = jsonFile.existsSync();
if (fileExists) this.setState(() => fileContent = JSON.decode(jsonFile.readAsStringSync()));
});
}
@override
void dispose() {
keyInputController.dispose();
valueInputController.dispose();
super.dispose();
}
void createFile(Map<String, dynamic> content, Directory dir, String fileName) {
print("Creating file!");
File file = new File(dir.path + "/" + fileName);
file.createSync();
fileExists = true;
file.writeAsStringSync(JSON.encode(content));
}
void writeToFile(String key, dynamic value) {
print("Writing to file!");
Map<String, dynamic> content = {key: value};
if (fileExists) {
print("File exists");
Map<String, dynamic> jsonFileContent = json.decode(jsonFile.readAsStringSync());
jsonFileContent.addAll(content);
jsonFile.writeAsStringSync(JSON.encode(jsonFileContent));
} else {
print("File does not exist!");
createFile(content, dir, fileName);
}
this.setState(() => fileContent = JSON.decode(jsonFile.readAsStringSync()));
print(fileContent);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("JSON Tutorial"),),
body: new Column(
children: <Widget>[
new Padding(padding: new EdgeInsets.only(top: 10.0)),
new Text("File content: ", style: new TextStyle(fontWeight: FontWeight.bold),),
new Text(fileContent.toString()),
new Padding(padding: new EdgeInsets.only(top: 10.0)),
new Text("Add to JSON file: "),
new TextField(
controller: keyInputController,
),
new TextField(
controller: valueInputController,
),
new Padding(padding: new EdgeInsets.only(top: 20.0)),
new RaisedButton(
child: new Text("Add key, value pair"),
onPressed: () => writeToFile(keyInputController.text, valueInputController.text),
)
],
),
);
}
}
TL; DR:我可以创建一个json字符串,但无法将其写入json文件
答案 0 :(得分:0)
无法访问创建的json文件的原因是因为使用了getExternalStorageDirectory()
。路径为“ / data / user / 0 / {PACKAGE_NAME} / app_flutter”,我认为无法使用设备的文件浏览器访问它。
我建议使用{{1}},因为它会在'/ storage / emulated / 0 / Android / data / {PACKAGE_NAME} / files'上写入文件,并且易于访问。
以下是运行您提供的repro的一些屏幕截图。
可以使用文件浏览器访问Json文件
打开json文件会显示文件中写入的相同字符串