### Flutter Authentication Initialization and UI Example Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md This Dart code snippet demonstrates the full integration of flutter_better_auth. It includes initializing the SDK with a base URL, setting up the app's main widget with BetterAuthProvider, and building a UI with buttons for various authentication actions like email sign-in, getting the session, signing out, social sign-in (GitHub), and email sign-up. It uses Flutter's Material Design widgets and BetterAuthConsumer to access the authentication client. ```dart import 'package:flutter/material.dart'; import 'package:flutter_better_auth/flutter_better_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterBetterAuth.initialize( url: 'your_base_url/api/auth', ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return BetterAuthProvider( child: MaterialApp( title: 'BetterAuth', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'Better Auth'), ), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title), ), body: BetterAuthConsumer( builder: (context, client) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, spacing: 8, children: [ FilledButton( onPressed: () async { final result = await client.signIn.email( email: "test@mail.com", password: "123456788", ); if (result.data != null) { debugPrint(result.data.toString()); } else { debugPrint(result.error?.message); } }, child: Text("Sign-in"), ), FilledButton( onPressed: () async { final result = await client.getSession(); if (result.data != null) { debugPrint(result.data.toString()); } else { debugPrint(result.error?.message); } }, child: Text("GetSession"), ), FilledButton( onPressed: () { client.signOut(); }, child: Text("SignOut"), ), FilledButton( onPressed: () async { await client.signIn.social( provider: 'github', disableRedirect: true, callbackURL: "/auth-callback", callbackUrlScheme: "myapp", ); }, child: Text("Github"), ), FilledButton( onPressed: () async { final result = await client.signUp.email( name: "test", email: "test@mail.com", password: "123456788", ); if (result.data != null) { debugPrint(result.data.toString()); } else { debugPrint(result.error?.message); } }, child: Text("SignUp"), ), ], ), ); }, ), ); } } ``` -------------------------------- ### CMake Installation Rules for Application Bundle Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/CMakeLists.txt Defines the installation process for the Flutter application bundle. It sets the installation prefix, cleans the build bundle directory, and installs the main executable, ICU data, Flutter library, bundled plugin libraries, and native assets. It also handles the installation of the AOT library for non-Debug builds. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### CMake Installation Rules for Windows Executable Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/CMakeLists.txt Sets up installation rules for the application's executable and associated files on Windows. It configures the installation prefix, installs the executable, ICU data, Flutter library, bundled plugin libraries, native assets, and Flutter assets. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### CMake Project Setup and Executable Definition Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/runner/CMakeLists.txt Sets up the CMake build system for the project, defines the minimum required version, names the project, and specifies the application executable along with its source files. It also includes generated plugin registrant files. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) ``` -------------------------------- ### Initialize FlutterBetterAuth Client Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Initializes the FlutterBetterAuth client with the Better Auth server URL. This setup is crucial before utilizing any authentication features, as it configures the HTTP client for cookie management and session persistence. ```dart import 'package:flutter/material.dart'; import 'package:flutter_better_auth/flutter_better_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize with your Better Auth server URL await FlutterBetterAuth.initialize( url: 'https://your-api.com/api/auth', ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return BetterAuthProvider( child: MaterialApp( title: 'My App', home: const HomePage(), ), ); } } ``` -------------------------------- ### Manage User Profiles and Account Deletion with Dart Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Provides examples for updating user profile information, changing email addresses, and deleting user accounts. Utilizes the flutter_better_auth package. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; // Update user profile Future updateProfile() async { final client = FlutterBetterAuth.client; final result = await client.updateUser( name: 'Jane Doe', image: 'https://example.com/avatar.jpg', ); if (result.data?.status == true) { print('Profile updated successfully'); } } // Change email Future changeEmail() async { final client = FlutterBetterAuth.client; final result = await client.changeEmail( newEmail: 'newemail@example.com', callbackURL: 'https://myapp.com/verify-new-email', ); if (result.data?.status == true) { print('Verification email sent to new address'); } } // Delete user account Future deleteAccount() async { final client = FlutterBetterAuth.client; final result = await client.deleteUser( password: 'currentPassword123', // Required for confirmation callbackURL: 'https://myapp.com/account-deleted', ); if (result.data?.success == true) { print('Account deleted'); } } ``` -------------------------------- ### Session Management with Flutter Better Auth Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Provides functionality to retrieve, list, and manage user sessions. Sessions contain user information, authentication tokens, and metadata. This includes getting the current session, listing all sessions for a user, and revoking sessions. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future manageSession() async { final client = FlutterBetterAuth.client; // Get current session final sessionResult = await client.getSession(); if (sessionResult.data != null) { final session = sessionResult.data!.session; final user = sessionResult.data!.user; print('Session ID: ${session.id}'); print('Expires at: ${session.expiresAt}'); print('User: ${user.name} (${user.email})'); print('Email verified: ${user.emailVerified}'); } // List all sessions for current user final sessionsResult = await client.listSessions(); if (sessionsResult.data != null) { for (final session in sessionsResult.data!) { print('Session: ${session.id}'); print(' IP: ${session.ipAddress}'); print(' User Agent: ${session.userAgent}'); print(' Created: ${session.createdAt}'); } } // Revoke other sessions (keep current) await client.revokeOtherSessions(); // Revoke all sessions await client.revokeSessions(); } ``` -------------------------------- ### Configure Flutter Library and Headers (CMake) Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/flutter/CMakeLists.txt Sets up the Flutter library and its associated header files. It defines variables for the library path, ICU data file, and project build directory, making them available to parent scopes for installation. It also appends necessary header files to a list and configures an INTERFACE library for Flutter. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### CMake Project Setup and Build Configuration Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/CMakeLists.txt Configures the minimum CMake version, project name, executable name, and build types (Debug, Profile, Release). It handles multi-configuration generators and sets default build types. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) set(BINARY_NAME "example") cmake_policy(VERSION 3.14...3.25) get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Social Authentication with Flutter Better Auth Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Handles user authentication via social providers like GitHub, Google, or Apple. Supports both OAuth redirect flow and ID token authentication. For OAuth, ensure `flutter_web_auth_2` is installed. ID token authentication is recommended for security. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; // OAuth redirect flow (requires flutter_web_auth_2) Future signInWithGitHub() async { final client = FlutterBetterAuth.client; final result = await client.signIn.social( provider: 'github', disableRedirect: true, callbackURL: '/auth-callback', callbackUrlScheme: 'myapp', // Custom URL scheme for deep linking scopes: 'user:email', ); if (result.data != null) { print('GitHub auth successful'); print('User: ${result.data!.user?.name}'); } } // ID Token authentication (recommended) Future signInWithIdToken() async { final client = FlutterBetterAuth.client; final result = await client.signIn.social( provider: 'google', idToken: SocialIdTokenBody( token: 'google_id_token_here', accessToken: 'optional_access_token', ), ); if (result.data != null) { print('Google sign in successful'); } } ``` -------------------------------- ### Initialize FlutterBetterAuth in main.dart Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md Demonstrates how to import the necessary packages and initialize the FlutterBetterAuth client in your application's main entry point. Ensure `WidgetsFlutterBinding.ensureInitialized()` is called before initializing the auth client with your API URL. ```dart import 'package:flutter/material.dart'; import 'package:flutter_better_auth/flutter_better_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterBetterAuth.initialize(url: 'api_url'); runApp(const MyApp()); } ``` -------------------------------- ### Email Sign Up for New Users Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Registers new users by collecting their name, email, and password. An optional callback URL can be provided for email verification purposes. The function returns data about the created user upon successful registration. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future signUpWithEmail() async { final client = FlutterBetterAuth.client; final result = await client.signUp.email( name: 'John Doe', email: 'newuser@example.com', password: 'securePassword123', callbackURL: 'https://myapp.com/verify-email', // Optional ); if (result.data != null) { final response = result.data!; print('Account created for: ${response.user.name}'); print('Email verified: ${response.user.emailVerified}'); } else { print('Registration failed: ${result.error?.message}'); } } ``` -------------------------------- ### Import and Use FlutterBetterAuth Plugins Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md Illustrates how to import specific plugins like admin, phone, email OTP, and JWT from the `flutter_better_auth` package. Once imported, these plugins can be accessed directly through the client instance. ```dart import 'package:flutter_better_auth/plugins/admin/admin_plugin.dart'; import 'package:flutter_better_auth/plugins/phone/phone_plugin.dart'; import 'package:flutter_better_auth/plugins/email_otp/email_otp_plugin.dart'; import 'package:flutter_better_auth/plugins/jwt/jwt_plugin.dart'; // Example usage: // client.phone // client.admin // client.emailOtp // client.jwt ``` -------------------------------- ### Send and Verify Email Verification Tokens with Dart Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Demonstrates how to send verification emails to users and verify their email addresses using a token. Requires the flutter_better_auth package. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; // Send verification email Future sendVerificationEmail() async { final client = FlutterBetterAuth.client; final result = await client.sendVerificationEmail( email: 'user@example.com', callbackURL: 'https://myapp.com/verify', ); if (result.data?.status == true) { print('Verification email sent'); } } // Verify email with token Future verifyEmail(String token) async { final client = FlutterBetterAuth.client; final result = await client.verifyEmail( token: token, callbackURL: 'https://myapp.com/verified', ); if (result.data != null) { print('Email verified: ${result.data!.user.emailVerified}'); } } ``` -------------------------------- ### Wrap MaterialApp with BetterAuthProvider Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md Shows how to wrap your root `MaterialApp` widget with `BetterAuthProvider`. This makes the authentication services available throughout your widget tree. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return BetterAuthProvider( child: MaterialApp( title: 'BetterAuth', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'Better Auth'), ), ); } } ``` -------------------------------- ### Manage Social Accounts with Flutter Better Auth Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Demonstrates how to link, unlink, and manage social provider accounts for authenticated users using Flutter Better Auth. It covers listing accounts, linking new ones, unlinking existing accounts, and retrieving or refreshing access tokens. This functionality requires the Flutter Better Auth client to be initialized. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future manageSocialAccounts() async { final client = FlutterBetterAuth.client; // List linked social accounts final accountsResult = await client.social.listAccounts(); if (accountsResult.data != null) { for (final account in accountsResult.data!) { print('Provider: ${account.providerId}'); print('Account ID: ${account.accountId}'); } } // Link a new social account final linkResult = await client.social.link( provider: 'google', callbackURL: 'https://myapp.com/link-callback', scopes: 'email profile', ); // Unlink a social account await client.social.unlink( providerId: 'google', accountId: 'google-account-id', ); // Get access token for a linked provider final tokenResult = await client.social.getAccessToken( providerId: 'google', ); if (tokenResult.data != null) { print('Provider Access Token: ${tokenResult.data!.accessToken}'); } // Refresh provider access token final refreshResult = await client.social.refreshToken( providerId: 'google', ); } ``` -------------------------------- ### Configure Trusted Origins for Better Auth Server Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md This TypeScript code demonstrates how to configure the trustedOrigins for your Better Auth server. It's essential to include your callback URL scheme (e.g., 'YOUR_CALLBACK_URL_SCHEME_HERE://') in this list to allow communication between your client and server during the authentication flow. ```typescript export const auth = betterAuth({ trustedOrigins: ["YOUR_CALLBACK_URL_SCHEME_HERE://"] }) ``` -------------------------------- ### Add flutter_better_auth Dependency Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md Instructions for adding the flutter_better_auth package to your Flutter project. This can be done via the `flutter pub add` command or by manually updating the `pubspec.yaml` file. ```sh flutter pub add flutter_better_auth ``` ```yaml dependencies: flutter_better_auth: ``` -------------------------------- ### Admin User Management with Flutter Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Provides administrative functions for managing users, roles, and sessions. Requires admin privileges and the `admin_plugin`. Supports creating, updating, banning, and listing users. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; import 'package:flutter_better_auth/plugins/admin/admin_plugin.dart'; Future adminOperations() async { final client = FlutterBetterAuth.client; // Create a new user final createResult = await client.admin.createUser( name: 'New User', email: 'newuser@example.com', password: 'initialPassword123', role: 'user', // Optional role ); if (createResult.data != null) { print('User created: ${createResult.data!.user.id}'); } // Set user role await client.admin.setRole( userId: 'user-id-here', role: 'admin', ); // Ban a user await client.admin.banUser( userId: 'user-id-here', banReason: 'Violation of terms', banExpiresIn: '30d', // Optional expiration ); // Unban a user await client.admin.unBanUser(userId: 'user-id-here'); // List all users final usersResult = await client.admin.listUsers(); // Impersonate a user (for debugging) final impersonateResult = await client.admin.impersonateUser( userId: 'user-id-here', ); // Stop impersonating await client.admin.stopImpersonating(userId: 'user-id-here'); // Remove a user await client.admin.removeUser(userId: 'user-id-here'); // Set user password (admin override) await client.admin.setUserPassword( userId: 'user-id-here', newPassword: 'newPassword123', ); // Check permissions final permResult = await client.admin.hasPermission( permissions: {'admin': true, 'write': true}, ); print('Has permission: ${permResult.data?.success}'); } ``` -------------------------------- ### Email and Password Sign In Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Handles user authentication using email and password credentials. It returns a Result object that indicates success with session data or failure with an error message and code. The 'rememberMe' option can be used to persist the session. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future signInWithEmail() async { final client = FlutterBetterAuth.client; final result = await client.signIn.email( email: 'user@example.com', password: 'securePassword123', rememberMe: 'true', // Optional: persist session ); switch (result) { case Success(data: final response): print('Signed in successfully!'); print('User ID: ${response.user.id}'); print('User Name: ${response.user.name}'); print('Session Token: ${response.session.token}'); break; case Failure(error: final error): print('Sign in failed: ${error.message}'); print('Error code: ${error.code}'); break; } } ``` -------------------------------- ### Phone Authentication with OTP Verification using Dart Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Shows how to authenticate users via phone number using OTP. This functionality requires importing the phone plugin from flutter_better_auth. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; import 'package:flutter_better_auth/plugins/phone/phone_plugin.dart'; // Send OTP to phone number Future sendPhoneOTP() async { final client = FlutterBetterAuth.client; final result = await client.phone.sendOtp( body: PhoneBody(phoneNumber: '+1234567890'), ); if (result.data != null) { print('OTP sent successfully'); } } // Verify phone number Future verifyPhone(String otp) async { final client = FlutterBetterAuth.client; final result = await client.phone.verify( body: VerifyPhoneBody( phoneNumber: '+1234567890', code: otp, ), ); if (result.data != null) { print('Phone verified for: ${result.data!.user.name}'); } } // Sign in with phone number Future signInWithPhone(String otp) async { final client = FlutterBetterAuth.client; final result = await client.phone.signIn( body: SignInPhoneBody( phoneNumber: '+1234567890', code: otp, ), ); if (result.data != null) { print('Signed in via phone'); } } // Reset password via phone Future resetPasswordViaPhone() async { final client = FlutterBetterAuth.client; await client.phone.requestPasswordResetOTP( body: PhoneBody(phoneNumber: '+1234567890'), ); // After receiving OTP await client.phone.restPassword( body: ResetPhonePasswordBody( phoneNumber: '+1234567890', code: '123456', newPassword: 'newPassword123', ), ); } ``` -------------------------------- ### Configure Flutter Tool Backend Command (CMake) Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/flutter/CMakeLists.txt Sets up a custom command to execute the Flutter tool backend. It defines a phony output file to ensure the command runs every time and specifies the command to execute with environment variables and arguments. This command generates necessary Flutter library files and wrapper sources. ```cmake # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### Username and Password Sign In Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Authenticates users using their username and password. This method provides an alternative to email-based sign-in. It returns user information upon successful login or an error message if authentication fails. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future signInWithUsername() async { final client = FlutterBetterAuth.client; final result = await client.signIn.username( username: 'johndoe', password: 'securePassword123', rememberMe: 'true', ); if (result.data != null) { print('Welcome back, ${result.data!.user.displayUsername}!'); } else { print('Login failed: ${result.error?.message}'); } } ``` -------------------------------- ### Email OTP Authentication with Flutter Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Handles user authentication using email-based one-time passwords. Supports sending verification codes, signing in, verifying emails, and resetting passwords. Requires the `email_otp_plugin`. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; import 'package:flutter_better_auth/plugins/email_otp/email_otp_plugin.dart'; // Send verification OTP Future sendEmailOTP() async { final client = FlutterBetterAuth.client; final result = await client.emailOtp.sendVerification( email: 'user@example.com', type: 'sign-in', // or 'sign-up', 'forget-password' ); if (result.data?.success == true) { print('OTP sent to email'); } } // Sign in with email OTP Future signInWithEmailOTP(String otp) async { final client = FlutterBetterAuth.client; final result = await client.emailOtp.signIn( email: 'user@example.com', otp: otp, ); if (result.data != null) { print('Signed in: ${result.data!.user.name}'); } } // Verify email with OTP Future verifyEmailWithOTP(String otp) async { final client = FlutterBetterAuth.client; final result = await client.emailOtp.verifyEmail( email: 'user@example.com', otp: otp, ); if (result.data != null) { print('Email verified'); } } // Reset password with email OTP Future resetPasswordWithOTP() async { final client = FlutterBetterAuth.client; // Request OTP await client.emailOtp.forgotPassword(email: 'user@example.com'); // Reset with OTP final result = await client.emailOtp.resetPassword( email: 'user@example.com', otp: '123456', password: 'newSecurePassword', ); if (result.data?.success == true) { print('Password reset successful'); } } ``` -------------------------------- ### CMake Standard Settings and Application ID Definition Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/runner/CMakeLists.txt Applies standard build settings to the application target and adds preprocessor definitions for the application ID. This ensures consistent build configurations and proper identification of the application. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the application ID. add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") ``` -------------------------------- ### Access BetterAuthClient with BetterAuthConsumer Widget Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Demonstrates how to use the BetterAuthConsumer widget to access the BetterAuthClient instance within the Flutter widget tree. This allows for easy retrieval of session data and other authentication-related operations. ```dart import 'package:flutter/material.dart'; import 'package:flutter_better_auth/flutter_better_auth.dart'; class AuthPage extends StatelessWidget { const AuthPage({super.key}); @override Widget build(BuildContext context) { return BetterAuthConsumer( builder: (context, client) { return Column( children: [ ElevatedButton( onPressed: () async { final result = await client.getSession(); if (result.data != null) { print('User: ${result.data!.user.name}'); } }, child: const Text('Get Session'), ), ], ); }, ); } } // Alternative: Access client directly without widget final client = FlutterBetterAuth.client; ``` -------------------------------- ### CMake Library Linking and Include Directories Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/runner/CMakeLists.txt Links necessary libraries, including the Flutter engine and GTK, to the application target. It also specifies the include directories for the project, allowing the compiler to find header files. ```cmake # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Build C++ Wrapper Libraries (CMake) Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/flutter/CMakeLists.txt Defines static C++ wrapper libraries for Flutter plugins and applications. It lists core, plugin, and application-specific source files, applies standard build settings, and configures properties like position-independent code and visibility. It also links against the Flutter library and sets include directories. ```cmake # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) ``` -------------------------------- ### JWT Token Operations with Flutter Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Facilitates access to JWT tokens and JSON Web Key Sets (JWKS) for token verification and refresh. Requires the `jwt_plugin`. Allows fetching the current access token and retrieving JWKS for validation. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; import 'package:flutter_better_auth/plugins/jwt/jwt_plugin.dart'; Future jwtOperations() async { final client = FlutterBetterAuth.client; // Get JWT token final tokenResult = await client.jwt.token(); if (tokenResult.data != null) { print('Access Token: ${tokenResult.data!.token}'); } // Get JWKS (JSON Web Key Set) for token verification final jwksResult = await client.jwt.jwks(); if (jwksResult.data != null) { for (final key in jwksResult.data!.keys) { print('Key ID: ${key.kid}'); print('Algorithm: ${key.alg}'); } } } ``` -------------------------------- ### Configure Android Manifest for Flutter Web Auth Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md This XML snippet shows how to update your AndroidManifest.xml to handle callback URLs for flutter_web_auth_2. Ensure you replace YOUR_CALLBACK_URL_SCHEME_HERE with your actual callback URL scheme. This is crucial for receiving authentication responses from social providers. ```xml ... ... ``` -------------------------------- ### CMake Custom Command for Flutter Tool Backend Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/flutter/CMakeLists.txt Defines a custom CMake command to execute the Flutter tool backend script. This command is triggered by the `flutter_assemble` custom target and is designed to run every time due to the use of a non-existent output file `_phony_`. It sets up the environment variables and passes build parameters to the `tool_backend.sh` script. ```cmake # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### Access FlutterBetterAuth Client Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/README.md Provides two methods for accessing the BetterAuth client instance. You can use `BetterAuthConsumer` to access the client within its builder function, or directly access the static `FlutterBetterAuth.client` property. ```dart BetterAuthConsumer( builder: (context, client) { return Widget(); } ) ``` ```dart final client = FlutterBetterAuth.client; ``` -------------------------------- ### CMake Project Configuration and Settings Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/CMakeLists.txt Defines the minimum CMake version, project name, executable name, and application ID. It also sets modern CMake policies and configures library paths for bundled libraries. This section establishes the foundational settings for the build. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) set(BINARY_NAME "example") set(APPLICATION_ID "ts.mila.better_auth.example") cmake_policy(SET CMP0063 NEW) set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Configure CMake for Flutter Application Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/windows/runner/CMakeLists.txt This CMake script sets up the build environment for a Flutter application. It specifies the minimum CMake version, defines the project, and adds the executable target. It also includes necessary source files, applies standard build settings, and adds preprocessor definitions for the build version. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"" ) target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### CMake Custom Function for List Prepending Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/flutter/CMakeLists.txt Defines a custom CMake function `list_prepend` to add a prefix to each element of a list. This is a workaround for older CMake versions (pre-3.10) that lack the `list(TRANSFORM ... PREPEND ...)` command. It takes the list name and the prefix as arguments and modifies the list in the parent scope. ```cmake function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() ``` -------------------------------- ### CMake Target Properties for Runtime Output Directory Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/CMakeLists.txt Configures the runtime output directory for the main executable (`${BINARY_NAME}`). It places the executable in a subdirectory named `intermediates_do_not_run` within the binary directory to prevent accidental execution of unbundled copies. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Anonymous Sign In with Flutter Better Auth Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Creates anonymous user sessions for users who have not yet registered. This method is useful for providing a temporary session before a user decides to fully register. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; Future signInAnonymously() async { final client = FlutterBetterAuth.client; final result = await client.signIn.anonymous(); if (result.data != null) { print('Anonymous session created'); print('Is Anonymous: ${result.data!.user.isAnonymous}'); print('User ID: ${result.data!.user.id}'); } } ``` -------------------------------- ### Password Management with Flutter Better Auth Source: https://context7.com/tsiresymila1/flutter_better_auth/llms.txt Handles password reset flows and password changes for authenticated users. This includes requesting a password reset email, resetting a password using a token, and changing the password for the currently logged-in user. ```dart import 'package:flutter_better_auth/flutter_better_auth.dart'; // Request password reset email Future forgotPassword() async { final client = FlutterBetterAuth.client; final result = await client.forgotPassword( email: 'user@example.com', redirectTo: 'https://myapp.com/reset-password', ); if (result.data != null) { print('Password reset email sent'); } } // Reset password with token Future resetPassword(String token) async { final client = FlutterBetterAuth.client; final result = await client.resetPassword( newPassword: 'newSecurePassword456', token: token, ); if (result.data?.status == true) { print('Password reset successfully'); } } // Change password for authenticated user Future changePassword() async { final client = FlutterBetterAuth.client; final result = await client.changePassword( currentPassword: 'oldPassword123', newPassword: 'newPassword456', revokeOtherSessions: 'true', // Optional: logout other devices ); if (result.data != null) { print('Password changed successfully'); } } ``` -------------------------------- ### CMake Dependency and Library Configuration for Flutter Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/flutter/CMakeLists.txt Configures system-level dependencies for Flutter on Linux using PkgConfig to find GTK, GLIB, and GIO libraries. It sets paths for the Flutter library and ICU data file, defines header files, and creates an interface library target named 'flutter' with appropriate include directories and link libraries. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### CMake Flutter and Dependency Integration Source: https://github.com/tsiresymila1/flutter_better_auth/blob/main/example/linux/CMakeLists.txt Includes the Flutter managed directory and finds the GTK+ 3.0 library using PkgConfig. It also adds the 'runner' subdirectory for application-specific build rules and declares a dependency on `flutter_assemble` for the main binary. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_subdirectory("runner") add_dependencies(${BINARY_NAME} flutter_assemble) ```