Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a Local json file dart flutter

Tags:

json

flutter

dart

I am creating an app that allows user to save small data. I have a json file in my assets folder and I would like to create an app that can write more json data to it. Path: assets/vault.json

vault.json

[
  {
    "name":"Ash",
    "age":"22",
    "hobby" : "golf"
  },
  {
    "name":"philip",
    "age":"17",
    "hobby" : "fishing"
  },
  {
    "name":"charles",
    "age":"32",
    "hobby" : "drawing"
  }

]

However I am stuck at adding more list to the json file.

In my main.dart, I created 3 textfield for input and a button onPress to trigger writeToFile(arg1,arg2,arg3).

Here is what I have tried:

void writeToFile(String hobbyy, String agee, String namee) {
  print("Writing to file!");

  Map<String, dynamic> content = new Map();
  content1 = {name: namee};
  content2 = {age: agee};
  content3 = {hobby: hobbyy};

  content.addAll(content1);
  content.addAll(content2);
  content.addAll(content3);


  print(content);  //working fine
}

Future<String> _loadAVaultAsset() async {
  return await rootBundle.loadString('assets/vault.json');
}

Future loadVault() async {
  String jsonString = await _loadAVaultAsset();
  final jsonResponse = json.decode(jsonString);
  var add = jsonResponse.toString();


  add = add.replaceFirst(new RegExp(r'}]'), "},"+content.toString()+"]");

  print(add); //shows the full json string that I want. 

//How to add/replace (add) into the json file?
}

although I am getting the json string that I want, I am unable to reflect it in the json file.

Here is my vault_model.dart (incase if there is any use):

class UsersList{
  final List<Users> user;

  UsersList({
    this.user,
  });

  factory UsersList.fromJson(List<dynamic> parsedJson){

    List<Users> entireList = new List<Users>();

    entireList = parsedJson.map((i)=>Users.fromJson(i)).toList();

    return UsersList(
      user: entireList,
    );
  }
}

class Users{
  final String name;
  final String age;
  final String hobby;

  Users({
    this.name,
    this.age,
    this.hobby
});

  factory Users.fromJson(Map<String, dynamic> json){
    return new Users(
      name: json['name'],
      age: json['age'],
      hobby: json['hobby'],
    );
  }

}

Please teach me how to replace the old json string with the new string (add) in the assets/vault.json path.

like image 253
Ping Kee Ng Avatar asked Aug 12 '18 08:08

Ping Kee Ng


People also ask

How do you call local JSON in flutter?

The code which is used to fetch data from the JSON file (see the full code below): Future<void> readJson() async { final String response = await rootBundle. loadString('assets/sample. json'); final data = await json.

How do I store JSON in flutter?

fromJson(Map<String, dynamic> json) : this. value = json['value']; Map<String, dynamic> toJson() => {'value': value}; } ... JsonStore jsonStore = JsonStore(); CounterModel counter; loadFromStorage() async { Map<String, dynamic> json = await jsonStore.


2 Answers

Instead of storing in rootBundle, can you store it in app's file system. Refer here

like image 102
Dinesh Balasubramanian Avatar answered Oct 17 '22 15:10

Dinesh Balasubramanian


Since you cannot write to a file in assets during runtime, as mentioned before, store it somewhere else in your local machine. The following code can read from a json file and write to it --

import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/../vault.json'); //load the json file
    await readPlayerData(file); //read data from json file
    
    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json 
      .map(
        (player) => player.toJson(),
      )
      .toList();
      
    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async { 
  
    
    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);
    
    for(var p in jsonResponse){
        
        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }
    
      
}

class Player {
  late String name;
  late String age;
  late String hobby;
  

  Player(
     this.name,
     this.age,
    this.hobby,
  
  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];
    
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;
    
    return data;
  }
  
}
like image 41
Sadikul Haque Sadi Avatar answered Oct 17 '22 15:10

Sadikul Haque Sadi