Google search engine
Home Blog Page 8

Dependency Injection in Flutter: A Comprehensive Guide

0

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table of Contents:

Introduction

What is Dependency Injection?

The Concept of Injection

Why Use Dependency Injection in Flutter?

Approaches to Dependency Injection in Flutter

Advantages of Implementing Dependency Injection

Which Approach Should You Choose?

Conclusion

References


Introduction

Dependency Injection (DI) is a software design pattern used to increase modularity, improve testability, and manage dependencies efficiently. In Flutter, DI plays a crucial role in separating concerns and ensuring scalable application architecture.

In this guide, we’ll explore the core concepts of DI, its benefits, and how to implement it in Flutter using different approaches, including Provider, GetIt, and Riverpod.


What is Dependency Injection?

Dependency Injection is a technique where an object receives its dependencies from an external source rather than creating them itself. This helps in better managing the lifecycle of objects and makes unit testing easier.

For example, instead of creating an instance of a service class inside a widget, we inject it from an external source.


The Concept of Injection

Dependency injection is a programming technique that makes our code more maintainable by decoupling the dependencies of a class. The primary goal of dependency injection is to provide a class with its dependencies, rather than having the class create these dependencies itself. This way, we can manage dependencies in a more maintainable way, making our code easier to test and modify.

In Flutter, we implement dependency injection by passing instances of dependencies into the class that needs them. This could be done through the constructor (constructor injection), a method (method injection), or directly into a field (field injection).

class DataRepository {
final DataService _dataService;

DataRepository(this._dataService);

Future<String> fetchData() => _dataService.fetchData();
}

Why Use Dependency Injection in Flutter?

So, why should you use Dependency Injection in your Flutter app? Here are some compelling reasons:

  • Loose Coupling: Dependency Injection helps reduce coupling between components, making it easier to modify or replace individual components without affecting the entire app.
  • Testability: With DI, you can easily mock dependencies, making it easier to write unit tests and ensure your app’s reliability.
  • Flexibility: DI allows you to swap out dependencies with alternative implementations, making it easier to adapt to changing requirements.
  • Reusability: By decoupling components, you can reuse code more effectively, reducing duplication and improving maintainability.

Approaches to Dependency Injection in Flutter

Flutter provides multiple ways to implement Dependency Injection. The most commonly used methods are:

  1. Constructor Injection
  2. InheritedWidget (Flutter’s built-in DI)
  3. Provider (Recommended by Flutter)
  4. GetIt (Service Locator)
  5. Riverpod (Modern alternative to Provider)

1. Constructor Injection

The simplest form of DI, where dependencies are passed through a constructor.

class ApiService {
void fetchData() {
print("Fetching data...");
}
}

class HomeScreen {
final ApiService apiService;

HomeScreen(this.apiService);

void loadData() {
apiService.fetchData();
}
}

void main() {
ApiService apiService = ApiService();
HomeScreen homeScreen = HomeScreen(apiService);
homeScreen.loadData();
}

2. InheritedWidget (Manual DI Management)

Flutter’s built-in InheritedWidget allows passing dependencies down the widget tree.

class DependencyProvider extends InheritedWidget {
final ApiService apiService;

DependencyProvider({required Widget child})
: apiService = ApiService(),
super(child: child);

static DependencyProvider of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DependencyProvider>()!;
}

@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) => false;
}

3. Provider (Recommended by Flutter Team)

Provider is a simple state management solution that also works as a Dependency Injection tool.

Installation

Add provider to pubspec.yaml:

dependencies:
provider: ^6.0.5

Implementation

class ApiService {
void fetchData() {
print("Fetching data using Provider...");
}
}

void main() {
runApp(
MultiProvider(
providers: [
Provider(create: (context) => ApiService()),
],
child: MyApp(),
),
);
}

class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final apiService = Provider.of<ApiService>(context, listen: false);
apiService.fetchData();
return Container();
}
}

4. GetIt (Service Locator Pattern)

GetIt is a popular DI framework for Flutter that allows easy access to services.

Installation

Add get_it to pubspec.yaml:

dependencies:
get_it: ^7.2.0

Implementation

final getIt = GetIt.instance;

void setupDependencies() {
getIt.registerSingleton<ApiService>(ApiService());
}

void main() {
setupDependencies();
runApp(MyApp());
}

class HomeScreen extends StatelessWidget {
final ApiService apiService = getIt<ApiService>();

@override
Widget build(BuildContext context) {
apiService.fetchData();
return Container();
}
}

5. Riverpod (Modern Alternative to Provider)

Riverpod improves upon Provider by eliminating context dependency.

Installation

Add flutter_riverpod to pubspec.yaml:

dependencies:
flutter_riverpod: ^2.1.3

Implementation

final apiServiceProvider = Provider((ref) => ApiService());

class HomeScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final apiService = ref.watch(apiServiceProvider);
apiService.fetchData();
return Container();
}
}

Advanced Dependency Injection Techniques

1. Using Environment-Specific Dependencies

Many apps require different dependencies based on the environment (e.g., dev, staging, production). Using DI, we can manage these configurations efficiently.

void setupDependencies(String environment) {
if (environment == "production") {
getIt.registerSingleton<ApiService>(ProductionApiService());
} else {
getIt.registerSingleton<ApiService>(MockApiService());
}
}

2. Modular DI for Large-Scale Applications

For enterprise-level applications, using a modular DI approach helps in breaking dependencies into separate modules.

abstract class AppModule {
void registerDependencies();
}

class CoreModule implements AppModule {
@override
void registerDependencies() {
getIt.registerSingleton<ApiService>(ApiService());
}
}

Advantages of Implementing Dependency Injection

Dependency injection brings several benefits to our Flutter projects. It makes our code more flexible and modular, as we can easily swap out different implementations of the same class without changing the class that uses the dependency. This is particularly useful when we want to use different dependencies in different environments, such as development, staging, and production environments.

Dependency injection also makes our code easier to test. We can inject mock implementations of dependencies during testing, allowing us to isolate the class under test and ensure it’s working correctly.

Finally, dependency injection can improve the performance of our Flutter applications. By using a service locator like GetIt, we can manage singleton classes, ensuring that only one instance of a class is created and reused throughout our app.


Which Approach Should You Choose?

  • Use Provider if you want a simple and Flutter-recommended solution.
  • Use GetIt if you prefer a Service Locator approach with global access.
  • Use Riverpod for a modern DI and state management solution.
  • Use InheritedWidget for small-scale apps without extra dependencies.
  • Use Constructor Injection for basic DI needs with minimal dependencies.

Conclusion

Dependency Injection in Flutter helps maintain clean architecture, improve testability, and enhance modularity. By using Provider, GetIt, or Riverpod, you can manage dependencies efficiently and build scalable applications. Choose the DI approach that best fits your project’s needs.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


References:

Implementing Dependency Injection in Flutter
Know about dependency injection and the popular Flutter packages that help manage dependencies. Also see how to…www.dhiwise.com

Communicating between layers
How to implement dependency injection to communicate between MVVM layers.docs.flutter.dev

https://30dayscoding.com/blog/building-flutter-apps-with-darts-dependency-injection


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
 And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Streamlining Payments In Flutter

In today’s digital world, having a fast, secure, and user-friendly payment system is essential for any app. Whether you’re building an e-commerce store, subscription service, or on-demand platform, integrating a streamlined payment solution ensures higher conversions and better user experience.

Flutter, being one of the most powerful cross-platform frameworks, offers multiple ways to integrate payments smoothly. This guide will walk you through everything you need to know about streamlining payments in Flutter

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents:

What is Streamlining Payment?

Why Optimized Payment Processing Matters?

Selecting the Right Payment Plugin

Simple Payment Gateway Integration in Flutter

Challenges in Payment Integration

Performance Optimization in Streamlined Payment

The Future of Streamlined Payments in Flutter

Conclusion

Reference 


1. What is Streamlining Payment?

Streamlining payments refers to optimizing the payment flow by reducing friction, enhancing security, and improving speed. A streamlined payment system ensures users can complete transactions quickly with minimal manual input.

Instead of traditional, slow, and error-prone payment methods, streamlined payments use modern techniques like one-tap payments, digital wallets, auto-fill, and biometric authentication to improve user experience.


2. Why Optimized Payment Processing Matters?

A well-implemented payment system offers the following advantages:

  • Reduced Checkout Time: Minimizes steps and friction during the payment process.
  • Enhanced User Experience: Ensures a seamless transaction flow.
  • Increased Conversion Rates: Reduces cart abandonment due to failed or complicated transactions.
  • Improved Security and Compliance: Adheres to industry standards, mitigating fraud and data breaches.

Advantages and Considerations of Streamlining Payments

Advantages

  • Faster Checkout: Reduces cart abandonment by enabling quick and efficient transactions.
  • Enhanced User Experience: Provides a seamless and intuitive payment flow, improving customer satisfaction.
  • Lower Failure Rates: Optimized for mobile transactions, reducing payment failures and errors.
  • Multi-Platform Support: Works efficiently across Android, iOS, and Web platforms.
  • Secure & PCI Compliant: Uses advanced encryption and tokenization to protect sensitive payment data.

Considerations

  • Higher Integration Effort: Requires additional backend optimizations and compliance with payment gateway requirements.
  • Gateway Limitations: Some payment providers, such as PayPal, charge higher transaction fees, which may impact overall costs.
  • Dependency on Third-Party Providers: Businesses must rely on payment service providers like Stripe, Razorpay, or PhonePe, which may introduce platform-specific constraints.
  • Security Risks: Requires robust fraud detection and security mechanisms to prevent unauthorized transactions.

Despite these challenges, streamlining payments significantly enhances conversion rates, user trust, and overall business efficiency.

How is it Different from Traditional Payment Methods


3. Selecting the Right Payment Plugin

Integrating a payment gateway in a Flutter app is not just about adding a checkout button — it directly affects user experience, security, compliance, and app performance. Developers must consider several critical factors before selecting a payment plugin.

1. Platform Compatibility

Key Considerations:

  • Does the plugin support Android, iOS, and Web?
  • Does it require native SDKs or additional dependencies?
  • Is desktop compatibility required for Windows/macOS apps?

Impact:

  • Ensures a seamless payment experience across devices.
  • Reduces the need for separate implementations per platform.
  •  Some plugins may not support Web or desktop, limiting accessibility.

2. Supported Payment Methods

Key Considerations:

  • Credit/Debit Cards (Visa, Mastercard, Amex)
  • UPI (for India-focused apps)
  • Digital Wallets (Google Pay, Apple Pay, PayPal)
  • Net Banking & Bank Transfers
  • Buy Now Pay Later (BNPL) & EMI options

Impact:

  • Increases conversion rates by offering users their preferred payment methods.
  • Supports regional preferences (e.g., UPI for India, PayPal for international users).
  • Limited payment options can lead to higher cart abandonment.

3. Security and Compliance

Key Considerations:

  • Does the plugin support PCI-DSS compliance for handling card transactions?
  • Is tokenization and encryption used to secure data?
  • Compliance with GDPR, RBI guidelines (India), PSD2 (EU), CCPA (California)

