Ping Kee Ng
Ping Kee Ng

Reputation: 557

Writing to a Local json file dart flutter

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.

Upvotes: 13

Views: 62659

Answers (3)

Sadikul Haque Sadi
Sadikul Haque Sadi

Reputation: 579

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;
  }
  
}

Upvotes: 8

clarity
clarity

Reputation: 67

It does not appear that you can write to a file in assets during runtime (see this post for reference). This page describes how to use path_provider to to find the local paths and read/write local files.

Upvotes: 3

Dinesh Balasubramanian
Dinesh Balasubramanian

Reputation: 21728

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

Upvotes: 16

Related Questions