【问题标题】:How to get data from Firestore in Scoped Model - Flutter如何在 Scoped 模型中从 Firestore 获取数据 - Flutter
【发布时间】:2019-07-26 05:45:36
【问题描述】:

我正在尝试从 Firestore 获取数据,在调试打印中,它会在未来工作并且列表获取数据,并且在 debugPrint 长度为 +,但是当我尝试在另一个小部件列表中获取数据时接收到 null,在 debugPrint 长度是0 .

model.dart

  class BBModel extends Model {
  int _counter = 10;

  int get counter => _counter;

  var db = dbBB;
  List<BB> _bbs;

  List<BB> get bbs => _bbs;

  Future<List<BB>> getBBs() async {
    var snapshot = await db.getDocuments();
    for (int i = 0; i < snapshot.documents.length; i++) {
      _bbs.add(BB.fromSnapshot(snapshot.documents[i]));
      print(bbs.length.toString()); //recives 23
    }
    notifyListeners();
    return _bbs;
  }
}

main.dart

void main() {
  var model = BBModel();

  model.getBBs();
  runApp(ScopedModel<BBModel>(model: BBModel(), child: MyApp()));
}

statefullpage.dart

Expanded(
flex: 1,
child: Container(
height: 400.0,
child: ScopedModelDescendant<BBModel>(
builder: (context, child, model) {
return ListView.builder(
itemCount: model.bbs.length,
itemBuilder: (context, index) {
return Text(model.bbs[index].bbID);
  });
 }))),

【问题讨论】:

    标签: firebase dart flutter


    【解决方案1】:

    等待你可以使用

    await model.getBBs();
    

    但是,除此之外,我不建议将数据上传到主服务器,因为随着数据越来越大,您会减慢应用程序的使用速度。仅将数据上传到您需要的页面并找到一种方法来执行此操作。

    【讨论】:

      【解决方案2】:

      看起来您在 main.dart 中编写的代码是错误的。实例化的模型与您在 ScopedModel 中发送的模型不同。

      更正

      在您的 main.dart 文件中将 model: model 更改为 model: BBModel()

      void main() {
        final model = BBModel();    
      
        model.getBBs();
        runApp(ScopedModel<BBModel>(model: model, child: MyApp()));
      }
      

      【讨论】:

        【解决方案3】:

        在 main.dart 中,我会尝试这样做:

        void main() {
          var model = BBModel();
        
          model.getBBs().then((someVariableName){
            runApp(ScopedModel<BBModel>(model: BBModel(), child: MyApp()));
          });
        }
        

        注意:“someVariableName”将包含一个列表

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-17
          • 1970-01-01
          • 1970-01-01
          • 2019-10-22
          • 2020-04-19
          • 1970-01-01
          • 2018-12-22
          • 2020-04-01
          相关资源
          最近更新 更多