I am able to read a JSON file but I can’t seem to write to or update a JSON file. I’m able to update a JSON string but can’t seem up write my json string to a file. The code below is the what I used to read the file. However, I’m not able to then write to the same file.
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"]);
}
Assets file: (button.json)
[{"navbar" : "top"}]
Printed Value:
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.
- The problem that I am currently facing is that I am unable to write and update the value to JSON file.
In pursuit of trying another way to read and write to a JSON file, I used another method to create and write to the JSON file but I’ve found that this only temporarily stores and reads and does not write to a JSON file.
From what I understand on Android, the getApplicationDocumentsDirectory() method returns the AppData directory. However, when I searched within this directory on my phone, I could not find my button.json file.
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: I’m able to create a json string but unable to write it to a json file