Auto-Read SMS with runtime permission - Flutter(Android)

Mukund Jogi
7Span
Published in
3 min readJul 8, 2022

Achieve Flutter auto read SMS or OTP with SMS Retriever API

Auto — Read SMS with Runtime Permission Flutter — Mukund Jogi

Hi Flutter Devs.

SMS Retriever API

With this API, SMS content will be automatically read by our app.

To implement a full SMS verification flow using the SMS User Consent API you need to interact with both a backend server to send the SMS as well as the SMS User Consent API to prompt the user for access to a single message containing a one-time code.

Step by step, your app and server must do the following to implement an SMS verification flow using the SMS User Consent API:

  1. Your app calls the SMS User Consent API to begin listening for an SMS response from the server. An SMS message received prior to starting SMS User Consent will not be forwarded to your app.
  2. After you start the SMS User Consent API, your app makes a request to a server to verify a user’s phone number using SMS verification.
  3. When the user’s device receives the SMS message containing a one-time code, Google Play services displays the contents of the message to the user and asks for consent to make that text available to your app.
  4. If the user consents, the entire SMS message is made available to your app.
  5. Your app parses out the one-time code from the message text and sends it to the server.

Setup android-side

At first, when a user tries to log in our system, we want to pick up the user phone number from mobile and send it to the server so that server can send an OTP SMS to that mobile number. We can manually input phone number in the EditText or show a picker by Google Auth API to fetch the phone number from associated google account. To do that, we need to add the dependency below.

Dependency to be added in pubspec.yaml

Initialising the smsUserConsent

In your file where you need to use try to not to listen the onReceive() in initState() as the build may get execute and you may miss to listen the onReceive(). You need to request the request OTP read using smsConsent after you complete API call for the request OTP.

Source : developers.google.com

So we finally achieved auto read SMS.

Thats all folks. Happy coding✌🏻

Connect me on Twitter and LinkedIn. Follow me here for more updates.

Keep learning and sharing. Thank you

--

--

Mukund Jogi
7Span
Writer for

Team Lead, Flutter and Android Developer at 7Span