简体   繁体   中英

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 .

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

Looks like the code you're written in main.dart is wrong. The instatiated model is different from the one you've sent in your ScopedModel.

Correction

Change model: model to model: BBModel() in your main.dart file.

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

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

In main.dart, I would try doing:

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

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

note: "someVariableName" will contain a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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