Skip to content

fluo-dev/flutter-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fluo introduction

Fluo

Getting started

Add the package to your dependencies:

flutter pub add fluo

Add the FluoLocalizations.delegate to your app's localizationsDelegates:

MaterialApp(
  // ...other properties...
  localizationsDelegates: const [
    FluoLocalizations.delegate,
    // ...other delegates...
  ],
)

Use the Fluo SDK:

import 'package:fluo/fluo.dart';
import 'package:fluo/fluo_onboarding.dart';

FutureBuilder(
  // Get your api key from https://dashboard.fluo.dev (it's free)
  future: Fluo.init('YOUR_API_KEY'),
  builder: (context, snapshot) {
    // Check if Fluo is initialized.
    if (!Fluo.isInitialized) {
      return const Scaffold();
    }

    // Fluo is initialized. Check if the user is ready.
    if (!Fluo.instance.isUserReady()) {
      return FluoOnboarding(
        fluoTheme: FluoTheme.native(), // or FluoTheme.web()
        onUserReady: () => setState(() {}), // force build
      );
    }

    // User is ready!
    return ConnectedScreen(
      onSignOut: () async {
        await Fluo.instance.clearSession();
        setState(() {});
      },
    );
  },
)

For macOS, make sure you have networking allowed by adding this key to both {your-app}/macos/Runner/DebugProfile.entitlements and {your-app}/macos/Runner/Release.entitlements:

<dict>
	<!-- Add this key set to true -->
	<key>com.apple.security.network.client</key>
	<true/>
</dict>

More about the SDK

Below are the most important methods to know:

// Initialize the SDK
await Fluo.init('YOUR_API_KEY');

// Check if init is done
Fluo.isInitialized

// Check if user is ready (= valid session + valid user attributes)
Fluo.instance.isUserReady()

// Session management
Fluo.instance.hasSession()
await Fluo.instance.getAccessToken()
await Fluo.instance.refreshSession()
await Fluo.instance.clearSession()

// If you build your own connect screen (and don't use FluoOnboarding)
Fluo.instance.showConnectWithEmailFlow(/* ... */)
Fluo.instance.showConnectWithMobileFlow(/* ... */)
Fluo.instance.showConnectWithGoogleFlow(/* ... */)
Fluo.instance.showConnectWithAppleFlow(/* ... */)

// If you want to force show the registration steps
Fluo.instance.showRegisterFlow(/* ... */)

Integrating with Firebase

Select 'Firebase' for your backend. Once complete, when users are onboarded, Fluo forwards their info to:

  1. the Firebase Authentication service
  2. a users table created automatically in the Firestore Database (make sure the Firestore Database is initialized)

Back to your app code, to initialize correctly the Firebase session, use the Fluo.instance.session.firebaseToken as below:

// 1. Initialize the Firebase client somewhere in your code
// 2. Make sure Fluo is initialized and has a session
// 3. Use 'signInWithCustomToken' as shown below
if (Fluo.isInitialized) {
  final fluoSession = Fluo.instance.session;
  if (fluoSession != null) {
    final firebaseToken = fluoSession.firebaseToken!;
    await FirebaseAuth.instance.signInWithCustomToken(firebaseToken);
  }
}

Integrating with Supabase

