How to assign values from file to members of classes in Flutter?

Viewed 21

How can I assign values read asynchronously from JSON file with path_provider package.

I have DataStorage class for handling file

class DataStorage {
  DataStorage() {
    initFile();
  }

  Future<String> get docDirPath async {
    final dir = await getApplicationDocumentsDirectory();
    return dir.path;
  }

  String fileName = '/lists.json';

  Future<File> get listsFile async {
    final path = await docDirPath;
    return File(path + fileName);
  }

  Future<Map<String, dynamic>> readFile() async {
    try {
      final file = await listsFile;
      final data = jsonDecode(await file.readAsString(encoding: utf8));
      return data;
    } on Exception catch (e) {
      return {"error": e.toString()};
    }
  }

  Future<File> writeFile(Map<String, dynamic> data) async {
    final file = await listsFile;
    final jsonData = jsonEncode(data);
    return file.writeAsString(jsonData);
  }

  Future<Map<String, dynamic>> loadTemplate() async {
    return jsonDecode(await rootBundle.loadString('assets/template.json'));
  }

  // creating file from a template if file doesn't exists
  void initFile() async {
    if (!(await listsFile).existsSync()) {
      writeFile(await loadTemplate());
    }
  }
}

and i want to asign values from that file for example:

class Data {
  int id; 
  String label;
  bool state;

  Data({
    required this.id,
    required this.label,
    required this.state
  });

  factory Data.fromJson(Map<String, dynamic> json) => Data(
      id: json['id'] as int,
      label: json['label'] as String,
      state: json['state'] as bool);


}

class Demo {
  DataStorage storage = DataStorage();
  Data data; // How to inicialize this member with Data.fromJson(await storage.readFile());
}

I can't create async constructor neither async initState() function in stateful widget.

1 Answers

You can create an async function to set that data.

Ex.

DataConstructor(){
   this.setInitialData();
}

Or

//In some stateful widget

initState(){
   this.setInitialData();
}

Future<void> setInitialData() async {
 ....
}
Related