Impact:

  • Protects users from fraud and unauthorized transactions.
  • Builds trust by ensuring compliance with regulatory laws.
  • Non-compliant gateways can result in legal issues or penalties.
  • Security breaches can cause reputational and financial damage.

4. Performance and Optimization

Key Considerations:

  • Transaction speed — How quickly does the payment process complete?
  • Async API calls — Does it prevent UI freezes and improve responsiveness?
  • Caching support — Can frequently used payment methods be stored securely for faster transactions?

Impact:

  • Faster transactions enhance user experience and reduce drop-offs.
  • Background processing ensures a smooth, non-blocking UI.
  • Slow processing or UI freezes can cause user frustration and abandoned checkouts.

5. Pricing & Fees

Key Considerations:

  • Transaction fees per payment method (e.g., Stripe charges ~2.9% per transaction)
  • Are there setup fees, API call limits, or hidden costs?
  • Does the gateway offer a free-tier or sandbox mode for testing?

Impact:

  • Helps businesses optimize costs by choosing a cost-effective provider.
  • Understanding transaction fees avoids unexpected expenses.
  • High transaction fees can reduce profit margins, especially for small businesses.

6. API Stability and Documentation

Key Considerations:

  • Is the API well-documented and frequently updated?
  • Does it provide sample projects and SDKs for Flutter?
  • How responsive is developer support?

Impact:

  • Faster integration with clear documentation and ready-to-use code.
  • Reduces development time and debugging effort.
  • Poor documentation can lead to implementation errors and delays.

7. Integration Complexity

Key Considerations:

  • Does the plugin require a backend setup (e.g., Stripe needs server-side processing)?
  • Are there pre-built UI components for quick integration?
  • Does the gateway support no-code/low-code solutions?

Impact:

  •  Simple integration speeds up development time.
  • Backend-heavy solutions offer more control but increase complexity.
  • Complex integrations require additional server-side development, increasing costs.

8. Selecting the Right Plugin Based on Target Market

Key Considerations:

  • For global applications, Stripe or PayPal provides extensive support for international transactions.
  • For India-based payments, Razorpay, Paytm, and PhonePe offer better support for local payment methods such as UPI.
  • For fast mobile transactions, Google Pay and Apple Pay offer near-instant payment processing.

Impact:

  • Using region-specific payment solutions improves acceptance rates.
  • Localized payment methods enhance user convenience.
  • Wrong selection can result in low success rates for transactions.

9. Payment Methods & Features

  • Need recurring payments? → Stripe, Braintree support subscriptions.
  • Want one-tap payments? → Google Pay, Apple Pay enable instant transactions.
  • Looking for UPI transactions? → Razorpay, PhonePe are ideal.

Impact:

  • Allows businesses to offer seamless and flexible payment options.
  • One-tap payments boost conversion rates and reduce friction.
  • Lack of essential features can hinder app usability and user retention.

Flutter offers multiple payment plugins that help developers integrate payment gateways efficiently.


4. Simple Payment Gateway Integration in Flutter

Each payment plugin requires different setup steps and dependencies. Below is a basic breakdown of what developers need to integrate each plugin effectively.

1. Flutter Stripe (flutter_stripe)

Requirements:

  • Stripe account & API keys
  • Backend setup for Payment Intents
  • PCI-DSS compliance for card transactions

Integration Complexity: Moderate (requires backend)

Setup Steps:

  1. Add dependency in pubspec.yaml
dependencies:
flutter_stripe: ^11.4.0

2. Initialize Stripe in main.dart

import 'package:flutter_stripe/flutter_stripe.dart';

void main() {
Stripe.publishableKey = "your_publishable_key";
runApp(MyApp());
}

3. Create Payment Intent (Server-Side)

  • Call Stripe’s API to generate a client secret
  • Use that client secret to confirm payment

Backend (Node.js example)

const stripe = require("stripe")("your_secret_key");

app.post("/create-payment-intent", async (req, res) => {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000, // Amount in cents
currency: "usd",
});
res.json({ clientSecret: paymentIntent.client_secret });
});

4. Confirm the payment using the client secret

Future<void> processPayment() async {
try {
final paymentIntent = await fetchPaymentIntentFromServer();
await Stripe.instance.confirmPayment(
paymentIntentClientSecret: paymentIntent['clientSecret'],
params: PaymentMethodParams.card(paymentMethodData: PaymentMethodData()),
);
} catch (e) {
print("Payment failed: $e");
}
}

Read the below link for more details

flutter_stripe – Dart API docs
flutter_stripe API docs, for the Dart programming language.pub.dev

Best For: Global businesses handling secure card transactions


2. Razorpay (razorpay_flutter)

Requirements:

  • Razorpay merchant account
  • API keys for client-side payments
  • Server integration for order creation

Integration Complexity: Easy (minimal backend required)

Setup Steps:

  1. Add razorpay_flutter dependency
dependencies:
razorpay_flutter: ^1.4.0

2. Initialize the Razorpay SDK

import 'package:razorpay_flutter/razorpay_flutter.dart';

Razorpay _razorpay = Razorpay();

void initPayment() {
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
}

3. Create Payment Order (Server-Side)

  • Use Razorpay’s API to generate an order ID

4. Open Payment Gateway

void startPayment() {
var options = {
'key': 'your_api_key',
'amount': 1000, // In paisa (10 INR)
'name': 'Your Business',
'description': 'Test Payment',
'prefill': {'contact': '1234567890', 'email': 'user@example.com'}
};
_razorpay.open(options);
}

void _handlePaymentSuccess(PaymentSuccessResponse response) {
print("Payment successful: ${response.paymentId}");
}

void _handlePaymentError(PaymentFailureResponse response) {
print("Payment failed: ${response.message}");
}

void _handleExternalWallet(ExternalWalletResponse response) {
print("External wallet used: ${response.walletName}");
}

Read the below link for more details

Integrate With Flutter Standard SDK
Integrate the Razorpay Flutter Standard plugin with our native Android and iOS SDKs.razorpay.com

Best For: India-based apps with UPI, wallets, and net banking support


3. PhonePe (phonepe_payment_sdk)

Requirements:

  • PhonePe merchant account
  • API key & secret key
  • Approval for PhonePe API access

Integration Complexity: Moderate (requires API approval)

Setup Steps:

  1. Add phonepe_payment_sdk dependency
dependencies:
phonepe_payment_sdk: ^3.0.0

2. Initialize the PhonePe SDK

import 'package:phonepe_payment_sdk/phonepe_payment_sdk.dart';

PhonePePaymentSDK.instance.initialize(
environment: Environment.PRODUCTION,
appId: "your_app_id",
merchantId: "your_merchant_id",
);

3. Create a payment request with transaction details

final response = await PhonePePaymentSDK.instance.startTransaction(
request: PhonePePaymentRequest(
transactionId: "txn123456",
amount: 10000,
callbackUrl: "your_callback_url",
),
);

4. Process UPI payments via PhonePe app

 /**
* This method is called to get list of upi apps in @Android only.
* Return: String
* JSON String -> List of UPI App with packageName, applicationName & versionCode
* NOTE :- In iOS, it will throw os error at runtime.
*/
static Future<String?> getInstalledUpiAppsForAndroid()

Read the below link for more details

https://developer.phonepe.com/category/v1/hybrid-sdk-android-and-ios/flutter-sdk-integration

Best For: UPI-first apps in India needing fast transactions


4. PayPal (flutter_paypal_payment)

Requirements:

  • PayPal business account
  • Client ID and Secret Key
  • Server-side integration for advanced payments

Integration Complexity: Moderate (requires PayPal setup)

Setup Steps:

  1. Add flutter_paypal_payment dependency
dependencies:
flutter_paypal_payment: ^1.0.0

2. Configure PayPal credentials in the app

import 'package:flutter_paypal_payment/flutter_paypal_payment.dart';

void startPayPalPayment(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PaypalCheckout(
sandboxMode: true,
clientId: "your_client_id",
secretKey: "your_secret_key",
transactions: [
{
"amount": {
"total": '10.00',
"currency": "USD",
},
},
],
),
),
);
}

Read the below link for more details

Initialize the SDK
Learn how to create and integrate scalable PayPal checkout solutions for web and mobile applications.developer.paypal.com

Best For: International businesses & freelancers accepting PayPal payments


5. Pay Plugin (pay)

Requirements:

  • Google Pay / Apple Pay account
  • Payment configuration JSON file
  • No backend required for basic payments

Integration Complexity: Very Easy (no backend required)

Setup Steps:

  1. Add pay dependency
dependencies:
pay: ^3.1.0

2. Create Payment Configuration JSON Files

Google Pay Configuration (assets/google_pay.json)

{
"provider": "google_pay",
"data": {
"environment": "TEST",
"apiVersion": 2,
"apiVersionMinor": 0,
"allowedPaymentMethods": [
{
"type": "CARD",
"parameters": {
"allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
"allowedCardNetworks": ["MASTERCARD", "VISA"]
},
"tokenizationSpecification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:publishableKey": "your_publishable_key",
"stripe:version": "2023-01-01"
}
}
}
],
"merchantInfo": {
"merchantName": "Example Merchant"
},
"transactionInfo": {
"totalPriceStatus": "FINAL",
"totalPrice": "99.99",
"currencyCode": "USD"
}
}
}

Apple Pay Configuration (assets/apple_pay.json)

{
"provider": "apple_pay",
"data": {
"merchantIdentifier": "merchant.com.example",
"displayName": "Example Merchant",
"merchantCapabilities": ["3DS"],
"supportedNetworks": ["visa", "masterCard"],
"countryCode": "US",
"currencyCode": "USD",
"paymentItems": [
{
"label": "Total",
"amount": "99.99"
}
]
}
}

3. Initialize Google Pay / Apple Pay in Flutter

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:pay/pay.dart';

void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}

4. Implement Payment Buttons & Payment Flow

//Define Payment Items

const _paymentItems = [
PaymentItem(
label: 'Total',
amount: '99.99',
status: PaymentItemStatus.final_price,
),
];

//Load Payment Configurations

Future<String> loadPaymentConfig(String filePath) async {
return await rootBundle.loadString(filePath);
}

//Google Pay Button Implementation

FutureBuilder<String>(
future: loadPaymentConfig('assets/google_pay.json'),
builder: (context, snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return GooglePayButton(
paymentConfiguration: PaymentConfiguration.fromJsonString(snapshot.data!),
paymentItems: _paymentItems,
type: GooglePayButtonType.buy,
margin: const EdgeInsets.only(top: 15.0),
onPaymentResult: onGooglePayResult,
loadingIndicator: const Center(child: CircularProgressIndicator()),
);
},
);

//Apple Pay Button Implementation

