简体   繁体   中英

How to make showDIalog wait for a function to finish first before building widget

So I'm trying to create a qr scanner feature, I manage to do all the function and functionality for the code, but when my code try to fetch the data the widget build run first resulting some data is null. How can I make the showDialog widget to wait for my function to be done first before moving on in building the data ?

Here's my code:

void getQRData() async {
    // Get User Data from ID
    print('qrcode: $qrcode');

    // Take the UserData[Number] to get user short data
    data = await UserDatabase.getUserShortData(
      userId: qrcode,
      phoneNumber: null,
    );

    print('data is : $data');

    await Future.forEach(
        Provider.of<ContactDataProvider>(context, listen: false)
            .getContactConnection
            .keys, (key) async {
      connectedContactData =
          Provider.of<ContactDataProvider>(context, listen: false)
              .getContactConnection[key];
      print(connectedContactData);
      if (connectedContactData['status'] == 'connected' ||
          connectedContactData['status'] == 'sent_req') {
        filteredId.add(connectedContactData['contact_uid']);
        print('filteredId: ${filteredId}');
      }
    });
  }
Container(
                  width: 250,
                  height: 250,
                  child: ScanView(
                    controller: scanController,
                    scanAreaScale: 0.8,
                    scanLineColor: Colors.red,
                    onCapture: (photoData) {
                      qrcode = photoData;
                      print('qrcode: $qrcode');

                      getQRData();

                      print(data);
                      
                      //ShowDialog Widget Code
                    },
                  ),
                ),

On the code above, my showDialog widget code run first before the getQRData() function is done. Resulting the widget is always error because the data is still null. Like what I just print

Firstly, convert getQRData method from void to future.

Future<void> getQRData() async {...}

Now on onCapture

 onCapture: (photoData) async {
       qrcode = photoData;
       await  getQRData(); 
       await showDialog(...);
     },

More about dart async-await

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