'Flutter FireBase - How can you asynchronously await verifyPhoneNumber?

I'm trying to implement phone authentication in my Flutter application using FirebaseAuth.instance.verifyPhoneNumber but do not know how to await it in an async function, so that the asynchronous codeSent parameter completes before moving on.

For example, with the following code:

ElevatedButton(
            onPressed: () async {
              await FirebaseAuth.instance.verifyPhoneNumber(
                phoneNumber: phoneNumber,
                verificationCompleted: (phoneAuthCredential) {},
                verificationFailed: (error) {},
                codeSent: (verificationId, forceResendingToken) async {
                  await Future.delayed(
                    Duration(seconds: 2),
                  );
                },
                codeAutoRetrievalTimeout: (verificationId) {},
              );
              print('COMPLETED');
            },
            child: Text('Verify'),
          ), 

I want the Future.delayed(Duration(seconds: 2)) to complete before the print statement. Is there any way of implementing this functionality? Am I missing something obvious?



Solution 1:[1]

If all you want is for Future.delayed(Duration(seconds: 2)) to be completed before the print statement, then call the print statement inside the codeSent method. Like this

codeSent: (String verificationId, [int? forceResendingToken]) async {
  await Future.delayed(const Duration(seconds: 2));
  print('COMPLETED');
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter O.