Firebase数据库创建的Flutter数据类

时间:2018-09-13 10:20:43

标签: firebase firebase-realtime-database flutter

我可以知道如何在flutter中使用Firebase数据库创建数据类,并且将立即在应用程序的第一页中加载数据吗?

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.stack.imgur.com/DV3X0.png

1 个答案:

答案 0 :(得分:4)

假设这是您简化的课程

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

然后在应用程序的第一页中,您正在监听数据库并获得一家公司,类似这样的

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

在这里,您正在从数据库接收DataSnapshot对象。您需要做的是将DataSnapshot解析为Company类。为此,您需要在Company类中创建一个自定义的Constructor,像这样

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

最后,当您从firebase收到文档时,将调用此构造函数

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

我只与Firestore合作,但我认为这可能是这样。 希望对您有帮助