简体   繁体   English

如何在范围模型中从Firestore获取数据-Flutter

[英]How to get data from Firestore in Scoped Model - Flutter

I'm trying to get data from Firestore, in debug print the future does it job and list gets data and in debugPrint length is +, but when I try to get data in another Widget list recives null, in debugPrint length is 0 . 我正在尝试从Firestore获取数据,将来在调试打印中会执行此操作,列表是否会获取数据,并且debugPrint的长度为+,但是当我尝试在另一个Widget列表中获取数据时会返回null,而debugPrint的长度为0。

model.dart 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 main.dart

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

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

statefullpage.dart 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);
  });
 }))),

Looks like the code you're written in main.dart is wrong. 看来您在main.dart中编写的代码是错误的。 The instatiated model is different from the one you've sent in your ScopedModel. 实例化的模型与您在ScopedModel中发送的模型不同。

Correction 更正

Change model: model to model: BBModel() in your main.dart file. 在main.dart文件model: BBModel() model: model更改 model: BBModel()

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

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

In main.dart, I would try doing: 在main.dart中,我将尝试执行以下操作:

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

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

note: "someVariableName" will contain a List< BB> 注意:“ someVariableName”将包含一个List <BB>

To wait you can use the 要等待,您可以使用

await model.getBBs();

Apart from this however, I do not recommend uploading data to the main, as you would slow down the use of the app, as the data is getting bigger. 但是除此之外,我不建议将数据上传到主目录,因为随着数据量的增加,您会降低应用程序的使用速度。 Upload the data only to the pages you need and find a way to do this. 仅将数据上传到您需要的页面,并找到一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM