I have seen lot of examples from parsing the json
file from the assets
But How do I get the get the json file from file manager and parse it?
void openJsonFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
if (file.path.contains('.json')) {
parse(file);
}
} else {
// User canceled the picker
}
}
void parse(File file) async {
final String response = await rootBundle.loadString(file.path);
List<JsonItem> items = (jsonDecode(response) as List<dynamic>)
.map((e) => JsonItem.fromJson(e))
.toList();
Navigator.of(dkey.currentState!.context).push(
MaterialPageRoute(
builder: (context) => JsonParsedListScreen(items: items)),
);
}
class JsonItem {
int? id;
String? name;
JsonItem({this.id, this.name});
factory JsonItem.fromJson(Map<String, dynamic> json) {
return JsonItem(name: json['name'], id: json['id']);
}
}
E/flutter (20466): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Unable to load asset: /data/user/0/com.example.play/cache/file_picker/sample.json
E/flutter (20466): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
E/flutter (20466): <asynchronous suspension>
E/flutter (20466): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:72:27)
E/flutter (20466): <asynchronous suspension>
E/flutter (20466): #2 HomePage.parse (package:play/nextPage.dart:52:29)
E/flutter (20466): <asynchronous suspension>
E/flutter (20466):
I get this log for this line final String response = await rootBundle.loadString(file.path);
CodePudding user response:
This is for loading from assets
,
final String response = await rootBundle.loadString(file.path);
but reading from a file is something like this:
final response = await file.readAsString();