FutureBuilder<String>(
future: loadPaymentConfig('assets/apple_pay.json'),
builder: (context, snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return ApplePayButton(
paymentConfiguration: PaymentConfiguration.fromJsonString(snapshot.data!),
paymentItems: _paymentItems,
style: ApplePayButtonStyle.black,
type: ApplePayButtonType.buy,
margin: const EdgeInsets.only(top: 15.0),
onPaymentResult: onApplePayResult,
loadingIndicator: const Center(child: CircularProgressIndicator()),
);
},
);

Read the below link for more details

Google Pay introduces a Flutter plugin for payments
Share Posted by Jose Ugia, Developer Programs Engineer, Google Pay and Anthony Panissidi, Technical Writer, Google…developers.googleblog.com

Best For: Quick mobile wallet payments without backend setup


5. Challenges in Payment Integration

Even with streamlined payments, developers face the following challenges:

1. Security Risks

  • Fraud detection & prevention mechanisms must be implemented.
  • Use tokenization and encryption to protect card details.

2. Compatibility Issues

  • Some plugins may not support older Android/iOS versions.
  • Testing is required across different devices.

3. Regulatory Compliance

  • Ensure compliance with PCI-DSS and local banking regulations.
  • GDPR and data privacy laws must be considered.

4. Handling Payment Failures

  • Implement retry mechanisms for network failures.
  • Provide clear user feedback on payment status.

6. Performance Optimization in Streamlined Payment

Optimizing the payment flow and reducing transaction latency are crucial for enhancing user experience and minimizing payment failures. Below are key strategies to optimize performance in Flutter-based payment systems.

Optimizing Payment Flow

  • Use Batch Processing for Bulk Transactions: Reduces the number of API requests, improving efficiency for businesses handling multiple transactions at once.
  • Minimize Request Size: Compress and optimize payloads to reduce response time and enhance processing speed.
  • Enable One-Click Checkout: Allow users to save payment methods for future use, significantly reducing checkout time.
  • Reduce Form Fields: Minimize the number of required fields to speed up the checkout process without compromising security.
  • Implement Biometric Authentication: Utilize Face ID or fingerprint recognition for secure and seamless transactions, eliminating the need for manual input.

Reducing Latency

  • Securely Store Payment Method Tokens: Save user payment credentials securely to enable faster subsequent transactions.
  • Use Asynchronous API Calls: Prevent UI freezes by handling payment requests asynchronously, ensuring smooth user interactions.
  • Implement Caching for Frequently Used Payment Methods: Reduce redundant API calls by caching previously used payment methods for quick access.
  • Offload Payment Processing to Backend Servers: Handle payment validations and processing on secure backend servers instead of the client-side to enhance performance and security.

By implementing these optimizations, developers can ensure that their Flutter payment integration is fast, reliable, and efficient, leading to better user retention and a lower payment failure rate.


7. The Future of Streamlined Payments in Flutter

As digital transactions evolve, payment systems in Flutter apps will become more intelligent, secure, and seamless. Here are some emerging trends shaping the future of payments:

1. AI-Powered Fraud Detection

 What’s Changing?

  • AI-driven fraud detection will analyze transaction patterns in real-time to detect anomalies.
  • Machine Learning (ML) models will help prevent fraudulent transactions before they occur.

 Impact:

  • Reduces chargebacks and financial losses for businesses.
  • Enhances user trust and security with instant risk assessment.

Example:
 Stripe Radar uses AI to prevent fraud in real-time transactions.

2. Crypto & Decentralized Payments

What’s Changing?

  • Cryptocurrencies like Bitcoin, Ethereum, and stablecoins will be integrated into payment gateways.
  • Decentralized Finance (DeFi) will reduce reliance on banks, making global transactions easier.

 Impact:

  • Lower transaction fees compared to traditional payment gateways.
  • Enables borderless transactions with fast settlements.

Example:
 PayPal & Stripe are exploring crypto payments for seamless transactions.

3. Real-Time Global Payment Systems (UPI Expansion)

What’s Changing?

  • Unified Payments Interface (UPI) has transformed digital payments in India with instant money transfers.
  • More countries are adopting real-time payment solutions similar to UPI.

Impact:

  • Faster, low-cost global transactions without card dependencies.
  • Boosts financial inclusion for unbanked populations.

Example: India’s UPI expansion to Europe, the UAE, and the USA is gaining momentum.

4. Voice & Biometric-Based Payments

What’s Changing?

  • Users will soon authorize payments using voice commands, facial recognition, and fingerprint scans.
  • AI-powered voice assistants like Siri, Google Assistant, and Alexa will enable hands-free payments.

Impact:

  • Enhances accessibility and convenience.
  • Provides higher security through biometric authentication.

Example: Apple Pay & Google Pay already support facial and fingerprint authentication.


8. Conclusion

A streamlined payment flow is essential for enhancing user experience, improving transaction success rates, and boosting revenue. By choosing the right Flutter payment plugin, developers can create a fast, secure, and user-friendly checkout process.

Key Takeaways:

  • Google Pay & Apple Pay (pay plugin): Ideal for mobile-first apps needing a quick and secure wallet-based payment solution.
  • Razorpay & PhonePe: Best for UPI, net banking, and card transactions, especially for India-focused apps.
  • Stripe & PayPal: Suitable for global businesses requiring secure card payments and international transactions.
  • Best Practices: Optimizing performance, ensuring PCI-DSS compliance, reducing latency, and handling payment failures effectively.

By following best practices and addressing integration challenges, developers can build a smooth, reliable, and secure payment experience in Flutter apps.

Need help integrating a specific payment method in Flutter? Let’s discuss in the comments!

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


9. Reference

Google Pay introduces a Flutter plugin for payments
Share Posted by Jose Ugia, Developer Programs Engineer, Google Pay and Anthony Panissidi, Technical Writer, Google…developers.googleblog.com

flutter_stripe – Dart API docs
flutter_stripe API docs, for the Dart programming language.pub.dev

https://developer.phonepe.com/category/v1/hybrid-sdk-android-and-ios/flutter-sdk-integration

Initialize the SDK
Learn how to create and integrate scalable PayPal checkout solutions for web and mobile applications.developer.paypal.com

Integrate With Flutter Standard SDK
Integrate the Razorpay Flutter Standard plugin with our native Android and iOS SDKs.razorpay.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Convert String & Number To Byte Array In Flutter & Dart

0

This blog will explore the Convert String & Number To Byte Array In Flutter & Dart. We perceive how to execute a demo program. We will show you how to convert a string or a number to a byte array in your Dart and Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Converting a String into a Byte Array

Converting a Number into a Byte Array

Conclusion



Converting a String into a Byte Array:

There is more than one method for transforming a given string into a byte array in Dart.

> Using the utf8.encode() method:
The utf8.encode() technique can be imported from Dart: convert takes a string and returns a list of UTF-8 bytes.

The code:

import 'dart:convert';

void main() {
String text = 'FlutterDevs.com';
List<int> bytes = utf8.encode(text);
print(bytes);
}

When we run the application, we ought to get the screen’s output like the underneath screen Console Output.

[70, 108, 117, 116, 116, 101, 114, 68, 101, 118, 115, 46, 99, 111, 109]

Process finished with exit code 0
  • > Using the codeUnits property of the String class:
    The codeUnits property of the String class returns a list of UTF-16 code units.

The code:

void main() {
String text = 'FlutterDevs.com';
List<int> bytes = text.codeUnits;
print(bytes);
}

When we run the application, we ought to get the screen’s output like the underneath screen Console Output.

[70, 108, 117, 116, 116, 101, 114, 68, 101, 118, 115, 46, 99, 111, 109]

Process finished with exit code 0
  • > Using the runes property of the String class:
    The runes property gives you an iterable of Unicode code points of a string.

The code:

void main() {
String text = 'FlutterDevs.com Welcome you';
Iterable<int> bytes = text.runes;

List<int> list = bytes.toList();
print(list);
}

When we run the application, we ought to get the screen’s output like the underneath screen Console Output.

[70, 108, 117, 116, 116, 101, 114, 68, 101, 118, 
115, 46, 99, 111, 109, 32, 87, 101, 108, 99, 111,
109, 101, 32, 121, 111, 117]

Process finished with exit code 0

Converting a Number into a Byte Array:

To convert a number over entirely to a byte array, you can initially change it over completely to a string and afterward utilize one of the methodologies referenced in the past section to get the job done.

The code:

import "dart:convert";

void main() {
int myInt = 2023;
print(utf8.encode(myInt.toString()));

double myDouble = 7.4235;
print(utf8.encode(myDouble.toString()));
}

When we run the application, we ought to get the screen’s output like the underneath screen Console Output.

[50, 48, 50, 51]
[55, 46, 52, 50, 51, 53]

Process finished with exit code 0

Conclusion:

In the article, I have explained the Convert String & Number To Byte Array In Flutter & Dart; you can modify this code according to your choice. This was a small introduction to Convert String & Number To Byte Array In Flutter & Dart User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Convert String & Number To Byte Array In Flutter & Dart of your projects. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Using Firebase with Flutter: A Complete Guide

0

If you’re looking for the best Flutter app development company for your mobile application, then feel free to contact us at — support@flutterdevs.com.

Table of Contents:

Introduction

Why Use Firebase with Flutter?

Prerequisites

Steps to Follow

Setting Up Firebase Project

Setting Up Firebase in Your Flutter App

Firebase Authentication

Firestore Database

Firebase Storage

Firebase Functions (Optional)

Conclusion

References


Introduction

Firebase is an excellent backend service that allows you to add features such as user authentication, real-time databases, file storage, and serverless cloud functions to your Flutter apps. In this comprehensive guide, we will walk you through how to integrate Firebase with your Flutter app, covering Firebase Authentication, Firestore, Firebase Storage, and Firebase Functions.

Why Use Firebase with Flutter?

Firebase is one of the most popular backend-as-a-service platforms, and integrating it with Flutter can offer numerous benefits for developers. Firebase simplifies the process of adding complex features to your app while providing reliable and scalable backend services. Here’s why you should consider using Firebase with Flutter:

1. Fast and Easy Integration

Firebase offers a straightforward integration process for Flutter. With well-documented SDKs and a FlutterFire plugin (the official Flutter SDK for Firebase), Firebase enables you to quickly add backend services to your app, whether you’re building a simple app or a complex one. You don’t need to spend time setting up and maintaining your own backend servers.

  • FlutterFire SDK: The FlutterFire plugins are designed specifically for Flutter, making the integration between Firebase and Flutter seamless and developer-friendly.
  • Extensive Documentation: Firebase has excellent documentation and examples for Flutter, making it easier for developers to implement Firebase features.

2. Real-Time Database and Firestore

Firebase provides two main database solutions: Firebase Realtime Database and Cloud Firestore. Both are scalable, serverless databases that automatically sync data across all connected clients in real-time.

  • Cloud Firestore: It’s the next-generation database from Firebase, offering more advanced features, such as more powerful querying capabilities and a more flexible data structure.
  • Real-time Updates: Firebase automatically syncs data in real-time, making it ideal for apps that need live updates, such as social media apps, messaging apps, or live sports scores.

3. Authentication Made Easy

