1

I'm new to Dart/Flutter and working on a project to parse some JSON data into a list in Dart. I've been stuck trying to access the list, Dart File # 2 -"_database.bpreading" to select entries. This may be a simple solution in Dart but I've tried many commands using Map() but to no avail. Would appreciate your help. Here are the codes:-

Dart File # 1
=============
class DatabaseFileRoutines {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;

    return File('$path/local_persistence.json');
  }

  Future<String> readJournals() async {
    try {
      final file = await _localFile;

      if (!file.existsSync()) {
        print("File does not exist: ${file.absolute}");
        await writeBpreading('{"bpreadings": []}');
      }
      String contents = await file.readAsString();

      return contents;
    } catch (e) {
      print("error readBpreading: $e");
      return "";
    }
  }

  Future<File> writeBpreading(String json) async {
    final file = await _localFile;
    return file.writeAsString('$json');
  }
}

Database databaseFromJson(String str) {
  final dataFromJson = json.decode(str);
  return Database.fromJson(dataFromJson);
}

String databaseToJson(Database data) {
  final dataToJson = data.toJson();
  return json.encode(dataToJson);
}

class Database {
  List<Bpreading> bpreading;

  Database({
    this.bpreading,
  });

  factory Database.fromJson(Map<String, dynamic> json) => Database(
        bpreading: List<Bpreading>.from(
            json["journals"].map((x) => Bpreading.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "journals": List<dynamic>.from(bpreading.map((x) => x.toJson())),
      };
}

class Bpreading {
  String id;
  String date;
  String time;
  String lab1;
  String lab2;

  Bpreading({
    this.id,
    this.date,
    this.time,
    this.lab1,
    this.lab2,
  });

 

  factory Bpreading.fromJson(Map<String, dynamic> json) => Bpreading(
        id: json["id"],
        date: json["date"],
        time: json["time"],
        lab1: json["lab1"],
        lab2: json["lab2"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "date": date,
        "time": time,
        "lab1": lab1,
        "lab2": lab2,
      };
}
Dart file #2
============
class BpJournal extends StatefulWidget {
   
   @override
   BpJournalState createState() => BpJournalState();
}

class BpJournalState extends State<BpJournal> {
  Database _database;
  String dia;

  Future<List<Bpreading>> _loadJournals() async {
     await DatabaseFileRoutines().readJournals().then((journalsJson) {
       _database = databaseFromJson(journalsJson);
       _database.bpreading.sort((comp1, comp2) => comp2.date.compareTo(comp1.date));
     });
     return _database.bpreading;
  }
  • Please show the structure of your json, like give an example. – Phani Rithvij Jul 06 '20 at 11:32
  • The JSON values are of type String and manually captured and stored in the Database as expected below:- Bpreading( id:8765498 date:200706135125147565 time:135125147565 lab1: 76 lab2: 212 actually, I wanted to access the data(list) from JSON and display it to verify the data input. – Dingo Trail Jul 06 '20 at 16:04
  • Sorry, I don't know why the JSON example, BPreading(.. is wrapped into one line. – Dingo Trail Jul 06 '20 at 16:13
  • Sorry about that didn't understand your question properly, Ok so in which line are you getting an error? I couldn't find any fault in your code. We can try to resolve it by looking at your error message. And what exactly do you mean by select entries?. you are sorting them by date so you want to filter some entries? Assuming your json now looks like `{'journals': [...]}` You need a method to access a json of the form `[{},...]` if I understood correctly. – Phani Rithvij Jul 06 '20 at 16:28
  • If that's your issue take a look at https://stackoverflow.com/a/59031571/8608146 – Phani Rithvij Jul 06 '20 at 16:34
  • I wanted to create a new growable list containing the values for lab1 and lab2 only and I tried creating a new list, myList as follow:-List myList = List.from(_database.bpreading).map((Map dataFromJson)=> Bpreading.fromJson(dataFromJson)).toList(); and got an error after Map as 'Map dataFromJson The argument type 'Bpreading Function(Map)' can't be assigned to the parameter type 'dynamic Function(Bpreading)'.' – Dingo Trail Jul 07 '20 at 15:38

0 Answers0