Himanshu Ranjan
Himanshu Ranjan

Reputation: 302

How to use json data that I receive from MongoDB in flutter?

I want to use the json data that I receive from mongodb on to my flutter client.

The format of my mongodb document is:

{
    "_id":"2020-10-10 18:35:19.465085",
    "classhours":"56",    
    "sleephours":"56",
    "studyhours":"56",
    "activity":"9.0"
}

I am able to fetch data like this:

 db = await mongo.Db.create(
        "mongodb+srv://id:[email protected]/students?retryWrites=true&w=majority");
    await db.open();

    print('DB Connected');
    coll = db.collection(widget.uid);
    print(coll);
    var response = await coll.find();
    print(response);

I am able to print all the documents in the console using this. How to use the response in the client ui like for text.Can someone help me with it?

Upvotes: 0

Views: 1653

Answers (2)

chinmay kabi
chinmay kabi

Reputation: 1

You can convert the JSON response to a Map. Here's an example

import 'dart:convert';
void main() {
  var db="{\"_id\":\"2020-10-10 18:35:19.465085\",\r\n\"classhours\":\"56\",    \r\n \"sleephours\":\"56\",\r\n\"studyhours\":\"56\",\r\n\"activity\":\"9.0\"\r\n}";
  Map<String, dynamic> db_map=jsonDecode(db);
  print(db_map['_id']);
}

Or you can make a Plain Old Dart Object of the response using Quicktype. Here is what you would get

// To parse this JSON data, do
//
//     final dbModel = dbModelFromJson(jsonString);

import 'dart:convert';

DbModel dbModelFromJson(String str) => DbModel.fromJson(json.decode(str));

String dbModelToJson(DbModel data) => json.encode(data.toJson());

class DbModel {
    DbModel({
        this.id,
        this.classhours,
        this.sleephours,
        this.studyhours,
        this.activity,
    });

    DateTime id;
    String classhours;
    String sleephours;
    String studyhours;
    String activity;

    factory DbModel.fromJson(Map<String, dynamic> json) => DbModel(
        id: DateTime.parse(json["_id"]),
        classhours: json["classhours"],
        sleephours: json["sleephours"],
        studyhours: json["studyhours"],
        activity: json["activity"],
    );

    Map<String, dynamic> toJson() => {
        "_id": id.toIso8601String(),
        "classhours": classhours,
        "sleephours": sleephours,
        "studyhours": studyhours,
        "activity": activity,
    };
}

After you receive your response, just use

DbModel model=DbModel.fromJson(json.decode(db));
print(model._id); // Access whatever variables you want

EDIT 1: In my example, I have hardcoded the response as a String variable db. This is equivalent to the response variable as mentioned in the question

Upvotes: 0

Joy Terence
Joy Terence

Reputation: 730

You can use FutureBuilder widget to set Text widget with value that you receive from asynchronous calls.

For more info refer: https://flutter.dev/docs/cookbook/networking/fetch-data

Upvotes: 1

Related Questions