Firebase Authentication supports multiple authentication methods, including:

  • Email/Password Authentication (easy to set up)
  • Social Logins (Google, Facebook, Twitter, etc.)
  • Phone Authentication (SMS-based login)
  • Anonymous Authentication (to allow users to use your app without full login)

Firebase handles most of the complex security and user management tasks for you, including:

  • Password hashing
  • Session management
  • Security rules

This allows developers to focus more on building the app’s features and less on implementing authentication protocols.

4. Scalable and Secure Cloud Storage

Firebase provides Firebase Storage, a powerful service for storing user-generated content such as images, videos, and documents. Firebase Storage integrates seamlessly with Firebase Authentication, allowing you to control who has access to the files you store.

  • Automatic scaling: Firebase Storage is designed to scale automatically without requiring you to manage the infrastructure.
  • Security: Firebase Storage allows you to define access control rules, ensuring that users can only access files that they are authorized to view.
  • Integration with Firestore: You can easily store file URLs in Firestore and link them with other user data.

5. Serverless Backend with Firebase Functions

Firebase Functions allows you to write backend code that responds to events triggered by Firebase features or HTTPS requests without managing any server infrastructure. This is a huge benefit for developers who want to avoid setting up and maintaining their server-side code.

  • Event-driven Functions: Firebase Functions can respond to events from Firestore, Firebase Authentication, Firebase Realtime Database, and more.
  • Custom Logic: You can write custom server-side logic for tasks like sending notifications, processing payments, or triggering workflows.
  • Scaling Automatically: Firebase Functions scale automatically based on demand, which means they are perfect for apps that need to handle varying workloads.

6. Cloud Messaging

Firebase Cloud Messaging (FCM) allows you to send push notifications and messages to users, even when the app is in the background or closed. This is essential for user engagement in mobile applications, allowing you to send personalized updates, reminders, or promotional offers.

  • Push Notifications: Send targeted messages to specific user segments.
  • Cross-Platform: Firebase Cloud Messaging supports both Android and iOS, allowing you to send notifications to users on both platforms from a single API.

7. Analytics and Crash Reporting

Firebase provides Firebase Analytics, a powerful tool for tracking user interactions within your app. It helps you understand how users engage with your app, what features are most popular, and how users behave across different devices and platforms.

  • Firebase Crashlytics: Firebase also includes Crashlytics, a real-time crash reporting tool that helps you monitor and resolve issues in your app. With it, you can see exactly where the crash occurred and gather data on how many users were affected.
  • Real-Time Analytics: Firebase Analytics provides real-time insights into app usage, helping you make data-driven decisions to improve your app’s performance and user experience.

8. Easy Deployment and Hosting

Firebase Hosting allows you to deploy your web app (or even static assets like HTML, CSS, and JavaScript) to the cloud with a single command. It’s fast, secure, and scalable, making it perfect for Flutter web apps.

  • Global CDN: Firebase Hosting is backed by a content delivery network (CDN) that serves your content globally with low latency.
  • Simple Hosting: You can deploy static content with ease, and Firebase provides SSL by default, ensuring your content is served securely.

9. Pay As You Go Model

Firebase offers a pay-as-you-go model, which means you only pay for the services you use. The Firebase Free Tier offers generous limits, so you can get started with most features without incurring any costs. As your app scales and your user base grows, you can upgrade to a paid plan, which offers additional resources and greater capacity.

  • Scalable Pricing: Firebase’s pricing model is flexible, so you can scale as your app grows.
  • No Infrastructure Management: Since Firebase is fully managed, you don’t need to worry about maintaining servers, scaling infrastructure, or patching security issues.

10. Cross-Platform Compatibility

Firebase is designed to work seamlessly with both Android and iOS apps. The same Firebase project can be used across platforms, and the APIs are consistently designed, allowing you to focus on building cross-platform Flutter apps rather than worrying about platform-specific configurations.

  • Unified Platform: Firebase’s consistent APIs across Android, iOS, and Web mean you can build a truly cross-platform app.
  • FlutterFire Plugin: The official FlutterFire plugin provides easy access to Firebase services in Flutter, making it simple to integrate Firebase into your app.

Prerequisites

Before we dive into the tutorial, here’s what you need:

  1. Flutter SDK: Ensure you have Flutter installed on your machine. If not, follow the official Flutter installation guide: Install Flutter.
  2. Firebase Account: You’ll need a Firebase project. You can create one at Firebase Console.
  3. Android Studio/VS Code: You can use either Android Studio or VS Code for Flutter development.

Steps to Follow

Step 1: Set Up Firebase Project

Before integrating Firebase with your Flutter app, you need to create and configure a Firebase project.

1.1 Create a Firebase Project

  1. Visit the Firebase Console.
  2. Click on “Add Project” and follow the on-screen instructions.
  • Name your project.
  • Choose your country/region.
  • Disable or enable Google Analytics for your project.

2. Click “Create Project”.

1.2 Set Up Firebase Authentication

  1. In the Firebase Console, select Authentication from the sidebar.
  2. Go to the Sign-in method tab.
  3. Enable the authentication methods you want (Email/Password, Google, Facebook, etc.).
  • For this tutorial, we’ll enable Email/Password Authentication.

1.3 Set Up Firestore

  1. In the Firebase Console, click on Firestore Database in the sidebar.
  2. Choose Start in test mode (this is for testing, you can configure security rules later).
  3. Create your Firestore database in a specific location.

1.4 Set Up Firebase Storage

  1. In the Firebase Console, navigate to Storage and click on Get Started.
  2. Choose the storage location for your files.
  3. Set up security rules for storage, ensuring they fit your app’s privacy requirements.

Step 2: Set Up Firebase in Your Flutter App

2.1 Create a Flutter Project

If you haven’t already created a Flutter project, you can do so by running:

flutter create firebase_flutter_app
cd firebase_flutter_app

2.2 Add Firebase SDK to Your Flutter Project

In the Firebase Console, add your app to the Firebase project by selecting Add App and choosing Android or iOS.

Modify pubspec.yaml

Open the pubspec.yaml file and add the following Firebase dependencies:

dependencies:
flutter:
sdk: flutter
firebase_core: ^2.14.0 # Firebase core dependency
firebase_auth: ^4.5.0 # Firebase Authentication
cloud_firestore: ^5.0.0 # Firestore Database
firebase_storage: ^11.0.0 # Firebase Storage
firebase_functions: ^4.5.0 # Firebase Functions (optional)

After saving, run the following command to fetch the dependencies:

flutter pub get

Android Setup

  1. In the Firebase Console, click on Project settings > General.
  2. Click on the Add App button for Android and follow the setup instructions. Download the google-services.json file and add it to the android/app directory.

Modify android/build.gradle:

classpath 'com.google.gms:google-services:4.3.15' // Add this line in the dependencies section

In android/app/build.gradle:
apply plugin: 'com.google.gms.google-services' // Add this line at the bottom of the file

iOS Setup

  1. In the Firebase Console, click Add App for iOS and download the GoogleService-Info.plist file.
  2. Add this file to your ios/Runner directory.
  3. Run pod install in the ios directory to install necessary dependencies.

Step 3: Firebase Authentication

Firebase Authentication enables secure login and user management for your app.

3.1 Email/Password Authentication

Sign Up User

Here’s an example of how to allow users to sign up with their email and password:

import 'package:firebase_auth/firebase_auth.dart';

Future<User?> signUpWithEmailPassword(String email, String password) async {
try {
final UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user; // Returns the user object
} catch (e) {
print("Error: $e");
return null;
}
}

Sign In User

Similarly, to sign in a user:

Future<User?> signInWithEmailPassword(String email, String password) async {
try {
final UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user; // Returns the user object
} catch (e) {
print("Error: $e");
return null;
}
}

3.2 Google Sign-In (Optional)

For users who prefer to sign in using their Google accounts, you can use the google_sign_in package: Add google_sign_in Dependency

dependencies:
  google_sign_in: ^5.0.7

Sign In with Google

import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';

final GoogleSignIn googleSignIn = GoogleSignIn();

Future<User?> signInWithGoogle() async {
try {
GoogleSignInAccount? googleUser = await googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser!.authentication;

final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);

final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
return userCredential.user;
} catch (e) {
print("Error: $e");
return null;
}
}

Step 4: Firestore Database

Firestore is a NoSQL database that allows you to store and sync data in real-time.

4.1 Adding Data to Firestore

You can store data in Firestore by creating collections and documents.

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> addUserData(String name, String email) async {
try {
await FirebaseFirestore.instance.collection('users').add({
'name': name,
'email': email,
'createdAt': FieldValue.serverTimestamp(),
});
print('User added successfully');
} catch (e) {
print('Error: $e');
}
}

4.2 Fetching Data from Firestore

You can fetch data by querying Firestore collections.

Future<void> getUserData() async {
try {
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('users').get();
snapshot.docs.forEach((doc) {
print(doc['name']);
print(doc['email']);
});
} catch (e) {
print('Error: $e');
}
}

4.3 Listening for Real-time Updates

You can also listen to real-time changes in Firestore with snapshots():

StreamBuilder(
stream: FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
var user = snapshot.data!.docs[index];
return ListTile(
title: Text(user['name']),
subtitle: Text(user['email']),
);
},
);
},
);

Step 5: Firebase Storage

Firebase Storage allows you to upload and retrieve files such as images, videos, and more.

5.1 Upload File to Firebase Storage

Here’s how to upload an image selected from the gallery:

import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

Future<void> uploadImageToStorage() async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery);

if (image != null) {
try {
final ref = FirebaseStorage.instance.ref().child('images/${image.name}');
await ref.putFile(File(image.path)); // Uploading file
String imageUrl = await ref.getDownloadURL(); // Getting file URL
print('Image uploaded, URL: $imageUrl');
} catch (e) {
print("Error: $e");
}
}
}

5.2 Retrieve File from Firebase Storage

To retrieve the file, you can use the file URL:

Future<void> downloadImage(String imagePath) async {
try {
String downloadUrl = await FirebaseStorage.instance.ref(imagePath).getDownloadURL();
print('Download URL: $downloadUrl');
} catch (e) {
print('Error: $e');
}
}

Step 6: Firebase Functions (Optional)

Firebase Functions enable you to run backend code in response to Firebase events or HTTP requests. While this step is optional, it can help you build powerful features like sending emails or performing backend logic.

6.1 Setting Up Firebase Functions

To use Firebase Functions in your app:

  1. Install Firebase CLI and set up Firebase Functions in your project.
  2. Write a simple Firebase function to run when triggered.

6.2 Calling Firebase Functions from Flutter

import 'package:firebase_functions/firebase_functions.dart';

Future<void> callFirebaseFunction() async {
try {
final HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('yourFunctionName');
final response = await callable.call();
print(response.data);
} catch (e) {
print('Error calling function: $e');
}
}

Conclusion

You’ve now learned how to integrate Firebase with Flutter, covering the most important Firebase services such as Firebase Authentication, Firestore Database, Firebase Storage, and Firebase Functions. With Firebase, you can add powerful features to your Flutter apps without worrying about setting up your backend infrastructure.

