Skip to main content

Using Firebase with Web3Auth Flutter SDK

mobileflutterfirebasewhitelabelcustom authenticationdapp shareblockchainWeb3Auth Team | January 17, 2023

This guide will cover the basics of how to use the Web3Auth Flutter SDK in your Flutter application with Firebase and make blockchain calls to get access to user's account, fetch balance, sign transaction, and send transaction.

Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/flutter/flutter-firebase-example

Quick Start

npx degit Web3Auth/web3auth-pnp-examples/flutter/flutter-firebase-example w3a-flutter-firebase-demo
cd w3a-flutter-firebase-demo
# Open in Android Studio or VS Code
flutter run

How it works?

When integrating Web3Auth Flutter SDK with Social Login the flow looks something like this:

Web3Auth - Firebase Login Flow

  • When a user logs in with Firebase, Firebase sends a JWT id_token to the app. This JWT token is sent to the Web3Auth SDK's login function.

  • Finally, on successful validation of the JWT token, Web3Auth SDK will generate a private key for the user, in a self-custodial way, resulting in easy onboarding for your user to the application.

Prerequisites

  • For Web Apps: A basic knowledge of JavaScript is required to use Web3Auth SDK.

  • For Mobile Apps: For the Web3Auth Mobile SDKs, you have a choice between iOS, Android, React Native & Flutter. Please refer to the Web3Auth SDK Reference for more information.

  • Create a Web3Auth account on the Web3Auth Dashboard

  • Android API version 24 or newer.

  • For Android build: compileSdkVersion needs to be 34. Check android/app/build.gradle in your Flutter project to change it.

  • iOS 12+

  • Xcode 11.4+ / 12.x

  • Swift 4.x / 5.x

  • For iOS build: platform :ios needs to be 13.0. Check ios/Podfile in your Flutter project to change it.

  • A Firebase account to be used as Federated Identity Provider.

  • A Google Developer account to be used as Identity provider for Firebase.

Setup

Setup your Firebase Project

Create a Firebase Project

  • Create a new project by clicking on Add project or use your existing project from Firebase console.

    Firebase Project - Set up 1

  • Give your project a name and click on Continue

    Firebase Project - Set up 2

  • Finally, click on Create Project

    Firebase Project - Set up 3

Select Authentication Provider

  • Once the project is created. Set up authentication by clicking on the Authentication card from the home screen of your project or choose Authentication under Build from the left sidebar.

    Firebase Project - Set up auth 1

  • From Sign-in method tab, select any provider you wish to enanle. For the purpose of this guide, we'll be enabling Google.

    Firebase Project - Set up auth 2

  • Finally, toggle the enable button and click on Save

    Firebase Project - Set up auth 3

Configure Firebase for Flutter

  • Once the project is created and authentication is configured. Let's use Firebase for Android by clicking on the Flutter button on the home screen of your project.

    Firebase Project Flutter - Set up web 1

  • In the next screen, install the Firebase CLI and click on Next button.

    Firebase Project Flutter - Set up web 2

  • In the next screen, install and run the FLutterFire CLI.

    Firebase Project Flutter - Set up web 3

  • From any directory, run this command:

dart run global activate flutterfire.cli
  • Then, at the root of your Flutter project, run this command: replace the project name with yours.
flutterfire configure --project=your-project-name
  • In the Next screen, Initialize Firebase and add plugins.

    Firebase Project Flutter - Set up web 4

Setup your Web3Auth Dashboard

  • Create a Project from the Project Section of the Web3Auth Developer Dashboard.

    Plug n Play Project Creation on Web3Auth Dashboard

    • Enter your desired Project name.

    • Select the Product you want to use. For this guide, we'll be using the Plug n Play product.

    • Select the Platform type you want to use. For this guide, we'll be using the Flutter as the platform.

    • Select the Web3Auth Network as Sapphire Devnet. We recommend creating a project in the Sapphire Devnet network during development. While moving to a production environment, make sure to convert your project to Sapphire Mainnet or any of the legacy mainnet network Mainet, Aqua, or Cyan network. Otherwise, you'll end up losing users and keys.

    • Select the blockchain(s) you'll be building this project on. For interoperability with Torus Wallets, you have the option of allowing the user's private key to be used in other applications using Torus Wallets (EVM, Solana, XRPL & Casper).

    • Finally, once you create the project, you have the option to whitelist your URLs for the project. Please whitelist the domains where your project will be hosted.

      Plug n Play Project - Whitelist

  • Add {SCHEME}://{YOUR_APP_PACKAGE_NAME} (e.g, w3a://com.example.w3aflutter) for Android and {bundleId}://auth (e.g, com.example.w3aflutter://openlogin) for iOS in the Whitelist URL field of the Web3Auth Dashboard.
  • Create a Verifier from the Custom Auth Section of the Web3Auth Developer Dashboard with following configuration:

    • Choose a name of your choice for the verifier identifier. eg. w3a-firebase-verifier
    • Select environment: testnet, mainnet,aqua, or cyan as per your requirement.
    • Select Custom from the Login Provider.
    • Select Sub for the JWT Verifier ID.
    • Enter https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com as the JWK endpoint for Firebase's idToken.
    • JWT validation fields:
      • iss: https://securetoken.google.com/<firebase-project-id>.
      • aud: <firebase-project-id>
    • Click on Create button to create your verifier. It may take up to 10 minutes to deploy verifier on testnet. You'll receive an email once it's complete.

    Custom Authentication - Create Firebase Verifier

  • You will require the verifierName of the newly created verifier and clientId of the Plug and Play Project.

