beax07
beax07

Reputation: 11

Download data before build - method

I want to build a contactScreen for my flutter app with an array downloaded from firebase. The array is correctly downloaded, but while building the app the array stays empty. With some tests (the print-statements) I figured out, that the app builds the screen and at the same time download the data (with getUserData()). So the download is not fast enough. (After a reload everything works fine).

@override
void initState() {
 super.initState();
 getUserData();
 print(contacts);
}

getUserData() async {
 var userData = await FirebaseFirestore.instance
    .collection('users')
    .doc(currentUser)
    .get();
  print(userData.data()!['contacts']);
  contacts = userData.data()!['contacts'];
}

Is it possible to download the data before the build method every time? I can't use the straembuilder because it's already in use for another download.

Upvotes: 0

Views: 36

Answers (1)

Anas Nadeem
Anas Nadeem

Reputation: 907

create a variable bool isLoading = true

getUserData() {
    //await retrieve data
    //after data is retrieved
    setState(() {
        isLoading = false;
    });
}

In your build method:

isLoading ? Container(child: Text('Loading...')) : YourScreen()

Upvotes: 1

Related Questions