As you continue developing with Flutter and Firebase, don’t forget to explore other Firebase services like Firebase Analytics, Firebase Cloud Messaging (FCM), and Firebase Crashlytics to further enhance your app’s capabilities.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


References:

Flutter – Realtime Database in Firebase – GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and…www.geeksforgeeks.org

A Complete Guide to Firebase Multifactor Authentication in Flutter | Codemagic Blog
A tutorial on how to use multifactor auth with Firebase authentication in Flutter.blog.codemagic.io


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
 And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Flutter 3.29 — What’s New In Flutter

0

Flutter continues to evolve, and Flutter 3.29 brings a set of powerful enhancements aimed at improving performance, refining UI components, and optimizing debugging tools. Whether you’re working on mobile, web, or desktop apps, this update introduces several developer-centric improvements that will make your workflow smoother and your applications more efficient.

In this blog, we’ll dive deep into each update, explore how it benefits developers, and provide practical implementation examples so you can start using them immediately.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents:

Performance Optimizations

Framework Enhancements

New Platform-Specific Features

Material 3 Enhancements

Development Workflow Improvements

Conclusion

Reference


1. Performance Optimizations:

Flutter 3.29 delivers remarkable performance improvements through advanced widget caching, optimized rendering pipelines, and more efficient state management.

What’s Improved?

  • Frame rendering speed: Up to 35% faster across platforms due to optimized Impeller implementation
  • Memory utilization: Average 15–20% reduction in memory footprint for complex UIs
  • Widget tree diffing: Rebuilds now execute with significantly lower overhead
  • State management: More efficient handling of state changes with reduced CPU overhead

Implementation Strategies

1. Optimized Widget Tree Diffing

In earlier versions of Flutter, when a state change occurred, the framework would recalculate the widget tree more than necessary. This could cause unnecessary UI rebuilds, leading to performance drops.

What’s Changed?
Flutter 3.29 now intelligently identifies which widgets actually need rebuilding and skips unnecessary re-renders, resulting in faster UI updates.

Example:

// BEFORE: Potentially causing unnecessary rebuilds
class UserListItem extends StatelessWidget {
final User user;

const UserListItem({required this.user});

@override
Widget build(BuildContext context) {
return ListTile(
leading: CircleAvatar(backgroundImage: NetworkImage(user.avatarUrl)),
title: Text(user.name),
subtitle: Text(user.email),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => UserDetailScreen(user: user)),
),
);
}
}

// AFTER: Optimized for Flutter 3.29's enhanced widget caching
class UserListItem extends StatelessWidget {
final User user;
final VoidCallback onTap;

// Using const constructor is now even more important in 3.29
const UserListItem({
required this.user,
required this.onTap,
Key? key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return ListTile(
leading: CircleAvatar(backgroundImage: NetworkImage(user.avatarUrl)),
title: Text(user.name),
subtitle: Text(user.email),
onTap: onTap, // Using passed callback instead of inline creation
);
}
}

// Usage in parent widget:
@override
Widget build(BuildContext context) {
// Pre-create callbacks to avoid rebuilds
final callbacks = List<VoidCallback>.generate(
users.length,
(index) => () => _navigateToUserDetail(users[index]),
);

return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) => UserListItem(
key: ValueKey(users[index].id), // Stable identity
user: users[index],
onTap: callbacks[index],
),
);
}

void _navigateToUserDetail(User user) {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => UserDetailScreen(user: user)),
);
}
  • In previous versions, if a single item changed, Flutter re-evaluated the entire list..
  • In Flutter 3.29, only the modified item gets rebuilt, significantly reducing CPU load.


2. Impeller Engine Optimization (iOS & Android)

Impeller, Flutter’s new rendering engine, gets faster GPU shader caching. This means that:

✔ Animations start instantly instead of waiting for shaders to compile.
Smoother frame rates, especially on iOS devices.
Better graphics rendering, reducing stutter in UI transitions.

 Before (Flutter 3.7)

Running a Lottie animation in Flutter resulted in slight frame drops when navigating between screens.

The first animation load lags due to the compilation of real-time shaders.

 After (Flutter 3.29)

Animations now pre-cache shaders, removing any frame drops.

Navigation feels more fluid, with faster screen transitions.

// Running a Lottie animation without lag
Lottie.asset('assets/animation.json', frameRate: FrameRate.max);

3. Improved Memory Management

Flutter 3.29 reduces RAM usage, which is crucial for low-end devices and large-scale applications.

Objects are now lazily initialized, reducing memory spikes.
Better garbage collection, ensuring unused objects are removed quickly.
Lower battery drain, as fewer resources are consumed in the background.

 Before (Flutter 3.7)

Large images & animations consumed more memory, sometimes leading to app crashes on older devices.

After (Flutter 3.29)

Memory is released faster, and Flutter avoids loading large assets until necessary.

Real-World Impact

  • 30% Faster Complex Animations & Transitions
     If your app has
    Lottie animations, gesture-based navigation, or UI transitions, you’ll see a noticeable speed boost.
  • Heavy UI Apps See Fewer Dropped Frames
    Apps with large lists, carousels, or grids (e.g., social media feeds, e-commerce product catalogs) now scroll smoother than before.
  • Battery Consumption Reduced
    Mobile users benefit from lower power consumption, as Flutter now optimizes rendering cycles to save energy.

2. Framework Enhancements

Cupertino Enhancements — Bringing iOS Closer to Native 

Flutter 3.29 introduces several improvements to Cupertino widgets, making them behave more like their native iOS counterparts.

1. CupertinoNavigationBar & CupertinoSliverNavigationBar Upgrades

The CupertinoNavigationBar and CupertinoSliverNavigationBar now offer:

  • A new bottom widget slot — Useful for placing search fields, buttons, or tabs inside the navigation bar.
  • Smoother scrolling behavior — The navigation bar now snaps naturally between collapsed and expanded states, mimicking iOS more accurately.

 Example — Using a Search Bar in CupertinoNavigationBar

CupertinoNavigationBar(
middle: Text("iOS Styled App"),
trailing: CupertinoButton(
padding: EdgeInsets.zero,
child: Icon(CupertinoIcons.search),
onPressed: () {
// Open search functionality
},
),
)
  • Before (Flutter 3.7): You had to position search fields manually, and scrolling behavior was slightly inconsistent.
  • Now (Flutter 3.29): You can directly place search fields, buttons, or extra widgets inside the navigation bar without extra effort.

2. New CupertinoSheetRoute — iOS-Style Modal Sheets

Apple’s UI guidelines favor fluid bottom sheets with blurred backgrounds and drag-to-dismiss gestures.

Supports drag-to-dismiss gestures — Users can swipe down to close the sheet.
Improved visuals — Now features blurred backgrounds for a native look.

 Example — Showing a Cupertino Modal Sheet

showCupertinoModalPopup(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text("Choose an action"),
message: Text("Select an option below"),
actions: [
CupertinoActionSheetAction(
onPressed: () {
// Perform action
},
child: Text("Option 1"),
),
CupertinoActionSheetAction(
onPressed: () {
Navigator.pop(context);
},
child: Text("Cancel"),
isDestructiveAction: true,
),
],
),
);
  • Before (Flutter 3.7): Developers had to use third-party packages to achieve a native iOS modal sheet look & feel.
  • Now (Flutter 3.29): Flutter provides a built-in CupertinoSheetRoute, making modal sheets look & behave exactly like iOS.

3. Better CupertinoAlertDialog & CupertinoActionSheet

Flutter 3.29 refines the CupertinoAlertDialog and CupertinoActionSheet with:

  • Dark Mode Improvements — Better contrast in dark mode for readability.
  • Rounded Corners & Spacing Adjustments — Dialogs feel more natural & aligned with iOS standards.

💡 Example — Cupertino Alert Dialog with iOS Styling

showCupertinoDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text("Alert"),
content: Text("Are you sure you want to proceed?"),
actions: [
CupertinoDialogAction(
child: Text("Cancel"),
onPressed: () => Navigator.pop(context),
),
CupertinoDialogAction(
child: Text("OK"),
onPressed: () {
// Perform action
},
),
],
),
);
  • Before (Flutter 3.7): The CupertinoAlertDialog lacked proper contrast in dark mode and required extra styling for a natural look.
  • Now (Flutter 3.29): Flutter automatically optimizes colors, spacing, and animations for a seamless experience.

3. New Platform-Specific Features 

1. Flutter Web Gets a Speed Boost with WebAssembly (Wasm)

WebAssembly (Wasm) is a low-level bytecode format that allows web applications to run much faster than traditional JavaScript execution. In Flutter 3.29, WebAssembly support has been improved significantly, leading to:

1. No more special HTTP headers for Wasm apps — Previously, developers had to manually configure headers for WebAssembly files. Now, Flutter handles it automatically.
2. Improved multi-threading support — WebAssembly can now take advantage of multi-threading, making complex operations (like image processing and animations) run more efficiently.
3. Web images now decode off the main UI thread — Instead of decoding images on the main UI thread, Flutter now processes them asynchronously, reducing UI lag and improving overall performance.

 Why This Matters?

  • If your Flutter web app has lots of images, loading them will now feel snappier.
  • Large computations (like video processing or real-time rendering) will now execute faster due to improved multi-threading.
  • Before (Flutter 3.7): WebAssembly performance was slower due to manual HTTP header configurations and main-thread image decoding.
  • Now (Flutter 3.29): Web apps feel much faster and run more smoothly with zero manual setup.

2. Android Vulkan & OpenGLES Optimization — Better Rendering on All Devices

Flutter 3.29 optimizes rendering on Android by improving support for Vulkan and OpenGLES, leading to:

  • Impeller is now the default renderer for Android — This replaces the older Skia rendering engine, offering smoother animations and faster frame rendering.
  • Automatic fallback to OpenGLES — If Vulkan isn’t available (common on older devices), Flutter will seamlessly switch to OpenGLES instead of Skia.
  • Improved GPU utilization — Flutter now takes better advantage of the GPU, ensuring less jank and better performance, even on mid-range & older Android devices

Why This Matters?

  • If your app has heavy UI elements like lists, animations, or 3D graphics, they will render more efficiently.
  • Older Android devices will automatically use OpenGLES, ensuring better frame rates and less lag.
  • Before (Flutter 3.7): Apps defaulted to Skia, which had performance limitations on Android.
  • Now (Flutter 3.29): Impeller is the default renderer, with automatic fallback to OpenGLES for older devices.

3. iOS: Skia is Gone — Impeller is Now the Only Renderer!

In a major shift, Flutter 3.29 completely removes Skia from iOS and fully switches to Impeller, which leads to:

  • No more FLTEnableImpeller flag — In previous versions, developers had to manually enable Impeller using FLTEnableImpeller. Now, Impeller is always ON..
  • Faster frame rendering & reduced jank — Impeller optimizes frame rendering, ensuring a smoother user experience
  • Better GPU acceleration — iOS animations now feel more fluid and run with lower CPU usage, which also improves battery efficiency.

Why This Matters?

  • If your iOS app has custom UI animations, scrolling lists, or complex graphics, it will run much smoother.
  • Your app automatically benefits from Impeller, without any extra configuration.
  • Before (Flutter 3.7): Developers had to manually enable Impeller, and Skia still handled rendering in some cases.
  • Now (Flutter 3.29): Skia is completely gone, and Impeller is the only renderer, leading to a faster and more stable UI experience.

4. Material 3 Enhancements

1. Enhanced Color Theming & Dark Mode Handling

Material 3 introduces dynamic color schemes that adapt to the user’s system settings, creating a harmonious and consistent experience.

What’s Improved?

Dynamic color schemes based on the primary color — Flutter now generates an entire color palette from a single seed color, making it easier to maintain a cohesive UI.
Better dark mode support — Material 3 ensures that dark mode automatically applies correct contrast levels for improved readability and accessibility.
 Smoother transitions between light and dark themes — Flutter 3.29 refines adaptive themes, providing a seamless transition when users switch between modes.

 Example: Applying Material 3 Themes with a Seed Color

ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), // Generates a color palette
brightness: Brightness.light, // Default light mode
useMaterial3: true, // Enables Material 3 styling
);

Why This Matters?

  • You no longer need to manually define color palettes — just pick a seed color, and Flutter does the rest!
  • Dark mode works out of the box, ensuring consistent contrast and readability.
  • Before (Flutter 3.7): Developers had to manually define color schemes.
  • Now (Flutter 3.29): Flutter automatically generates adaptive colors for both light and dark modes.

2.More Refined Shadows & Elevations for a Realistic Look

Shadows and elevations play a crucial role in defining the depth and hierarchy of UI elements. Flutter 3.29 enhances Material 3’s elevation system by:

Providing softer and more natural shadow effects
Ensuring consistent elevation across components
Automatically adjusting shadows for light & dark themes

Why This Matters?

  • Your app UI will now feel more polished and structured, without harsh shadows.
  • Shadows automatically adapt to dark mode, ensuring a natural look in both themes.
  • Before (Flutter 3.7): Shadows were too intense in dark mode.
  • Now (Flutter 3.29): Shadows are softened and blend more naturally.

3. Improved Typography & Button Styles

Typography and buttons have been fine-tuned to align with Material 3’s latest design guidelines.

More refined font scaling — Ensures better readability across different screen sizes.
Buttons have more rounded corners & better padding — Making them easier to tap and more accessible.
Adaptive font-weight & letter spacing — Improves visual clarity and consistency.

Why This Matters?

  • Buttons now feel more modern and accessible.
  • Typography adapts better to different screen sizes, improving usability.

🔹 Before (Flutter 3.7): Buttons had sharp corners, and fonts didn’t scale well.
🔹 Now (Flutter 3.29): Buttons are more rounded, and text is more readable across devices.


5. Development Workflow Improvements

Flutter 3.29 brings several enhancements to the development workflow, making it more efficient and enjoyable to build Flutter applications.

DevTools Enhancements

The Flutter DevTools suite has received significant updates in Flutter 3.29. The performance tools now provide more detailed insights into your application’s rendering and computation performance, helping you identify and resolve bottlenecks more effectively.

The widget inspector has been improved with better search capabilities and more detailed property information. This makes it easier to debug complex widget trees and understand how your UI is constructed at runtime.

Network profiling tools now provide more detailed information about HTTP requests, including headers, body content, and timing information. This is particularly useful when debugging API interactions or identifying network-related performance issues.

Hot Reload Optimizations

Flutter’s hot reload feature, one of its most beloved capabilities, has been optimized in Flutter 3.29 to be faster and more reliable. The framework now more intelligently determines which parts of your application need to be rebuilt when code changes, resulting in quicker reload times and a more responsive development experience.

These improvements are especially noticeable in larger applications, where hot reload times have been reduced by up to 40% in some cases. This means less time waiting and more time coding, ultimately leading to faster development cycles.

6. Conclusion: 

Flutter 3.29 represents a significant leap forward in performance, platform integration, and developer experience. This release solidifies Flutter’s position as a leading cross-platform framework for building beautiful, high-performance applications.

The improvements in rendering performance, particularly through the Impeller engine, address one of the most requested enhancements from the Flutter community. Combined with the numerous optimizations to memory usage, state management, and widget rebuilding, Flutter 3.29 delivers applications that are noticeably faster and more responsive.

The enhanced platform integrations ensure that Flutter applications not only perform well but also feel natural on each platform. This is crucial for winning user acceptance and creating experiences that meet platform-specific expectations.

Whether you’re building a new application or maintaining an existing one, Flutter 3.29 offers compelling reasons to upgrade and take advantage of these substantial improvements. Happy coding!

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Reference

Flutter 3.29.0 release notes
Release notes for Flutter 3.29.0.docs.flutter.dev


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Reverse a String In Dart

0

If you have a String in Dart if you need to reverse the request for the characters, there are multiple ways of making it happen.

This blog will explore the Reverse of a String In a Dart. We perceive how to execute a demo program. We will show you various ways to reverse a given string in Dart. This additionally works for any Dart framework including Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table Of Contents::

Reverse Using Split and Join

Reverse Using Runes

Reverse Using Code Units

Conclusion



Reverse Using Split and Join:

Dart’s String doesn’t have an inherent class part for reversing the characters. Be that as it may, Dart’s List has turned around getter. We can use it to reverse a String.

String reverseUsingSplitAndJoin(String text) {
final chars = text.split('');

return chars.reversed.join('');
}

The arrangement is to split the String into a List of characters, get the characters in the reversed request utilizing the reversed getter, and join the List into a String.

Reverse Using Runes:

One more method for reverse around is by getting the runes property of the String. The runes property returns an Iterable of unicode code-pont (int) of the characters.

String reverseUsingRunes(String text) {
final chars = text.runes.toList();

return String.fromCharCodes(chars.reversed);
}

The Iterable can be changed over into a List by calling the toList technique. Very much like the past method, utilize List’s reversed property to get the components in the reversed request. To change over the character codes to a String, utilize the factory technique String.fromCharCodes.

Reverse Using Code Units:

You can likewise get the codeUnits property of the String which returns a List of UTF-16 code units (int).

String reverseUsingCodeUnits(String text) {
final chars = text.codeUnits;

return String.fromCharCodes(chars.reversed);
}

Then, at that point, utilize the reversed strategy to reverse the request for the characters and convert it to a String utilizing the String.fromCharCodes factory technique.

Let’s put all the code together:

void main() {
var flutterDevs = 'FlutterDevs';

print(reverseUsingSplitAndJoin(flutterDevs));
print(reverseUsingRunes(flutterDevs));
print(reverseUsingCodeUnits(flutterDevs));
}

String reverseUsingSplitAndJoin(String text) {
final chars = text.split('');

return chars.reversed.join('');
}

String reverseUsingRunes(String text) {
final chars = text.runes.toList();

return String.fromCharCodes(chars.reversed);
}


String reverseUsingCodeUnits(String text) {
final chars = text.codeUnits;

return String.fromCharCodes(chars.reversed);
}

When we run the application, we ought to get the screen’s output like the underneath screen Console Output.

sveDrettulF
sveDrettulF
sveDrettulF

Process finished with exit code 0

Conclusion:

In the article, I have explained the Reverse of a String In Dart; you can modify this code according to your choice. This was a small introduction to the Reverse a String In Dart User Interaction from my side, and it’s working using Flutter. With no extra library, multiple ways of reversing a String in Dart exist.

The first is to split the String into a List of characters, reverse the request for the characters, and join the reversed characters. It should likewise be possible by getting the runes or codeUnits of the String, reversing the request for the character codes, and converting the character codes into a String

I hope this blog will provide you with sufficient information on Trying the Reverse a String In the Dart of your projects. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Biometric Authentication in Flutter: Unlock Your App with Face & Fingerprint

0

In this blog, we will implement biometric authentication in a Flutter app using the local_auth package. We’ll cover both fingerprint and face recognition, ensuring that your app provides a high level of security while maintaining user convenience.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table of contents

Introduction

What is Biometric Authentication?

Why Use Biometric Authentication in Your Flutter App?

How Flutter & local_auth Package Enable Biometric Authentication

Prerequisites

Steps to Follow

Benefits of Biometric Authentication

Drawbacks of Biometric Authentication

Enhancing Security in Biometric Authentication

Best Practices for Biometric Authentication

Conclusion

References


Introduction

In today’s digital world, security and convenience go hand in hand. Traditional authentication methods like passwords and PINs are prone to security threats such as phishing and brute-force attacks. Biometric authentication, such as fingerprint and face recognition, provides a seamless and secure way to log in to apps, ensuring that only the rightful user gains access.

With biometric authentication, users can log in faster without remembering complex passwords. This method leverages the unique biological traits of individuals, making unauthorized access significantly more difficult. Additionally, it enhances the user experience by offering a smooth and hassle-free authentication process.

Biometric authentication, such as fingerprint and face recognition, provides a seamless and secure way to log in to apps. In this blog, we will implement biometric authentication in a Flutter app using the local_auth package.


What is Biometric Authentication?

Biometric authentication leverages a person’s unique biological characteristics (like fingerprints, face recognition, or even iris scans) to verify their identity. It’s widely used in smartphones for locking screens, securing apps, and even making payments. The main advantage is that biometrics cannot be easily replicated or stolen, making them a reliable method of securing mobile apps.


Why Use Biometric Authentication in Your Flutter App?

  1. Enhanced Security:
  • Unmatched accuracy: Biometric authentication systems have a very low false acceptance rate, making it highly secure compared to other methods like passwords.
  • Hard to replicate: Unlike passwords or PIN codes, which can be stolen or guessed, biometric data is unique to each individual, making it nearly impossible to impersonate.

2. Convenience:

  • Quick and seamless: Biometric authentication is much faster than typing in a password, reducing friction for users.
  • No need to remember passwords: Users no longer need to remember multiple passwords or PIN codes, making the experience more user-friendly.

3. Improved User Experience:

  • Easy access: With the ability to authenticate using facial recognition or a fingerprint scan, users can access the app in seconds, improving overall satisfaction.
  • Modern technology: Biometric authentication provides a sleek, modern touch that aligns with users’ expectations for convenience and cutting-edge tech.

4. Compliance and Privacy:

  • Biometric authentication enhances privacy and meets the growing demand for secure methods to access sensitive data, which is particularly important for industries such as banking, healthcare, and government services.

How Flutter & local_auth Package Enable Biometric Authentication

Flutter, being a cross-platform framework, allows you to write code once and run it on both Android and iOS devices. When it comes to biometric authentication, the Flutter ecosystem provides excellent tools to streamline integration.

The key package that enables biometric authentication in Flutter is local_auth. This plugin supports fingerprint scanning, face recognition, and other biometric methods that are supported by both Android and iOS devices. Whether you’re developing an app for smartphones, tablets, or even wearables, the local_auth package can help implement secure biometric authentication with minimal effort.

Here’s why the local_auth the package is so effective:

  1. Cross-Platform Support:
  • The local_auth the package works seamlessly across both Android and iOS platforms. It abstracts platform-specific implementations, making it easy for developers to use biometric authentication without worrying about the complexities of each platform’s native APIs.

2. Comprehensive Biometric Authentication:

  • The plugin supports various forms of biometric data on both platforms. On Android, it works with fingerprint recognition, and on iOS, it supports both Touch ID and Face ID, making it flexible for different devices and scenarios.

3. Device Compatibility:

  • The local_auth package detects whether the device has biometric authentication capabilities, such as a fingerprint scanner or a face recognition system. It then makes sure that the appropriate authentication method is used based on the device’s capabilities.

4. Security and Privacy:

  • The plugin integrates with secure hardware on the device, such as the Secure Enclave on iPhones or Trusted Execution Environment (TEE) on Android devices. This means that biometric data is never stored on the device or in the cloud, and only authentication tokens are passed between the app and the device.

5. Simple API:

  • local_auth provides an intuitive API that allows developers to easily check for biometric availability, prompt for authentication, and handle success or failure cases—all without needing to write complex platform-specific code.

Prerequisites

Before getting started, ensure you have:

  • Flutter installed
  • An Android or iOS device with biometric authentication support
  • A Flutter project setup

Let’s walk through how to integrate biometric authentication in your Flutter app.

Steps to Follow 

Step 1: Add Dependencies

Add the local_auth package to your pubspec.yaml

dependencies:
flutter:
sdk: flutter
local_auth: ^2.1.6

Run:

flutter pub get

Step 2: Configure Android & iOS Permissions

Android

Modify android/app/src/main/AndroidManifest.xml:

<manifest>
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature android:name="android.hardware.fingerprint" android:required="false"/>

<application>
<meta-data
android:name="androidx.biometric.AuthenticatorType"
android:value="BIOMETRIC_STRONG | DEVICE_CREDENTIAL" />
</application>
</manifest>

iOS

Modify ios/Runner/Info.plist:

<key>NSFaceIDUsageDescription</key>
<string>We need access to Face ID for authentication</string>

Step 3: Implement Biometric Authentication

Create a new Dart file biometric_auth.dart:

import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';

class BiometricAuth {
final LocalAuthentication auth = LocalAuthentication();

Future<bool> isBiometricAvailable() async {
return await auth.canCheckBiometrics || await auth.isDeviceSupported();
}

Future<bool> authenticateUser() async {
try {
return await auth.authenticate(
localizedReason: 'Authenticate to access the app',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
} catch (e) {
print("Error: $e");
return false;
}
}
}

Step 4: Integrate Authentication in UI

Modify main.dart:

import 'package:flutter/material.dart';
import 'biometric_auth.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LoginScreen(),
);
}
}

class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
final BiometricAuth biometricAuth = BiometricAuth();

void _loginWithBiometrics() async {
bool isAuthenticated = await biometricAuth.authenticateUser();
if (isAuthenticated) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Authentication failed")),
);
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Login")),
body: Center(
child: ElevatedButton(
onPressed: _loginWithBiometrics,
child: Text("Login with Biometrics"),
),
),
);
}
}

class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Home")),
body: Center(child: Text("Welcome to Home Screen!")),
);
}
}

Step 5: Test the Application

Run the app on a real device:

flutter run

If everything is set up correctly, you should be able to authenticate using face or fingerprint recognition.

Benefits of Biometric Authentication

  • Enhanced Security: Biometrics are harder to forge compared to passwords.
  • Convenience: Users can log in quickly without remembering passwords.
  • User Experience: Reduces friction in authentication, making the app more user-friendly.
  • Device-Level Protection: Uses built-in security mechanisms of the device.

Drawbacks of Biometric Authentication

  • Device Dependency: Not all devices support biometrics.
  • Privacy Concerns: Storing biometric data raises security and privacy risks.
  • False Positives/Negatives: Recognition systems are not 100% accurate.
  • Physical Restrictions: Injuries or facial obstructions can prevent authentication.

Enhancing Security in Biometric Authentication

To make biometric login even more secure, consider implementing the following best practices:

  • Multi-Factor Authentication (MFA): Combine biometrics with a secondary factor like a PIN or OTP.
  • Secure Storage: Store authentication tokens securely using Flutter Secure Storage or Encrypted Shared Preferences.
  • Liveness Detection: Ensure that face unlock cannot be fooled by photos or videos.
  • Biometric Strength Check: Use only strong biometric methods (e.g., Face ID, high-quality fingerprint sensors).
  • Session Timeout: Implement automatic logout after inactivity.
  • Server-Side Verification: For critical actions, use backend validation to verify the user’s identity.

Best Practices for Biometric Authentication

  1. Fallback Mechanism: Always provide an alternative authentication method in case biometrics fail (e.g., PIN or password).
  2. Security: Never store biometric data directly. Let the OS handle biometric verification, and only store tokens or authentication results.
  3. User Experience: Make sure the authentication process is clear and the user is informed of what they need to do (e.g., “Place your finger on the sensor”).

Conclusion

Biometric authentication provides an easy-to-use, secure, and fast method to verify users in your Flutter app. By leveraging the local_auth package, you can integrate both fingerprint and face recognition in a few simple steps. Not only will this improve your app’s security, but it will also create a frictionless user experience.

With the growing importance of privacy and security, adopting biometric authentication in your Flutter app is a great way to keep your users’ data safe and provide them with the convenience they expect.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


References:

Unlocking Secure Authentication: A Guide to Adding Biometric Authentication to Flutter Apps
Learn how to integrate biometric authentication into your Flutter app, enhancing user experience and security. Discover…30dayscoding.com

How to Integrate Device Fingerprinting Into Your Flutter Application
Secure your app with device fingerprinting to block threats. Integrate it into Flutter using Fingerprint’s SDKs.fingerprint.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


GraphQL With HTTP In Flutter

0

GraphQL can fetch only the data that is needed, GraphQL has become extremely popular in modern app development. It can improve your app’s efficiency and performance when used in conjunction with Flutter, a leading cross-platform development framework.

This article will explore GraphQL With HTTP In Flutter. We will learn how to execute a demo program and how to implement graphql with HTTP using the HTTP package in your Flutter applications.

For Http:

http | Dart package
A composable, multi-platform, Future-based API for HTTP requests.pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

What is GraphQL?

Implementation

GraphQL Operations

GraphQL Query with HTTP

GraphQL Mutations

Error Handling

Conclusion



What is GraphQL?:

GraphQL is an open-source query language developed by Facebook. By allowing clients to request only the data they require, GraphQL provides a more dynamic and effective method of interacting with APIs than REST APIs. Applications become more effective as a result of this reduction in data over- or under-fetching.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
http: ^1.3.0

Step 2: Import

import 'package:http/http.dart';

Step 3: Run flutter packages get in the root directory of your app.

GraphQL Operations:

There are two main operations GraphQL works:

  • Query: Retrieve data.
  • Mutation: Change data.

Every operation is organized as a query that resembles JSON, but it defines the required data using a particular syntax.

GraphQL Query with HTTP:

Here’s how to put this into implementing Flutter:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> fetchUsers() async {
const String graphqlEndpoint = 'https://www.example.com/graphql';
const String query = '''
query {
users {
id
name
email
}
}
''';

final response = await http.post(
Uri.parse(graphqlEndpoint),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'query': query}),
);

if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print(data['data']['users']);
} else {
throw Exception('Failed to fetch users');
}
}

GraphQL Mutations:

You can change the data on the server through mutations. To create a new user, for instance:

Future<void> createUser(String name, String email) async {
const String graphqlEndpoint = 'https://example.com/graphql';
const String mutation = '''
mutation(\$name: String!, \$email: String!) {
createUser(input: { name: \$name, email: \$email }) {
id
name
email
}
}
''';

final variables = {'name': name, 'email': email};

final response = await http.post(
Uri.parse(graphqlEndpoint),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'query': mutation, 'variables': variables}),
);

if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print(data['data']['createUser']); // Access the created user data
} else {
throw Exception('Failed to create user');
}
}

Error Handling:

An error field is frequently included in GraphQL response. To deal with mistakes:

final responseBody = jsonDecode(response.body);
if (responseBody['errors'] != null) {
print('GraphQL Error: ${responseBody['errors']}');
} else {
print('Data: ${responseBody['data']}');
}

Conclusion:

In the article, I have explained GraphQL With HTTP in a flutter; you can modify this code according to your choice. This was a small introduction to GraphQL With HTTP In Flutter On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the GraphQL With HTTP in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on GraphQL With HTTP using the HTTP package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Explore Digital Signature In Flutter

0

Digital signatures are pivotal in guaranteeing the respectability and authenticity of digital records. By integrating digital signature usefulness into your Flutter application, you can upgrade the security of your application.

This article will Explore a Digital Signature In Flutter. We will perceive how to execute a demo program and we are going to learn about how we can implement digital signature using the signature package in your Flutter applications.

For Signature:

Signature | Flutter Package
A Flutter plugin providing a performance-optimized signature canvas with the ability to set custom style, boundaries, and…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

This demo video shows how to implement a digital signature in Flutter and how an animated loader will work using the signature package in your Flutter applications. We will offer users a digital signature and how to undo, redo, and clear the signature. It will be shown on your device.

Demo Module::


Constructor:

To control the signature, we need to use a SignatureController constructor underneath.

SignatureController({
List<Point>? points,
this.disabled = false,
this.penColor = Colors.black,
this.strokeCap = StrokeCap.butt,
this.strokeJoin = StrokeJoin.miter,
this.penStrokeWidth = 3.0,
this.exportBackgroundColor,
this.exportPenColor,
this.onDrawStart,
this.onDrawMove,
this.onDrawEnd,
})

Properties:

There are some properties of SignatureController are:

  • penColor: This property is used to color the signature line drawn on the pad.
  • penStrokeWidth: This property determines the width or thickness of the signature line drawn.
  • exportBackgroundColor: This property is used to determine the color of the exported PNG image.
  • point: This property is used as a setter representing the position of the signature on the 2D canvas.
  • onDrawStart: This property uses a callback function that notifies us when the drawing has started.
  • onDrawMove: This property uses a callback function that notifies us while drawing our signature.
  • onDrawEnd: This property uses a callback function that notifies us when the drawing has stopped.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
signature: ^5.4.0

Step 2: Import

import 'package:signature/signature.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

We should adjust our main. dart file. We want to create a new class MyHomePage(). In this class first, we will initialize the signature controller.

 final SignatureController _controller = SignatureController(
penStrokeWidth: 1,
penColor: Colors.red,
exportBackgroundColor: Colors.transparent,
exportPenColor: Colors.black,
onDrawStart: () => log('onDrawStart called!'),
onDrawEnd: () => log('onDrawEnd called!'),
);

Now, we will add the initState() method. In this method, we will add a _controller.addListener() navigate to log ().

@override
void initState() {
super.initState();
_controller.addListener(() => log('Value changed'));
}

We will add dispose() method. in this method, we will add _controller.dispose().