Using the Web3Auth SDK

To use the Web3Auth SDK, you need to add the dependency of the respective platform SDK of Web3Auth to your project. To know more about the available SDKs, please have a look at this documentation page.

For this guide, we will be using the Web3Auth Flutter SDK.

Installation

To install the web3auth_flutter package, you have two options. You can either manually add the package in the pubspec.yaml file, or you can use the flutter pub add command.

Add web3auth_flutter as a dependency to your pubspec.yaml.

dependencies:
web3auth_flutter: ^3.1.7

Add web3auth_flutter using flutter pub add command.

flutter pub add web3auth_flutter

Update compileSdkVersion

For Android build compileSdkVersion needs to be 34.

  • Check your app module gradle file in your project to change it.
android {
namespace "com.example.flutter_solana_example"
compileSdkVersion 34
ndkVersion flutter.ndkVersion

// ..
}

Add Web3Auth to Gradle

In your project-level gradle file add JitPack repository:

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io" } // <-- Add this line
}
}

Permissions

Open your app's AndroidManifest.xml file and add the following permission:

<uses-permission android:name="android.permission.INTERNET" />

Note: The <uses-permission> element must be a direct child of the <manifest> root element.

Configuration

Once the gradles and permission has been updated, we need to configure Web3Auth project by whitelisting you scheme and package name.

Configure a Plug n Play project
  • Go to Developer Dashboard, create or select a Web3Auth project.
  • Add {SCHEME}://{YOUR_APP_PACKAGE_NAME} to Whitelist URLs. eg. w3a://com.example.w3aflutter
  • Copy the Client ID from Project Details for initilization usage later.

Open your app's AndroidManifest.xml file and add the following deep link intent filter to your Main activity

<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="{scheme}" android:host="{YOUR_APP_PACKAGE_NAME}" android:path="/auth" />
<!-- Accept URIs: w3a://com.example.w3aflutter -->
</intent-filter>

Make sure your Main activity launchMode is set to singleTop in your AndroidManifest.xml

<activity
android:launchMode="singleTop"
android:name=".YourActivity">
// ...
</activity>

Initialization

After Installation, the next step to use Web3Auth is to Initialize the SDK. This can be achieved by using the init() function.

Please note that these are the most critical steps where you need to pass on different parameters according to the preference of your project. Additionally, Whitelabeling and Custom Authentication have to be configured within this step, if you wish to customise your Web3Auth Instance.

Create Web3Auth Instance

In your main.dart file, initialize the Web3AuthFlutter plugin at the very beginning such as in the overriden initState function

import 'dart:collection';
import 'dart:io';
import 'dart:async';

import 'package:web3auth_flutter/web3auth_flutter.dart';
import 'package:web3auth_flutter/enums.dart';
import 'package:web3auth_flutter/input.dart';
import 'package:web3auth_flutter/output.dart';


void initState() {
super.initState();
initPlatformState();
}

// Initialization
Future<void> initPlatformState() async {

Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
final loginConfig = HashMap<String, LoginConfigItem>();
loginConfig['jwt'] = LoginConfigItem(
verifier: "VERIFIER_NAME", // get it from web3auth dashboard
typeOfLogin: TypeOfLogin.jwt,
name: "Firebase JWT Login",
clientId: "WEB3AUTH_CLIENT_ID" // web3auth's plug and play client id
);

await Web3AuthFlutter.init(Web3AuthOptions(
clientId:'YOUR WEB3AUTH CLIENT ID FROM DASHBOARD',
network: Network.cyan,
redirectUri: redirectUrl,
loginConfig: loginConfig
));

await Web3AuthFlutter.initialize();
}

Read more about initializing the Flutter SDK here.

Authentication

Logging in

Once initialized, you can use the Web3AuthFlutter.login(LoginParams( loginProvider: Provider.google )) function to authenticate the user when they click the login button.

VoidCallback _login(Future<Web3AuthResponse> Function() method) {
return () async {
try {
final Web3AuthResponse response = await method();
setState(() {
_result = response.toString();
logoutVisible = true;
});
} on UserCancelledException {
print("User cancelled.");
} on UnKnownException {
print("Unknown exception occurred");
}
};
}