Select 'Supabase' for your backend. Once complete, when users are onboarded, Fluo forwards their info to:

  1. the Supabase Authentication service
  2. a users table that you will create as part of the Supabase setup (no worries, it's a simple copy-paste)

Back to your app code, to initialize correctly the Supabase session, use the Fluo.instance.session.supabaseSession as below:

// 1. Initialize the Supabase client somewhere in your code
// 2. Make sure Fluo is initialized and has a session
// 3. Use 'recoverSession' as shown below
if (Fluo.isInitialized) {
  final fluoSession = Fluo.instance.session;
  if (fluoSession != null) {
    final supabaseSession = fluoSession.supabaseSession!;
    await Supabase.instance.client.auth.recoverSession(supabaseSession);
  }
}

Integrating with any backend

Select 'Custom' for your backend. The general idea is to use the JWT access token provided by Fluo. Once decoded (using your secret key), it provides the user info which you can store in your database.

Here is a full example to understand how it works:

  1. Wherever you need it, call Fluo.instance.getAccessToken() to get the JWT access token generated by Fluo and send it to your backend.
import 'package:http/http.dart' as http;

// Example of a function that gets a user. If the user
// doesn't exist yet, it should create it first.
Future<User> getOrCreateUser() async {
  final fluo = GetIt.instance<Fluo>();
  // This method returns an access token which is valid for
  // 1 hour and auto-refreshed using a single-use refresh token
  final accessToken = await Fluo.instance.getAccessToken();
  final response = await http.get(
    Uri.parse('https://your-backend.com/api/user/me'),
    headers: {
      'authorization': 'Bearer $accessToken',
    },
  );
  return User.fromJson(jsonDecode(response.body));
}
  1. In your backend, decode the access token to get the JWT payload. The payload contains the user id (sub) and email. Depending on your configuration, it may also contain the first name and last name.
const jwt = require("jsonwebtoken")

// This is your JWT secret key (do not share it with anyone)
const SECRET_KEY = "{jwtSecret}"

// Following on the example, here is the corresponding endpoint.
// Note that this is simplified and does not handle all edge cases.
app.get("/api/user/me", async (req, res) => {
  const accessToken = req.headers["authorization"].split(" ")[1]

  // Decode the access token using your secret key
  const payload = jwt.verify(accessToken, SECRET_KEY)

  // 'payload.sub' contains a unique user id generated by Fluo
  const userId = payload.sub

  // Find the user by id
  let user = await User.findOne({ id: userId })

  // If the user doesn't exist, create it
  if (!user) {
    user = await User.create({
      id: userId,
      email: payload.email,
      firstName: payload.firstName,
      lastName: payload.lastName,
    })
  }

  return res.status(200).json(user)
})
  1. If you need to go further, here is a complete example of the payload. For example, for increased security, you might want to verify that the token has not expired.
{
  "iat": 1744039599, // issued at
  "exp": 1744043199, // expires 1 hour after being issued
  "iss": "fluo.dev", // issuer
  "sub": "2rztxukf57pnjz9", // user id
  "email": "peter@marvel.com", // user email
  "firstName": "Peter", // user first name
  "lastName": "Parker", // user last name
}

Customizing the theme

Pass a FluoTheme to the FluoOnboarding component.

For iOS, Android, macOS

FluoOnboarding(
  // ...other properties...
  fluoTheme: FluoTheme.native(/* parameters */),
)

For web

FluoOnboarding(
  // ...other properties...
  fluoTheme: FluoTheme.web(/* parameters */),
)

Parameters

{
  Color? primaryColor,
  Color? inversePrimaryColor,
  Color? accentColor,
  EdgeInsets? screenPadding,
  ButtonStyle? connectButtonStyle,
  ButtonStyle? connectButtonStyleGoogle,
  ButtonStyle? connectButtonStyleApple,
  TextStyle? connectButtonTextStyle,
  TextStyle? connectButtonTextStyleGoogle,
  TextStyle? connectButtonTextStyleApple,
  double? connectButtonIconSize,
  Widget? connectButtonIconEmail,
  Widget? connectButtonIconMobile,
  Widget? connectButtonIconGoogle,
  Widget? connectButtonIconApple,
  TextStyle? legalTextStyle,
  EdgeInsets? legalTextPadding,
  TextStyle? modalTitleTextStyle,
  TextStyle? titleStyle,
  InputDecorationTheme? inputDecorationTheme,
  TextStyle? inputTextStyle,
  TextStyle? inputErrorStyle,
  TextAlignVertical? inputTextAlignVertical,
  ButtonStyle? nextButtonStyle,
  Size? nextButtonProgressIndicatorSize,
  Color? nextButtonProgressIndicatorColor,
  double? nextButtonProgressIndicatorStrokeWidth,
  EdgeInsets? countryItemPadding,
  Color? countryItemHighlightColor,
  TextStyle? countryTextStyle,
  PinTheme? codeInputThemeDefault,
  PinTheme? codeInputThemeFocused,
  PinTheme? codeInputThemeSubmitted,
  PinTheme? codeInputThemeFollowing,
  PinTheme? codeInputThemeDisabled,
  PinTheme? codeInputThemeError,
}