@override
void dispose() {
_controller.dispose();
super.dispose();
}

We will add the code to the build method. In this method, we will add a ListView widget. In this widget, we will add SizeBox with a height was 50 and text that is ‘Signature’. Then below define the Signature() function. In this function, we will add a keycontrollerheightwidth, and backgroundColor.

ListView(
children: <Widget>[
const SizedBox(
height: 50,
child: Center(
child: Text(
'Signature',
style: TextStyle(fontSize: 20),
),
),
),
Signature(
key: const Key('signature'),
controller: _controller,
height: 300,
width: 350,
backgroundColor: Colors.grey[200]!,
),
],
),

Now, we will add the BottomAppBar() method. In this method, we will add three ElevatedButton(). The first button function called ‘Undo’ means make of no effect or as if not done. The second button function is called ‘Redo’ which means to do it over or again. The last button function is called ‘Clear’ means to remove things that are not wanted.

bottomNavigationBar: BottomAppBar(
child: Container(
decoration: const BoxDecoration(color: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.undo());
},
child: const Text("Undo")),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.redo());
},
child: const Text("Redo")),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.clear());
},
child: const Text("Clear")),
],
),
),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_digital_signature_demo/splash_screen.dart';
import 'package:signature/signature.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
// initialize the signature controller
final SignatureController _controller = SignatureController(
penStrokeWidth: 1,
penColor: Colors.red,
exportBackgroundColor: Colors.transparent,
exportPenColor: Colors.black,
onDrawStart: () => log('onDrawStart called!'),
onDrawEnd: () => log('onDrawEnd called!'),
);

@override
void initState() {
super.initState();
_controller.addListener(() => log('Value changed'));
}

@override
void dispose() {
_controller.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Digital Signature Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView(
children: <Widget>[
const SizedBox(
height: 50,
child: Center(
child: Text(
'Signature',
style: TextStyle(fontSize: 20),
),
),
),
Signature(
key: const Key('signature'),
controller: _controller,
height: 300,
width: 350,
backgroundColor: Colors.grey[200]!,
),
],
),
bottomNavigationBar: BottomAppBar(
child: Container(
decoration: const BoxDecoration(color: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.undo());
},
child: const Text("Undo")),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.redo());
},
child: const Text("Redo")),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
setState(() => _controller.clear());
},
child: const Text("Clear")),
],
),
),
),
);
}
}

Conclusion:

In the article, I have explained the Digital Signature in a flutter; you can modify this code according to your choice. This was a small introduction to Digital Signature On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Digital Signature in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on Digital Signature Using the signature package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Explore Tic-Tac-Toe Game In Flutter

0

To track down Flutter, a well-known open-source framework for making constructed mobile, web, and system applications from a solitary codebase, play the immortal round of spasm tic-tac-toe.

In this article, we will Explore the Tic-Tac-Toe Game In Flutter. We perceive how to execute a demo program. We will show you how to create a tic-tac-toe game in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The demo video below shows how to make a tic-tac-toe game in Flutter for beginners and how the game will work in your Flutter applications. We will offer a user the opportunity to play the game, which will be shown on their device.

Demo Module::


How to implement code in dart file :

You need to implement it in your code respectively:

Ensure Flutter and Dart are set up on your PC before we start writing code. If not, configure your environment using the official Flutter installation manual.

Once Flutter is installed, use the following command to start a new Flutter project:

flutter create flutter_tic_tac_toe_game_demo

This will create a brand-new Flutter project with the name flutter_tic_tac_toe_game_demo. Please click here to access the project directory:

cd flutter_tic_tac_toe_game_demo

Create a new dart file called game_screen.dart inside the lib folder.

First, we will create a list of strings called gameGridis equal to the square bracket. Also, create a String currentPlayer.

List<List<String>> gameGrid = [];
String currentPlayer = '';

Let’s create an initState method. In this method, we will add the startGame() method. In this method, we will add game rationale right into it. We’ll utilize a 2D list to represent the game state where every cell can either be unfilled, “X,” or “O.” We’ll likewise watch the dynamic player.

@override
void initState() {
super.initState();
startGame();
}
void startGame() {
gameGrid = List.generate(3, (_) => List.filled(3, ''));
currentPlayer = 'X';
setState(() {});
}

In this body part, we will add a Column widget. In this widget, we will add a current player which means they will show a playing active player. We will create a game board so, we will use GridView.builder() method.

Column(
children: [
const SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Current Player:',style: TextStyle(fontSize: 18),),
Text(currentPlayer,style: const TextStyle(fontSize: 18,fontWeight: FontWeight.bold),)
],
),
const SizedBox(height: 50,),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 9,
itemBuilder: (context, index) {
final row = index ~/ 3;
final col = index % 3;
return GestureDetector(
onTap: () => onCellTapped(row, col),
child: Container(
decoration: BoxDecoration(
border: Border.all(),
),
child: Center(
child: Text(
gameGrid[row][col],
style: const TextStyle(fontSize: 48),
),
),
),
);
},
),
),
ElevatedButton(onPressed: resetGame,style: ElevatedButton.styleFrom(
backgroundColor: Colors.green.shade300, // Background color
), child: const Text("Reset Game"),)
],
),

In this technique, we will add a 3×3 grid of cells built utilizing a GridView.builder method. In this method, we will add the gridDelegate was a SliverGridDelegateWithFixedCrossAxisCount(), and inside a crossAxisCount was a three. We will add that itemCount was a nine, itemBuilder we will return with GestureDetector() method. In this method, to deal with tapping, we epitomize every cell in a GestureDetector.

The onCellTapped function, which we’ll execute below, is summoned when a cell is tapped. Likewise, we will make an ElevatedButton. On this button, we will add the onPressed() function. In this function, we will add the resetGame function, and add the ElevatedButton.styleFrom() function. Inside the function, we will add backgroundColor was Colors.green.shade300, and its child we will add text “Reset Game”, which we’ll execute beneath, is invoked when a button is tapped.

Let’s create a onCellTapped() function:

The checkForWinner function in this code searches for win conditions while the onCellTapped function updates the board at whatever point a cell is tapped. Utilizing the showWinnerDialog function, we show a dialog on the off chance that there is a winner or a draw.

void onCellTapped(int row, int col) {
if (gameGrid[row][col].isEmpty) {
setState(() {
gameGrid[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
});


String winner = checkForWinner();
if (winner.isNotEmpty) {
showWinnerDialog(winner);
}
}
}


void showWinnerDialog(String winner) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Game Over'),
content:
Text(winner == 'Draw' ? 'It\'s a draw!' : 'Player $winner wins!'),
actions: [
TextButton(
onPressed: () {
resetGame();
Navigator.pop(context);
},
child: const Text('Play Again'),
),
],
),
);
}

Let’s create a checkForWinner() function:

These functions are in charge of determining if the game has a winner or a draw and displaying a dialog when it is over.

String checkForWinner() {
for (int i = 0; i < 3; i++) {
if (gameGrid[i][0] == gameGrid[i][1] &&
gameGrid[i][1] == gameGrid[i][2] &&
gameGrid[i][0].isNotEmpty) {
return gameGrid[i][0];
}
if (gameGrid[0][i] == gameGrid[1][i] &&
gameGrid[1][i] == gameGrid[2][i] &&
gameGrid[0][i].isNotEmpty) {
return gameGrid[0][i];
}
}
if (gameGrid[0][0] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][2] &&
gameGrid[0][0].isNotEmpty) {
return gameGrid[0][0];
}
if (gameGrid[0][2] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][0] &&
gameGrid[0][2].isNotEmpty) {
return gameGrid[0][2];
}
bool isDraw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (gameGrid[i][j].isEmpty) {
isDraw = false;
break;
}
}
}
if (isDraw) {
return 'Draw';
}
return '';
}

Let’s create a resetGame() function:

To allow participants to restart a game, we should at long last form the resetGame function. When the “Play Again” button in the dialog is hit, we utilize this function to reset the game board and the current player.

void resetGame() {
setState(() {
startGame();
});
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Outputs

Code File:


import 'package:flutter/material.dart';

class GameScreen extends StatefulWidget {
const GameScreen({super.key});

@override
State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
List<List<String>> gameGrid = [];
String currentPlayer = '';
@override
void initState() {
super.initState();
startGame();
}
void startGame() {
gameGrid = List.generate(3, (_) => List.filled(3, ''));
currentPlayer = 'X';
setState(() {});
}

void onCellTapped(int row, int col) {
if (gameGrid[row][col].isEmpty) {
setState(() {
gameGrid[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
});
String winner = checkForWinner();
if (winner.isNotEmpty) {
showWinnerDialog(winner);
}
}
}

String checkForWinner() {
for (int i = 0; i < 3; i++) {
if (gameGrid[i][0] == gameGrid[i][1] &&
gameGrid[i][1] == gameGrid[i][2] &&
gameGrid[i][0].isNotEmpty) {
return gameGrid[i][0];
}
if (gameGrid[0][i] == gameGrid[1][i] &&
gameGrid[1][i] == gameGrid[2][i] &&
gameGrid[0][i].isNotEmpty) {
return gameGrid[0][i];
}
}
if (gameGrid[0][0] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][2] &&
gameGrid[0][0].isNotEmpty) {
return gameGrid[0][0];
}
if (gameGrid[0][2] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][0] &&
gameGrid[0][2].isNotEmpty) {
return gameGrid[0][2];
}
bool isDraw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (gameGrid[i][j].isEmpty) {
isDraw = false;
break;
}
}
}
if (isDraw) {
return 'Draw';
}
return '';
}

void showWinnerDialog(String winner) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Game Over'),
content:
Text(winner == 'Draw' ? 'It\'s a draw!' : 'Player $winner wins!'),
actions: [
TextButton(
onPressed: () {
resetGame();
Navigator.pop(context);
},
child: const Text('Play Again'),
),
],
),
);
}

void resetGame() {
setState(() {
startGame();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text("Flutter Tic-Tac-Toe Game Demo"),
centerTitle: true,
backgroundColor: Colors.green.shade300,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Current Player:',style: TextStyle(fontSize: 18),),
Text(currentPlayer,style: const TextStyle(fontSize: 18,fontWeight: FontWeight.bold),)
],
),
const SizedBox(height: 50,),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 9,
itemBuilder: (context, index) {
final row = index ~/ 3;
final col = index % 3;
return GestureDetector(
onTap: () => onCellTapped(row, col),
child: Container(
decoration: BoxDecoration(
border: Border.all(),
),
child: Center(
child: Text(
gameGrid[row][col],
style: const TextStyle(fontSize: 48),
),
),
),
);
},
),
),
ElevatedButton(onPressed: resetGame,style: ElevatedButton.styleFrom(
backgroundColor: Colors.green.shade300, // Background color
), child: const Text("Reset Game"),)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Tic-Tac-Toe Game In Flutter; you can modify this code according to your choice. This was a small introduction to the Tic-Tac-Toe Game In Flutter In Dart User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Tic-Tac-Toe Game in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on the Tic-Tac-Toe Game in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.