Future<Web3AuthResponse> _withFirebase() {
var idToken = "";
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: 'custom+jwt@firebase.login', password: 'Testing@123');
idToken = (await credential.user?.getIdToken(true)).toString();
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}

return Web3AuthFlutter.login(LoginParams(
loginProvider: Provider.jwt,
mfaLevel: MFALevel.OPTIONAL,
extraLoginOptions: ExtraLoginOptions(id_token: idToken, domain: 'firebase')
));
}

When connecting, the login function takes the LoginParams arguments for the login. See the LoginParams for more details.

Sample loginResponse

{
"privKey": "0ajjsdsd....",
"userInfo": {
"email": "w3a-heroes@web3auth.com",
"name": "Web3Auth Heroes",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"verifier": "torus",
"verifierId": "w3a-heroes@web3auth.com",
"typeOfLogin": "google",
"aggregateVerifier": "w3a-google-sapphire",
"dappShare": "", // 24 words of seed phrase will be sent only incase of custom verifiers
"idToken": "<jwtToken issued by Web3Auth>",
"oAuthIdToken": "<jwtToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"oAuthAccessToken": "<accessToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"isMfaEnabled": false // Returns whether the user has enabled MFA or not
},
"ed25519PrivKey": "666523652352635....",
"coreKitKey": "0xajjsdsd....",
"coreKitEd25519PrivKey": "666523652352635....",
"sessionId": "0xajjsdsd...."
}

Get the User Profile

// Assuming the user is logged in, get the user profile from the web3AuthResponse
userInfo = web3AuthResponse.userInfo

Using the web3AuthFlutter.login function, you can get the details of the logged in user. Please note that these details are not stored anywhere in Web3Auth network.

If you wish you add Multi Factor Authentication, use dApp Share or select Curve for your Android application, read the linked documentation.

Logout

VoidCallback _logout() {
return () async {
try {
await Web3AuthFlutter.logout();
setState(() {
_result = '<empty>';
logoutVisible = false;
});
} on UserCancelledException {
print("User cancelled.");
} on UnKnownException {
print("Unknown exception occurred");
}
};
}

Logging out your user is as simple as calling the web3AuthFlutter.logout() function.

UI in this guide


Widget build(BuildContext context) {
// Map<String, dynamic> user = jsonDecode(_result);

return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Web3Auth x Flutter Example'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Padding(
padding: EdgeInsets.all(8.0),
),
Visibility(
visible: !logoutVisible,
child: Column(
children: [
const Icon(
Icons.flutter_dash,
size: 80,
color: Color(0xFF1389fd),
),
const SizedBox(
height: 40,
),
const Text(
'Web3Auth',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 36,
color: Color(0xFF0364ff)),
),
const SizedBox(
height: 10,
),
const Text(
'Welcome to Web3Auth x Flutter Firebase Demo',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
const Text(
'Login with',
style: TextStyle(fontSize: 12),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: _login(_withFirebase),
child: const Text('Firebase')),
],
),
),
Visibility(
// ignore: sort_child_properties_last
child: Column(
children: [
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor:
Colors.red[600] // This is what you need!
),
onPressed: _logout(),
child: Column(
children: const [
Text('Logout'),
],
)),
),
],
),
visible: logoutVisible,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(_result),
)
],
)),
),
),
);
}

Interacting with the Blockchain

Blockchain calls

Checkout the full codes to interact with ETH Blockchain.

Get Account

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Get Account
ElevatedButton(
onPressed: () async {
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
debugPrint("Account, ${address.hexEip55}");
},
child: const Text('Get Address'),
),
])));
}

Get Balance

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Get Balance
ElevatedButton(
onPressed: () async {
final prefs = await SharedPreferences.getInstance();
final privateKey = prefs.getString('privateKey') ?? '0';
final credentials = EthPrivateKey.fromHex(privateKey);
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
final balance = await client.getBalance(address);
debugPrint("Balance, ${balance}");
},
child: const Text('Get Balance'),
),
])));
}

Send Transaction

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Send Transaction
ElevatedButton(
onPressed: () async {
final prefs = await SharedPreferences.getInstance();
final privateKey = prefs.getString('privateKey') ?? '0';
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
final receipt = await client.sendTransaction(
credentials,
Transaction(
from: address,
to: EthereumAddress.fromHex(
'0x809D4310d578649D8539e718030EE11e603Ee8f3'),
value: EtherAmount.fromUnitAndValue(
EtherUnit.gwei, 5000000), // 0.005 ETH
),
chainId: 5); // change chainId as per your chain.
debugPrint("Receipt, ${receipt}");
},
child: const Text('Send Transaction'),
),
])));
}

Example code

The code for the application we developed in this guide can be found in the Web3Auth Flutter Firebase Example. Check it out and try running it locally yourself!

flutter run

Also, check other examples:

Questions?

Ask us on Web3Auth's Community Support Portal