What is app_flutter directory in dart/flutter - json

I'm working on a flutter application, and I want to write to a JSON file.
My JSON file is in the 'assets/' folder that I created and added to pubspec.yaml.
I can get the data using :
final String res2 = await rootBundle.loadString("assets/profile.json");
I went through here to get the path to the file: https://docs.flutter.dev/cookbook/persistence/reading-writing-files,
Like this :
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/assets/profile.json');
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> writeJSON(newDatas) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$newDatas');
}
But when I try to access the file, I get this error:
Cannot open file, path = '/data/user/0/com.example.myapp/app_flutter/assets/profile.json'
Do you know why?
Thank you!

Related

How to read a json file without assets flutter

I'm trying to execute a json file that shows 2 routes with bat files.
To read the file I'm using a path_provider to localize the json file, so that part I have it already done. I need to know why the program can't reconize the text. I put all the information inside a list bc is the correct way to read all the information.
dynamic complete_route = '';
_functionX(String args1, String args2) async {
var shell = Shell();
try {
final dir = await getApplicationDocumentsDirectory();
String d = dir.path;
final path = d;
final route = await ('$path\\config.json');
String contenido = await _leerArchivo(route);
String local_route = complete_route;
shell.run('$local_route $args1 $args2');
} catch (e) {
debug('error', true);
debug(e, true);
}
}
List lista = [];
_leerArchivo(String ruta) async {
try {
//final File f = File(ruta);
final res = await json.decode(ruta);
lista = res["routes"];
complete_route = res.toString();
return lista;
} catch (e) {
return e.toString();
}
}
Add permission in menifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Put below permission in <application .... /application>
android:requestLegacyExternalStorage="true"
rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/demofolder/demo.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());

Best strategy for locally storing remote data in Flutter

I have a Flutter app that has to request a considerable volume of JSON data from the network. This data has to be converted into a Map.
The remote data changes like every week or so, so I am looking for a way to "cache" or permanently store it in order not to have to request it every time the user opens the app.
What would be the best way to achieve this?
If you want to do something quick, you can store that data in a file (source) using path_provider
Create a reference to the file location:
Future<File> get _localFile async {
final path = await getApplicationDocumentsDirectory();
return File('$path/counter.txt');
}
Write data:
Future<File> writeCounter(int counter) async {
final file = await _localFile;
return file.writeAsString('$counter');
}
Read data:
Future<int> readCounter() async {
try {
final file = await _localFile;
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
return 0;
}
}
If you want to know all the options you have I suggest you read this: https://flutter.dev/docs/development/data-and-backend/state-mgmt/intro
You can use Hive lib to Save your data
import 'dart:io';
import 'package:hive/hive.dart';
part 'main.g.dart';
#HiveType(typeId: 1)
class Person {
Person({required this.name, required this.age, required this.friends});
#HiveField(0)
String name;
#HiveField(1)
int age;
#HiveField(2)
List<String> friends;
#override
String toString() {
return '$name: $age';
}
}
void main() async {
var path = Directory.current.path;
Hive
..init(path)
..registerAdapter(PersonAdapter());
var box = await Hive.openBox('testBox');
var person = Person(
name: 'Dave',
age: 22,
friends: ['Linda', 'Marc', 'Anne'],
);
await box.put('dave', person);
print(box.get('dave')); // Dave: 22
}

Flutter local json

I copy this file in my local and try to parse it.
The following are my questions in mind:
1) how to parse the categories [sport, maths] for listview purpose/
2) how to parse item inside the category?
3) does it need to change the format of the json to have simpler codes?
Currently, this is the code
Future<dynamic> _future;
Future<String> _getJson() async {
var response = await rootBundle.loadString('assets/example_2.json');
var decodedJason = json.decode(response);
return (decodedJason); }
void initState() {
_future = _getJson();
super.initState(); }
Thanks in advance
Add Your JSON File To The pubspec.yaml
assets:
- assets/example_2.json
And Then You Can Use rootBundle To Load & Display It
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/config.json');
}
Make A Sure Json File Is Not Empty?

Flutter fetch JSON from external Storage

I am trying to read a json file from external Storage (Android). But unable to do it.
I already setup the permission in manifest also checking the permission before reading. Though the file is already in the directory cannot read it.
ModelTestModel modelTestModel;
List<ModelTests> listModelTests;
Future<bool> get readPermission async {
await new Future.delayed(new Duration(seconds: 1));
bool checkResult = await SimplePermissions.checkPermission(
Permission.ReadExternalStorage);
if (!checkResult) {
var status = await SimplePermissions.requestPermission(
Permission.ReadExternalStorage);
if (status == PermissionStatus.authorized) {
var res = await fetchModelTest;
return res != null;
}
} else {
var res = await fetchModelTest;
return res != null;
}
return false;
}
Future<List<ModelTests>> get fetchModelTest async {
var dir = await getExternalStorageDirectory();
print(dir);
final data =
await rootBundle.loadString("${dir.path}/BCS/bsc.json");
print(data);
// var data = await rootBundle.loadString('assets/database/bcs-preparation.json'); this is working when when the file is inside assets
var jsonData = json.decode(data);
modelTestModel = ModelTestModel.fromJson(jsonData);
listModelTests = modelTestModel.modelTests;
return listModelTests;
}
Log
I/SimplePermission(17862): Checking permission :
android.permission.READ_EXTERNAL_STORAGE I/flutter (17862): Directory:
'/storage/emulated/0'
the permission is successful but cannot read the file
rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/BCS/bsc.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());

Where is the default save location Flutter

when I write this code:
onSubmit(){
if(csvname.isEmpty){
print('type name');
}else {
File csvFile = new File(csvname + ".csv");
print('yesssss');
}
}
Does it even create a csv file?
If yes where is it saved or how can I view it?
Full Code / pastebin
It is not saving it with the code you posted, see this doc. Here is an example on how to write to a local file:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath; return File('$path/counter.txt');
}
Future<File> writeCounter(int counter) async {
final file = await _localFile; // Write the file return file.writeAsString('$counter');
}