Friday, 20 September 2019

My Experience - Authentication with Flutter and Firebase

I set out to create a working minimal example. Just a basic form with username and password fields and submit button. On submit, display a message if logged in OR the error message returned by firebase. These are the steps I followed with the help of the flutter and firebase documentation.

Install Flutter (flutter_windows_v1.9.1+hotfix.2-stable)


https://flutter.dev/
https://flutter.dev/docs/get-started/install/windows

Unzip and copy flutter folder ( D:\coding\flutter is what I chose )
Add bin folder to User variables > Path in Windows


Next, command to check for platform dependencies

D:\Coding\flutter> flutter doctor

I needed Android toolchain, Android Studio, VS Code extension, Connected device (optional)

Install Android studio (3.5 for Windows 64-bit - android-studio-ide-191.5791312-windows)


https://developer.android.com/studio

I selected Custom and additionally checked Android Virtual Device



Open AVD Manager from Android Studio > Tools
Create a device in AVD Manager


Create a starter Flutter app


https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-ap

I called mines - myapp

Create a login form


https://flutter.dev/docs/cookbook/forms

Username, password and submit button


Create firebase project


https://firebase.google.com/docs/flutter/setup

You will be asked for your package name. Mines was package="com.example.myapp" from D:\Coding\myapp\android\app\src\main\AndroidManifest.xml

Modify Flutter app

Once the project is created in firebase, you are given a google-services.json file to download and add to your flutter app.

The link (last one from above) also shows you how to modify both build.gradle files. For me those are in these folders.

D:\Coding\myapp\android
D:\Coding\myapp\android\app

I paid attention to this line - Ensure that your app is not currently running in your emulator or on your device.

I also needed to add dependencies to pubspec.ymal. To get the latest version of those I checked on https://pub.dev/ and this is what I added

firebase_core: ^0.4.0+9
firebase_auth: ^0.14.0+5

This is all the firebase code I needed after the submit button is clicked

FirebaseAuth.instance
.signInWithEmailAndPassword(
email: username.text,
password: password.text)
.then((currentUser) => Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Logged in .. ' + username.text))))
.catchError((err) => Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Unable to login .. ' + err.toString()))));

Don't forget the import statement

import 'package:firebase_auth/firebase_auth.dart';

Make sure your virtual device is connected to the internet. For me that meant changing the DNS server to Google's DNS server - 8.8.8.8 and 8.8.4.4 else I would get Token retrieval failed: AUTHENTICATION_FAILED and dns probe finished bad config.

And this is the result where you see the different messages displayed



No comments: