Skip to main content

How to use Web3Auth Flutter SDK

pnpflutterevmandroidiosWeb3Auth Team | September 13, 2022

This guide will cover the basics of how to use the Web3Auth Flutter SDK in your Flutter application 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-quick-start

Quick Start

npx degit Web3Auth/web3auth-pnp-examples/flutter/flutter-quick-start w3a-flutter-demo
cd w3a-flutter-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 Core - Social Login Flow

  • When a user logs in with Google, Google 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.

Setup

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.

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: ^5.0.4

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.app_name"
compileSdkVersion 34
// ..
}

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. Please make sure the <uses-permission> element should be a direct child of the <manifest> root element.

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

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 Web3Auth Developer Dashboard, and create or open an existing Web3Auth project.
  • Whitelist {SCHEME}://{YOUR_APP_PACKAGE_NAME} in the developer dashboard. This step is mandatory for the redirect to work.

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="/path" />
<!-- Accept URIs: w3a://com.example.w3aflutter -->
</intent-filter>

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

Future<void> initWeb3Auth() async {

late final Uri redirectUrl;

if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://auth
}


await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));

}

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> _withGoogle() {
return Web3AuthFlutter.login(LoginParams(
loginProvider: Provider.google,
mfaLevel: MFALevel.OPTIONAL,
));
}

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

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 Demo',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
const Text(
'Login with',
style: TextStyle(fontSize: 12),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: _login(_withGoogle),
child: const Text('Google')),
ElevatedButton(
onPressed: _login(_withFacebook),
child: const Text('Facebook')),
ElevatedButton(
onPressed: _login(_withEmailPasswordless),
child: const Text('Email Passwordless')),
ElevatedButton(
onPressed: _login(_withDiscord),
child: const Text('Discord')),
],
),
),
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 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