Home > database >  How to wait until datas are loaded?
How to wait until datas are loaded?

Time:10-18

I try to learn flutter and i face an issue with data loading. I get information from sqlite database to display them in my homepage. When starting my app, i have an error : LateInitializationError: Field 'child' has not been initialized.

  late MonneyServices monneyServices;
  late ChildDAO childDAO;
  late Child child;

  void initState() {
    super.initState();
    this.monneyServices = MonneyServices();
      monneyServices.getChild().then((Child child) {
      this.child = child;
      setState(() {});
    });

the getChild method is async

  Future<Child> getChild() async {
    //return Child(1, 'Alice2', 100);
    Child child = Child(1, 'A', 1);

    this.childDAO.insertChild(Child(1, "Alice", 10));
    List<Child> childList = await this.childDAO.getChilds();
    child = childList.first;
    print(childList.first);

    return child;
  }

I use so datas in
@override Widget build(BuildContext context)

How can i wait until datas are loaded ?

Thanks for your help

CodePudding user response:

You could use FutureBuilder.

It lets you to await for a future to complete and return a different widget according to the future status.

In your case you should use it in the build method and not in initState. You should use it more or less like so:

Widget build(BuildContext context) {
    return FutureBuilder<Widget>(context, snapshot){
        if(snapshot.hasData){ //If the future has completed
            return snapshot.data; //You return the widget it completed to
        } else {
            return CircularProgressIndicator(); //Otherwise, return a progress indicator
        }
    }
}

CodePudding user response:

you can use a boolean variable be sure the data is loaded and reflect this in the build

late MonneyServices monneyServices;
  late ChildDAO childDAO;
  late Child child;
  bool isLoading = true; // <--

  void initState() {
    super.initState();
    this.monneyServices = MonneyServices();
      monneyServices.getChild().then((Child child) {
      this.child = child;
      isLoading = false; // <--
      setState(() {});
    });

and in the build:

@override
Widget build(BuildContext context) {
  if(isLoading) {
    return Text('loading...');
  }
  return child;
}

another note , try to avoid use this in state class

  • Related