GPH
GPH

Reputation: 1161

Flutter data class created by firebase database

May I know how to create a data class by using firebase database in flutter and the data will be loaded immediately in the first page of the app?

enter image description here

    import 'package:dnow/model/company.dart';
    import 'package:firebase_database/firebase_database.dart';

    class RepoData {

      static final Company bawp = new Company(
          name: 'King',
          about: 'Selling Food',
          backdropPhoto: 'assets/hk.jpg',

          shop: <Shop>[
            new Shop(
                shopName: 'ABC',
                thumbnail: 'assets/daofang.png',
                tel: "88776655",
                address: '23 Daisy street, Sydney'),

            new Shop(
                shopName: 'KKK',
                thumbnail: 'assets/fefew.png',
                tel: "88776655",
                address: '131 Man street, Sydney'),


          ],
          location: 'Sydney',
          logo: 'assets/logo.png',
          president: 'Grand Production House');
    }


  [1]: https://i.sstatic.net/DV3X0.png

Upvotes: 2

Views: 4261

Answers (1)

Sebastian
Sebastian

Reputation: 3894

Let's say this is your class simplified

Class Company {
 String name;
 String about;
 String backdropPhoto;
 String location;
 String logo;
 String president;
}

Then in the first page of your app you are listening to the database and receive one company, something like this

database.reference().child('companies').once().then((DataSnapshot snapshot) {
   //todo: parse snapshot
});

Here you are receiving a DataSnapshot object from the database. What you need to do is to parse the DataSnapshot to your Company class. In order to do that you need to create a custom Constructor in your Company class, like this

import 'package:firebase_database/firebase_database.dart';

Class Company {
 String name;
 String about;
 String backdropPhoto;
 String location;
 String logo;
 String president;

 Company.fromDb(DataSnapshot data) {
  name = data['name'];
  about = data['about'];
  backdropPhoto = data['backdropPhoto'];
  location = data['location'];
  logo = data['logo'];
  president = data['president'];
 }
}

Finally you will call this constructor when you receive the document from firebase

database.reference().child('companies').once().then((DataSnapshot snapshot) {
    Company company = Company.fromDb(snapshot);
});

I've only worked with Firestore but I think this is how it may work. Hope it helps

Upvotes: 8

Related Questions