estoy tratando de crear un archivo json de forma dynamica en el dispositivo, el archivo se crea correctamente, pero cuando trato de hacer el jsonDecode me arroja este error.
El error es este:
The following LateError was thrown building Home(dirty, state: HomeState#853db):
LateInitializationError: Field 'fileContent' has not been initialized.
The relevant error-causing widget was
Home
package:json_storage/main.dart:101
When the exception was thrown, this was the stack
#0 HomeState.fileContent (package:json_storage/main.dart)
package:json_storage/main.dart:1
#1 HomeState.build
package:json_storage/main.dart:183
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4691
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4574
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4746
...
════════════════════════════════════════════════════════════════════════════════
I/flutter (23568): true
E/flutter (23568): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
E/flutter (23568):
E/flutter (23568): ^
E/flutter (23568):
E/flutter (23568): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5)
E/flutter (23568): #1 _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:522:7)
E/flutter (23568): #2 _parseJson (dart:convert-patch/convert_patch.dart:41:10)
E/flutter (23568): #3 JsonDecoder.convert (dart:convert/json.dart:506:36)
E/flutter (23568): #4 JsonCodec.decode (dart:convert/json.dart:157:41)
E/flutter (23568): #5 jsonDecode (dart:convert/json.dart:96:10)
E/flutter (23568): #6 HomeState.initState.<anonymous closure>
package:json_storage/main.dart:131
E/flutter (23568): #7 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (23568): #8 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (23568): <asynchronous suspension>
E/flutter (23568):
He probado ya poniendolo async por si acaso pero parece que no es el problema, a si que no se que puede estar pasando.
Aqui dejo el codigo, es simplemente el archivo main.dart no tengo nada mas ya que es una app de prueba para ver si podia crear ese json y escribir en el, ademas he usado el paquete path_provider, pero eso es todo, puedo poner un repositorio en github si es necesario, pero solo es copiar y pegar este codigo y añadir path_provider en pubspec.yaml.
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();
late File jsonFile;
late Directory dir;
String fileName = 'myJsonFile.json';
bool fileExists = false;
// Si usas otra cosa Pon String, dynamic
late Map<String, dynamic> fileContent;
@override
void initState() {
super.initState();
getApplicationDocumentsDirectory().then((Directory directory) {
dir = directory;
jsonFile = new File(dir.path + '/' + fileName);
jsonFile.createSync();
fileExists = jsonFile.existsSync();
print(fileExists);
if (fileExists) {
fileContent = jsonDecode(jsonFile.readAsStringSync());
setState(() {});
}
});
}
@override
void dispose() {
keyInputController.dispose();
valueInputController.dispose();
super.dispose();
}
void createFile(Map<String, String> 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, String value) {
print('Writing to file');
Map<String, String> content = {key: value};
if (fileExists) {
print('File exists');
Map<String, String> jsonFileContent =
json.decode(jsonFile.readAsStringSync());
jsonFileContent.addAll(content);
jsonFile.writeAsStringSync(json.encode(jsonFileContent));
} else {
print('File does not exists!');
createFile(content, dir, fileName);
}
this.setState(() {
fileContent = json.decode(jsonFile.readAsStringSync());
});
}
@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() == '')
? 'PlaceHolder'
: 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 ElevatedButton(
child: new Text("Add key, value pair"),
onPressed: () {
writeToFile(keyInputController.text, valueInputController.text);
})
],
),
);
}
}
Alguna idea de que puede pasar?