Google search engine
Home Blog Page 10

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.

Related: Implement GraphQL with Flutter


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.


Zebra Striped ListView In Flutter

0

This blog will explore the Zebra Striped ListView In Flutter. We perceive how to execute a demo program. We will show you how to create a zebra-striped listview 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

Implementation

Code Implement

Code File



Introduction:

Envision you have a list of things on your phone or PC screen. Presently, I envision that everything on the list has an alternate color. For instance, the main thing may be white, the subsequent thing may be dark, the third thing may be white once more, etc. This is known as a zebra-striped list view. It is called that since it seems to be the stripes of a zebra. This is expected to make the list more alluring and straightforward. It can assist you with finding what you are searching for quicker and better.

Demo Module :


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.

To make a striped ListView (with the ListView.builder() constructor) in Flutter, you can utilize the itemBuilder parameter to return an alternate widget for everything in light of its index. In by far most cases, you can utilize a ternary operator to shift back and alternate between 2 colors for the background of everything as displayed beneath:

ListView.builder(
itemCount: 132,
itemBuilder: (context, index) {
return Container(
// alternate colors
color: index % 2 == 0 ? Colors.red : Colors.green,
/*...*/
);
},
);

First, we will generate dummy data for the list

final List<String> items = List.generate(100, (index) => 'Item $index');

Then, we will add the ListView.builder() method to the body part. In this method, we will add itemCount was items. length. Also, we will add the itemBuilder function. In this, we will add the final color is equal to the index.isEven then shows a white color else cyan color.

ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final color = index.isEven ? Colors.white : Colors.cyan[100];
return Container(
color: color,
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 24),
child: Text(
items[index],
style: const TextStyle(fontSize: 18),
),
);
},
),

Then, we will return a container with white color, padding, and items[index].

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_zebra_list_view_demo/splash_screen.dart';

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
// hide the debug banner
debugShowCheckedModeBanner: false,
title: 'KindaCode.com',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Splash(),
);
}
}

class MyHomePage extends StatelessWidget {
MyHomePage({super.key});

final List<String> items = List.generate(100, (index) => 'Item $index');

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: const Text('Flutter Zebra Striped ListView Demo'),
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final color = index.isEven ? Colors.white : Colors.cyan[100];
return Container(
color: color,
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 24),
child: Text(
items[index],
style: const TextStyle(fontSize: 18),
),
);
},
),
);
}
}

Conclusion:

In the article, I have explained the Zebra Striped ListView In Flutter; you can modify this code according to your choice. This was a small introduction to the Zebra Striped ListView 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 Digital Signature in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on Zebra Striped ListView 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.

Related: Grouped ListView in Flutter

Related: Sortable ListView In Flutter


 Dart Classes and Objects In Flutter

0

It is essential to comprehend the standards of object-oriented programming in Flutter while building applications. Classes and objects are the premises of OOP. You can without much of a stretch structure your application and organize your code.

Classes assist developers with characterizing properties and ways of behaving for various parts by going about as diagrams for object creation. Figuring out how to make and involve classes and objects in Flutter will help in making application development more versatile and effective.

This article will explore the Dart Classes and Objects In Flutter. We will execute a demo program and show the fundamentals of making classes and objects in Flutter that establish a simple starting point for any beginner in any case your application.

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 Class and Object in Flutter?

Why are Classes and Objects Essential in Flutter?

Build a Basic Class and Object in Flutter

Difference Between Class and Object in Flutter

Conclusion



What is Class and Object in Flutter?

In Flutter, a class is a blueprint for creating objects. It defines the properties (variables) and behaviors (methods) that the objects created from the class will have. A class allows you to organize your code by grouping related data and functionality.

Here is a basic example of making a class in Flutter:

class Bike{
  String model;
  int year;

  void displayInfo() {
    print('Model: $model, Year: $year');
  }
}

In this demo model, a Bike is a class with two properties: model and year. The displayInfo() strategy prints out the data about the bike.

Presently object is an unequivocal instance of a class, as each class is an overall element characterizing what an object is. One more method for putting it is that an object is a more unambiguous illustration of a class, as it has genuine values added to class properties.

This is the way you make objects in a Flutter from the bike class:

void main() {
  Bike myBike = Bike();  
  myBike.model = 'Apache';
  myBike.year = 2025;

  myBike.displayInfo(); 
}

In this demo example, myBike is an object of the Bike class. The object holds explicit information (‘Apache’ and 2025) and can utilize the displayInfo() technique to show that information.

Why are Classes and Objects Essential in Flutter?

Classes and objects are fundamental in Flutter since they assist with arranging code by gathering related information and working together. This makes the application more straightforward to manage, read, and scale as it develops.

Utilizing dart classes permits developers to make reusable parts, diminishing duplication and further developing effectiveness. Objects rejuvenate these classes by holding explicit information and ways of behaving, assisting you with building a fundamental Flutter application all the more really.

Build a Basic Class and Object in Flutter

  • Create a New Flutter Project
    Begin by making another Flutter project utilizing your favored IDE, such as Visual Studio Code or Android Studio. Open the terminal and run the order flutter to create project_name. This will set up the essential Flutter application structure you want to start. Presently, explore the lib organizer where you’ll compose your Dart code for building an essential class and object in Flutter.
  • Define a Class in Dart
    Inside the lib folder, create a new Dart file. Define your class using the class keyword. For example, if you’re creating a class to represent a “Bike,” you can structure it with properties like model and year. Here’s a class in Dart example:
  • Inside the lib folder, make another Dart file. Characterize your class utilizing the class keyword. For instance, if you’re making a class to address a “Bike,” you can structure it with properties like model and year.

Here is a class in the Dart model:

class Bike{
  String model;
  int year;
}
  • Add a Constructor to Your Class
    To instate your class properties, add a constructor. A dart class constructor is utilized to assign values to the class properties when an object is made. In the Bike class, the constructor would seem to be this:
Bike(this.model, this.year);
  • Create an Object from the Class
    Now that your class is prepared, you can make an object. In your main. dart file, launch the class by utilizing the new keyword or straightforwardly without it. For instance:
Bike myBike = Bike('Apache', 2025);

Here, you create an object named myCar from the Car class. This is how Dart creates objects without a class, but you still need to define it in your project.

Here, you make an object named myBike from the Bike class. This is how Dart makes objects without a class, yet you need to characterize it in your project.

  • Running the App
    At long last, run your application utilizing the flutter run command in the terminal. This will order and execute your Flutter application, permitting you to see the consequences of your group and object execution. Remember to test various situations by changing object properties or adding strategies to your class.

Difference Between Class and Object in Flutter

AspectClassObject
DefinitionA class is a plan that characterizes properties and strategies.An object is an instance of a class that holds genuine data.
PurposeIt fills in as a layout to characterize how an object ought to act.It is a particular substance made given the class definition.
CreationA class is characterized by utilizing the class keyword.You make an object in Dart by starting up the class.
InitializationClasses can have programmed initializers in constructors to set default values for properties.Objects get introduced with values characterized in the class constructor.
Exampleclass Bike{ String color; void drive() {…} }Bike myBike = Bike(); – This makes an object of the Bike class.

Conclusion:

In the article, I have explained the Dart Classes and Objects In Flutter; you can modify this code according to your choice. This was a small introduction to Dart Classes and Objects 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 Dart Classes and Objects In Flutter in your projectsClasses coordinate your code, and objects fill that construction with true communications. As you become familiar with these fundamentals, you will want to make more proficient and reusable parts in your Flutter 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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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.


Interactive Video Grid In Flutter

0

Flutter has arisen as an incredible tool for building outwardly rich and responsive applications. One of its numerous capacities is making intelligent media-rich parts like a video grid.

In this article, we will explore the Interactive Video Grid In Flutter. We will execute a demo program and show to user-interactive video grid utilizing the video_player and flutter_bloc package 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.

For Video Player :

video_player | Flutter package
Flutter plugin for displaying inline video with other Flutter widgets on Android, iOS, and web.pub.dev

For Flutter Bloc:

flutter_bloc | Flutter package
Flutter Widgets that make it easy to implement the BLoC (Business Logic Component) design pattern. Built to be used…pub.dev


Table Of Contents::

Introduction

Features

Implementation

Code Implement

Code File

Github

Conclusion



Introduction:

An interactive video grid is a collection of videos organized in a grid layout where users can connect with individual video things. This powerful cooperation guarantees that the connection point is natural and drawing in, particularly for applications like media libraries, video tutorial exercises, or e-commerce platform stages exhibiting item demos.

This demo video shows how to create an interactive video grid in Flutter and how an interactive video grid will work using the video_player and flutter_bloc packages in your Flutter applications. We will show a user that tapping or hovering over a video starts its playback, while others pause. It will be shown on your device.

Demo Module::


Features:

  • Videos are shown in a flawless grid format.
  • Users can play a video by tapping or drifting on it.
  • At the point when a video is done, a placeholder picture is shown.
  • Just a single video plays all at once to save assets and keep up with clarity.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
video_player: ^2.9.2
flutter_bloc: ^9.0.0

Step 2: Import

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:video_player/video_player.dart';

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

Code Implement:

You need to implement it in your code respectively:

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

First, we need a model to represent each video item model. In this class, we will add three final strings url, title, and description,

class VideoItemModel {
final String url;
final String title;
final String description;

VideoItemModel({required this.url, required this.title, required this.description});
}

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

In this file, we will oversee the state with bloc using flutter_bloc, we guarantee just a single video plays all at once.

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:video_player/video_player.dart';

class VideoCubit extends Cubit<int?> {
final Map<int, VideoPlayerController> _controllers = {};

VideoCubit() : super(null);

void registerController(int index, VideoPlayerController controller) {
_controllers[index] = controller;
}

void playVideo(int index) {
for (var entry in _controllers.entries) {
if (entry.key == index) {
entry.value.play();
} else {
entry.value.pause();
}
}
emit(index);
}

void stopVideo() {
for (var controller in _controllers.values) {
controller.pause();
}
emit(null);
}
}

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

In this file, we will create a new class VideoGridPage(). This class displays the grid of video items like title, description, and videoUrls.

class VideoGridPage extends StatelessWidget {
final List<VideoItemModel> videoItems = List.generate(
10,
(index) => VideoItemModel(
url: videoUrls[index % videoUrls.length],
title: 'Demo Video $index',
description: 'This is an interactive video of animal $index.',
),
);

static const List<String> videoUrls = [
'https://www.sample-videos.com/video321/mp4/720/big_buck_bunny_720p_1mb.mp4',
];

VideoGridPage({super.key});

@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => VideoCubit(),
child: Scaffold(
appBar: AppBar(title: const Text('Flutter Interactive Video Grid'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.orangeAccent.shade100,),
body: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
mainAxisExtent: 280, // Consistent height for grid items
),
itemCount: videoItems.length,
itemBuilder: (context, index) {
return VideoGridItem(index: index, videoItem: videoItems[index]);
},
),
),
);
}
}

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

In this file, VideoGridItem class handles the video playback and interaction.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_interactive_video_grid/video_card.dart';
import 'package:flutter_interactive_video_grid/video_cubit.dart';
import 'package:flutter_interactive_video_grid/video_item_model.dart';
import 'package:video_player/video_player.dart';

class VideoGridItem extends StatefulWidget {
final int index;
final VideoItemModel videoItem;

const VideoGridItem(
{super.key, required this.index, required this.videoItem});

@override
_VideoGridItemState createState() => _VideoGridItemState();
}

class _VideoGridItemState extends State<VideoGridItem> {
VideoPlayerController? _controller;
bool _isLoading = true;

@override
void initState() {
super.initState();
_initializeController();
}

void _initializeController() {
_controller = VideoPlayerController.network(widget.videoItem.url)
..initialize().then((_) {
if (mounted) {
context
.read<VideoCubit>()
.registerController(widget.index, _controller!);
setState(() {
_isLoading = false;
});
}
});
}

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

@override
Widget build(BuildContext context) {
return BlocBuilder<VideoCubit, int?>(
builder: (context, playingIndex) {
final isPlaying = playingIndex ==
widget.index;
return GestureDetector(
onPanDown: (_) {
context
.read<VideoCubit>()
.playVideo(widget.index);
},
child: VideoCard(
videoItem: widget.videoItem,
controller: _controller,
isPlaying: isPlaying,
),
);
},
);
}
}

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

In this file, we will create a new class VideoCard(). This class encapsulates the entire card UI, delegating its parts to specialized sub-widgets.

import 'package:flutter/material.dart';
import 'package:flutter_interactive_video_grid/video_details.dart';
import 'package:flutter_interactive_video_grid/video_item_model.dart';
import 'package:flutter_interactive_video_grid/video_thumbnail.dart';
import 'package:video_player/video_player.dart';

class VideoCard extends StatelessWidget {
final VideoItemModel videoItem;
final VideoPlayerController? controller;
final bool isPlaying;

const VideoCard({
super.key,
required this.videoItem,
this.controller,
required this.isPlaying,
});

@override
Widget build(BuildContext context) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 4,
child: Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
VideoThumbnail(controller: controller, isPlaying: isPlaying),
VideoDetails(
title: videoItem.title, description: videoItem.description),
],
),
),
);
}
}

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

In this file, we will create a new class VideoThumbnail (). This class displays either the video player or a placeholder image depending on whether the video is initialized and currently playing.

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

class VideoThumbnail extends StatelessWidget {
final VideoPlayerController? controller;
final bool isPlaying;

const VideoThumbnail({super.key,
this.controller,
required this.isPlaying,
});

@override
Widget build(BuildContext context) {
return Expanded(
child: Stack(
alignment: Alignment.center,
children: [
if (controller != null && controller!.value.isInitialized && isPlaying)
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: SizedBox(
width: double.infinity,
height: double.infinity,
child: VideoPlayer(controller!),
),
)
else
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: Image.network(
'https://www.sample-videos.com/img/Sample-png-image-200kb.png',
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
),
],
),
);
}
}

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

In this file, we will create a new class VideoDetails(). This class combines the title and description into a single widget for simplicity and better organization.

import 'package:flutter/material.dart';

class VideoDetails extends StatelessWidget {
final String title;
final String description;

const VideoDetails({super.key,
required this.title,
required this.description,
});

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
description,
style: const TextStyle(
fontSize: 14,
color: Colors.grey,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
);
}
}

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

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_interactive_video_grid/splash_screen.dart';
import 'package:flutter_interactive_video_grid/video_cubit.dart';
import 'package:flutter_interactive_video_grid/video_grid_item.dart';
import 'package:flutter_interactive_video_grid/video_item_model.dart';

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: Splash(),
);
}
}

class VideoGridPage extends StatelessWidget {
final List<VideoItemModel> videoItems = List.generate(
10,
(index) => VideoItemModel(
url: videoUrls[index % videoUrls.length],
title: 'Demo Video $index',
description: 'This is a interactive video of animal $index.',
),
);

static const List<String> videoUrls = [
'https://www.sample-videos.com/video321/mp4/720/big_buck_bunny_720p_1mb.mp4',
];

VideoGridPage({super.key});

@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => VideoCubit(),
child: Scaffold(
appBar: AppBar(title: const Text('Flutter Interactive Video Grid'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.orangeAccent.shade100,),
body: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
mainAxisExtent: 280, // Consistent height for grid items
),
itemCount: videoItems.length,
itemBuilder: (context, index) {
return VideoGridItem(index: index, videoItem: videoItems[index]);
},
),
),
);
}
}

Conclusion:

In the article, I have explained the Interactive Video Grid in a flutter; you can modify this code according to your choice. This was a small introduction to Interactive Video Grid 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 Interactive Video Grid in your flutter projectsWe will show you what the Introduction is. Make a demo program for working on an Interactive Video Grid Using the video_player and flutter_bloc 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.


Github:

Full source code of Flutter Interactive Video Grid:

GitHub – flutter-devs/flutter_interactive_video_grid
Contribute to flutter-devs/flutter_interactive_video_grid development by creating an account on GitHub.github.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! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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.

Related: Interactive Viewer In Flutter


3D Column Chart In Flutter

0

In this article, we will explore the 3D Column Chart In Flutter. We will implement a demo program and show you how to create a visually striking 3D Column Chart using the Syncfusion Flutter Charts 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.

For Syncfusion Flutter Charts:

syncfusion_flutter_charts 28.1.33 | Flutter package
A Flutter Charts library which includes data visualization widgets such as cartesian and circular charts, to create…pub.dev


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

A Column Chart is a compelling strategy for addressing categorical information utilizing vertical bars. It is great for contrasting information across various gatherings, for this situation, the mobile application development by various framework.

This demo video shows how to create a 3D column chart in Flutter and how a 3D column chart will work using theSyncfusion Flutter Charts in your Flutter applications. We will show a user that we will make a 3d impact for the column track and utilizing a custom series renderer, you can characterize a custom painter to render 3D components that add profundity and interactivity to your chart. It will be shown on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
syncfusion_flutter_charts: ^28.1.33

Step 2: Import

import 'package:syncfusion_flutter_charts/charts.dart';

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

Code Implement:

You need to implement it in your code respectively:

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

In the main. dart file, we will initialize the data for the chart. Now, create a language data model that represents the framework’s name and language in percentages.

class LanguageData {
LanguageData(this.framework, this.languagePercent);
final String framework;
final double languagePercent;
}

Next, a list will be initialized to hold the framework’s language data, adding color data for the oval shape at the top and language data for each framework.

  late List<LanguageData> _languageData;
late Map<String, Color> _cylinderColors;
late Map<String, Color> _topOvalColors;

@override
void initState() {
_languageData = <LanguageData>[
LanguageData('Flutter', 80.87),
LanguageData('React', 75.56),
LanguageData('Ionic', 60.92),
LanguageData('Xamarin', 55.22),
LanguageData('Angular', 45.22),
LanguageData('JQuery', 39.25),
];
_cylinderColors = {
'Flutter': const Color.fromARGB(255, 178, 52, 43),
'React': const Color.fromARGB(255, 125, 31, 142),
'Ionic': const Color.fromARGB(255, 8, 133, 120),
'Xamarin': const Color.fromARGB(255, 25, 108, 176),
'Angular': const Color.fromARGB(255, 92, 63, 53),
'JQuery': const Color.fromARGB(255, 139, 126, 4)
};
_topOvalColors = {
'Flutter': const Color.fromARGB(255, 210, 83, 74),
'React': const Color.fromARGB(255, 145, 56, 160),
'Ionic': const Color.fromARGB(255, 47, 150, 140),
'Xamarin': const Color.fromARGB(255, 59, 128, 185),
'Angular': const Color.fromARGB(255, 117, 80, 67),
'JQuery': const Color.fromARGB(255, 179, 163, 15)
};
super.initState();
}

In the body part, we will deliver a Flutter Column Chart with a track, a single ColumnSeries is utilized to envision language information close by a noticeable foundation track. The X-axis is set to CategoryAxis, addressing categorical information like framework names, while the Y-axis is set to NumericAxis for numeric values to show the language utilized in percentage.

How about we utilize the ChartTitle widget to add and alter the chart title. The title is aligned to the center utilizing the alignment property, and we’ve set the ChartAlignment value as the center. The text property is utilized to set the chart’s title.

The onDataLabelRender callback is utilized to change the appearance of data labels. The text property is updated to incorporate a percentage symbol close to the shown value. We should empower the TooltipBehavior to show the extra data when hovering over data points. The onTooltipRender callback modifies the tooltip text by splitting it into an organized header and value.

body: SfCartesianChart(
plotAreaBorderWidth: 0,
title: const ChartTitle(
alignment: ChartAlignment.center,
text:
'Percentage Mobile Application Development Framework',
),
tooltipBehavior: TooltipBehavior(enable: true),
onTooltipRender: (TooltipArgs tooltipArgs) {
List<String> tooltipText = tooltipArgs.text!.split(' : ');
tooltipArgs.header = tooltipText[0];
tooltipArgs.text = '${tooltipText[1]}%';
},
onDataLabelRender: (DataLabelRenderArgs dataLabelArgs) {
dataLabelArgs.text = '${dataLabelArgs.text}%';
},
primaryXAxis: CategoryAxis(
majorGridLines: const MajorGridLines(width: 0),
majorTickLines: const MajorTickLines(width: 0),
axisLine: const AxisLine(width: 0),
axisLabelFormatter: (axisLabelRenderArgs) {
final String countryName = axisLabelRenderArgs.text;
TextStyle textStyle = Theme.of(context)
.textTheme
.titleSmall!
.copyWith(color: _cylinderColors[countryName]);
return ChartAxisLabel(countryName, textStyle);
},
labelPosition: ChartDataLabelPosition.inside,
),
primaryYAxis: const NumericAxis(
isVisible: true,
plotOffsetStart: 50,
),
series: <CartesianSeries<LanguageData, String>>[
ColumnSeries(
dataSource: _languageData,
xValueMapper: (LanguageData data, index) => data.framework,
yValueMapper: (LanguageData data, index) =>
data.languagePercent,
pointColorMapper: (LanguageData data, index) =>
_cylinderColors[data.framework],
animationDuration: 2000,
isTrackVisible: true,
trackColor: const Color.fromARGB(255, 191, 188, 188),
dataLabelSettings: const DataLabelSettings(
isVisible: true,
labelAlignment: ChartDataLabelAlignment.middle),
onCreateRenderer: (ChartSeries series) {
return CustomColumn3DSeries(_topOvalColors);
},
),
],
)

For the primaryXAxis, we’ll utilize a CategoryAxis to address frameworks. We’ll alter the appearance by eliminating the majorGridLinesmajorTickLines, and axisLine. We’ll likewise customize the labelPosition to show it inside the chart.

For the primaryYAxis, we will involve a NumericAxis to address the language-involved values in a percentage format. We’ll set the isVisible property to false to conceal the Y-axis labels. Additionally, we’ll change the plotOffsetStart values to 50 to add padding at the beginning of the plot area, enhancing the chart’s visual allure.

This series overlays the language information onto the track. The yValueMapper is utilized to map the percentage of language to the Y-axis, while the pointColorMapper progressively assigns colors to the columns based on the framework name. This guarantees every data point is outwardly particular and simple to interpret. Furthermore, the animationDuration property is set to 2000 milliseconds, which animates the column series smoothly over 2 seconds when the chart is rendered.

Now we will create the CustomColumn3DSeries class extends the ColumnSeriesRenderer to make a custom 3D representation for the column series given on the LanguageData model. The createSegment technique is overridden to return a custom column segment, _CustomColumn3DPaint, which handles drawing 3D impacts for every column.

class CustomColumn3DSeries
extends ColumnSeriesRenderer<LanguageData, String> {
CustomColumn3DSeries(this.topOvalColors);

final Map<String, Color> topOvalColors;

@override
ColumnSegment<LanguageData, String> createSegment() {
return _CustomColumn3DPaint(topOvalColors);
}
}

class _CustomColumn3DPaint extends ColumnSegment<LanguageData, String> {
_CustomColumn3DPaint(this.topOvalColors);

final Map<String, Color> topOvalColors;

@override
void onPaint(Canvas canvas) {
final String countryName = series.xRawValues[currentSegmentIndex]!;
final double trackerTop = series.pointToPixelY(0, 100);
final Rect trackerTopOval = _ovalRect(trackerTop);
final Rect bottomOval = _ovalRect(segmentRect!.bottom);
final Rect animatedTopOval = _ovalRect(segmentRect!.bottom -
((segmentRect!.bottom - segmentRect!.top) * animationFactor));

super.onPaint(canvas);
canvas.drawOval(trackerTopOval,
Paint()..color = const Color.fromARGB(255, 204, 201, 201));
canvas.drawOval(bottomOval, Paint()..color = fillPaint.color);
canvas.drawOval(
animatedTopOval, Paint()..color = topOvalColors[countryName]!);
}

Rect _ovalRect(double ovalCenterY) {
const double ovalRadius = 15;
return Rect.fromLTRB(segmentRect!.left, ovalCenterY - ovalRadius,
segmentRect!.right, ovalCenterY + ovalRadius);
}
}

The __CustomColumn3DPaint class extends ColumnSegment and carries out the onPaint method to add a custom 3D paint. Inside the onPaint method. The ovalRect helper technique produces a rectangular bounding box for the ovals. It takes the center Y-coordinate and works out the aspects utilizing a fixed radius of 15. The subsequent 3D series impact gives the columns an outwardly distinct appearance and makes the data portrayal more engaging and instinctive.

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

Code File:

import 'package:flutter/material.dart';
import 'package:fluttre_3d_column_chart/splash_screen.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

void main() {
runApp(
const MaterialApp(
home: Splash(),
debugShowCheckedModeBanner: false,
),
);
}

class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
late List<LanguageData> _languageData;
late Map<String, Color> _cylinderColors;
late Map<String, Color> _topOvalColors;

@override
void initState() {
_languageData = <LanguageData>[
LanguageData('Flutter', 80.87),
LanguageData('React', 75.56),
LanguageData('Ionic', 60.92),
LanguageData('Xamarin', 55.22),
LanguageData('Angular', 45.22),
LanguageData('JQuery', 39.25),
];
_cylinderColors = {
'Flutter': const Color.fromARGB(255, 178, 52, 43),
'React': const Color.fromARGB(255, 125, 31, 142),
'Ionic': const Color.fromARGB(255, 8, 133, 120),
'Xamarin': const Color.fromARGB(255, 25, 108, 176),
'Angular': const Color.fromARGB(255, 92, 63, 53),
'JQuery': const Color.fromARGB(255, 139, 126, 4)
};
_topOvalColors = {
'Flutter': const Color.fromARGB(255, 210, 83, 74),
'React': const Color.fromARGB(255, 145, 56, 160),
'Ionic': const Color.fromARGB(255, 47, 150, 140),
'Xamarin': const Color.fromARGB(255, 59, 128, 185),
'Angular': const Color.fromARGB(255, 117, 80, 67),
'JQuery': const Color.fromARGB(255, 179, 163, 15)
};
super.initState();
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.tealAccent.shade100,
title: const Text("Flutter 3D Column Chart Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: SfCartesianChart(
plotAreaBorderWidth: 0,
title: const ChartTitle(
alignment: ChartAlignment.center,
text:
'Percentage Mobile Application Development Framework',
),
tooltipBehavior: TooltipBehavior(enable: true),
onTooltipRender: (TooltipArgs tooltipArgs) {
List<String> tooltipText = tooltipArgs.text!.split(' : ');
tooltipArgs.header = tooltipText[0];
tooltipArgs.text = '${tooltipText[1]}%';
},
onDataLabelRender: (DataLabelRenderArgs dataLabelArgs) {
dataLabelArgs.text = '${dataLabelArgs.text}%';
},
primaryXAxis: CategoryAxis(
majorGridLines: const MajorGridLines(width: 0),
majorTickLines: const MajorTickLines(width: 0),
axisLine: const AxisLine(width: 0),
axisLabelFormatter: (axisLabelRenderArgs) {
final String countryName = axisLabelRenderArgs.text;
TextStyle textStyle = Theme.of(context)
.textTheme
.titleSmall!
.copyWith(color: _cylinderColors[countryName]);
return ChartAxisLabel(countryName, textStyle);
},
labelPosition: ChartDataLabelPosition.inside,
),
primaryYAxis: const NumericAxis(
isVisible: true,
plotOffsetStart: 50,
),
series: <CartesianSeries<LanguageData, String>>[
ColumnSeries(
dataSource: _languageData,
xValueMapper: (LanguageData data, index) => data.framework,
yValueMapper: (LanguageData data, index) =>
data.languagePercent,
pointColorMapper: (LanguageData data, index) =>
_cylinderColors[data.framework],
animationDuration: 2000,
isTrackVisible: true,
trackColor: const Color.fromARGB(255, 191, 188, 188),
dataLabelSettings: const DataLabelSettings(
isVisible: true,
labelAlignment: ChartDataLabelAlignment.middle),
onCreateRenderer: (ChartSeries series) {
return CustomColumn3DSeries(_topOvalColors);
},
),
],
),
),
);
}
}

class CustomColumn3DSeries
extends ColumnSeriesRenderer<LanguageData, String> {
CustomColumn3DSeries(this.topOvalColors);

final Map<String, Color> topOvalColors;

@override
ColumnSegment<LanguageData, String> createSegment() {
return _CustomColumn3DPaint(topOvalColors);
}
}

class _CustomColumn3DPaint extends ColumnSegment<LanguageData, String> {
_CustomColumn3DPaint(this.topOvalColors);

final Map<String, Color> topOvalColors;

@override
void onPaint(Canvas canvas) {
final String countryName = series.xRawValues[currentSegmentIndex]!;
final double trackerTop = series.pointToPixelY(0, 100);
final Rect trackerTopOval = _ovalRect(trackerTop);
final Rect bottomOval = _ovalRect(segmentRect!.bottom);
final Rect animatedTopOval = _ovalRect(segmentRect!.bottom -
((segmentRect!.bottom - segmentRect!.top) * animationFactor));

super.onPaint(canvas);
canvas.drawOval(trackerTopOval,
Paint()..color = const Color.fromARGB(255, 204, 201, 201));
canvas.drawOval(bottomOval, Paint()..color = fillPaint.color);
canvas.drawOval(
animatedTopOval, Paint()..color = topOvalColors[countryName]!);
}

Rect _ovalRect(double ovalCenterY) {
const double ovalRadius = 15;
return Rect.fromLTRB(segmentRect!.left, ovalCenterY - ovalRadius,
segmentRect!.right, ovalCenterY + ovalRadius);
}
}

class LanguageData {
LanguageData(this.framework, this.languagePercent);
final String framework;
final double languagePercent;
}

Conclusion:

In the article, I have explained the 3D Column Chart in a flutter; you can modify this code according to your choice. This was a small introduction to 3D Column Chart 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 3D Column Chart in your flutter projectsWe will show you what the Introduction is. Make a demo program for working on a 3D Column Chart Using the Syncfusion Flutter Charts 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! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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.

Related: Dark Mode Implementation

Related: Handling Navigation Stacks


Top Flutter Packages Every Developer Should Know

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 You Need Flutter Packages

How Flutter Packages Enhance Development

How to Choose the Right Flutter Package

How to Integrate Multiple Packages in Your Flutter App

Top Flutter Packages

Testing and Debugging with Packages

Popular Tools to Use Alongside Flutter Packages

Future of Flutter Packages

Conclusion

References


Introduction

Flutter is one of the most popular frameworks for building mobile applications, offering a rich set of features and flexibility. As a growing community, Flutter developers have contributed thousands of packages that can help in making the development process easier, faster, and more efficient. In this blog, we’ll cover the top 10 Flutter packages every developer should know, whether you’re a beginner or a seasoned pro. These packages can improve your app’s performance, add features, and enhance your development workflow.


Why You Need Flutter Packages?

Flutter packages serve as the backbone of the development process, offering reusable solutions for common challenges developers face. Whether you need state management tools, image handling, or more complex features like notifications or real-time databases, Flutter packages save you time by providing pre-built solutions.

As the Flutter ecosystem grows, packages from the community allow developers to focus more on app logic, leaving many of the mundane tasks to the package itself. Instead of re-implementing the same functionalities for each new project, you can incorporate existing packages, speeding up development and improving app quality.


How Flutter Packages Enhance Development

Flutter packages help reduce the amount of code you need to write, lower the chances of bugs, and introduce best practices into your development workflow. They provide powerful tools for:

  • State Management: Simplify how you manage your app’s data and UI updates.
  • Networking: Easily connect to APIs and manage data transfers.
  • UI Components: Quickly implement advanced UI elements that otherwise require custom code.
  • Performance Optimization: Enhance your app’s performance through caching, background tasks, and data storage solutions.
  • Cross-Platform Support: Ensure your app works smoothly on both Android and iOS.

These benefits allow developers to create feature-rich applications while focusing on building a great user experience rather than reinventing the wheel.


How to Choose the Right Flutter Package

What to Consider:

When choosing the right package for your project, it’s important to consider a few key factors:

  • Popularity: Well-maintained packages with a large user base tend to be more reliable and offer better documentation and community support.
  • Compatibility: Ensure the package is compatible with your app’s requirements, Flutter version, and target platforms (iOS, Android).
  • License: Check the package’s license to make sure it fits with your project, especially if you’re working on commercial applications.
  • Documentation: A package with clear, well-written documentation will save you time and headaches down the road.
  • Performance: Some packages, especially UI-heavy ones, might have performance overheads. Always test the performance of the package with your app.

How to Integrate Multiple Packages in Your Flutter App

Best Practices for Integrating Packages:

Sometimes, you may need to use multiple packages in your Flutter project. Here are some best practices to make it easier:

  • Use Dependency Management: Use pubspec.yaml to manage dependencies and ensure that you’re using the correct versions of each package.
  • Keep Package Versions Up-to-Date: Regularly check for package updates to ensure you’re using the latest features and security patches.
  • Modularize Your Code: Break down your code into smaller modules or services that handle specific functionalities (e.g., networking, database, authentication). This makes it easier to manage and update individual packages without affecting the entire project.
  • Testing: Test each package thoroughly to ensure it integrates smoothly into your app without causing bugs or crashes. Consider unit tests for services or components using the packages.

Top Flutter Packages

1. Provider

What It Is:

Provider is one of the most widely used state management solutions in Flutter. It is simple to use and integrates well with the Flutter widget tree.

Why You Should Use It:

Provider allows you to manage state and dependency injection without requiring much boilerplate code. It’s flexible and makes state management more predictable by creating a reactive model for handling app data.

Key Features:

  • Easy to learn and implement.
  • Suitable for small to large projects.
  • Built-in support for asynchronous operations.

How to Use:

class MyState with ChangeNotifier {
int _counter = 0;
int get counter => _counter;

void increment() {
_counter++;
notifyListeners();
}
}

void main() {
runApp(
ChangeNotifierProvider(
create: (context) => MyState(),
child: MyApp(),
),
);
}

2. Dio

What It Is:

Dio is a powerful HTTP client for Flutter, offering advanced features for making HTTP requests and handling responses.

Why You Should Use It:

When working with APIs in Flutter, Dio can be a lifesaver. It supports interceptors, global configuration, form data, request cancellation, and file downloading.

Key Features:

  • Supports HTTP requests (GET, POST, PUT, DELETE, etc.).
  • Advanced configuration options like request and response interceptors.
  • Support for uploading and downloading files.
  • Built-in support for handling errors.

How to Use:

import 'package:dio/dio.dart';

void fetchData() async {
var dio = Dio();
try {
Response response = await dio.get('https://jsonplaceholder.typicode.com/posts');
print(response.data);
} catch (e) {
print(e);
}
}

3. Cached Network Image

What It Is:

This package allows you to load images from the network and cache them for future use. It helps to reduce the number of network requests and provides a better user experience.

Why You Should Use It:

If your app loads a lot of images from the internet, using CachedNetworkImage will save bandwidth and load times by caching images locally.

Key Features:

  • Supports caching images in memory and on the disk.
  • Placeholder and error widgets.
  • Custom cache manager for better control.

How to Use:

CachedNetworkImage(
imageUrl: "https://example.com/image.jpg",
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
);

4. Flutter Local Notifications

What It Is:

Flutter Local Notifications is a package for displaying local notifications on Android, iOS, and macOS.

Why You Should Use It:

Notifications are crucial for engaging users in mobile applications. This package allows you to send notifications even when the app is in the background or terminated.

Key Features:

  • Supports scheduling notifications.
  • Customizable notification content.
  • Works on both Android and iOS.

How to Use:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

void showNotification() async {
var androidDetails = AndroidNotificationDetails(
'your_channel_id',
'your_channel_name',
'your_channel_description',
importance: Importance.high,
priority: Priority.high,
);
var platformDetails = NotificationDetails(android: androidDetails);

await flutterLocalNotificationsPlugin.show(0, 'Title', 'Body', platformDetails);
}

5. Hive

What It Is:

Hive is a lightweight, fast, and secure NoSQL database for Flutter applications.

Why You Should Use It:

If you need a fast local database with minimal setup, Hive is the ideal choice. It allows you to store and retrieve data without relying on SQL.

Key Features:

  • Simple key-value store.
  • Supports encrypting data.
  • No need for a database server.
  • Fast and easy to set up.

How to Use:

import 'package:hive/hive.dart';

void openBox() async {
var box = await Hive.openBox('myBox');
box.put('key', 'value');
print(box.get('key'));
}

6. Flutter Bloc

What It Is:

Flutter Bloc is another powerful state management solution that helps manage complex states in large apps using the BLoC (Business Logic Component) pattern.

Why You Should Use It:

For more structured, scalable applications, Bloc allows for better separation of concerns. It’s a great choice for apps that require robust state management with clear boundaries.

Key Features:

  • BLoC architecture-based.
  • Decouples business logic from UI.
  • Handles multiple events and states in a declarative way.

How to Use:

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);

void increment() => emit(state + 1);
}

void main() {
runApp(
BlocProvider(
create: (context) => CounterCubit(),
child: MyApp(),
),
);
}

7. GetX

What It Is:

GetX is a reactive state management and navigation package for Flutter. It simplifies state management, dependency injection, and route management.

Why You Should Use It:

GetX is very efficient in managing both state and navigation. It simplifies many tasks in Flutter development with minimal code.

Key Features:

  • Simple state management and routing.
  • Dependency injection.
  • Reactive programming with less boilerplate.

How to Use:

import 'package:get/get.dart';

class CounterController extends GetxController {
var counter = 0.obs;

void increment() {
counter++;
}
}

void main() {
runApp(
GetMaterialApp(
home: MyHomePage(),
),
);
}

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final CounterController controller = Get.put(CounterController());

return Scaffold(
appBar: AppBar(title: Text("GetX Example")),
body: Center(
child: Obx(() => Text('Counter: ${controller.counter}')),
),
floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
child: Icon(Icons.add),
),
);
}
}

8. Flutter Fire

What It Is:

FlutterFire is a set of Flutter plugins that enable integration with Firebase services, including authentication, Firestore, Firebase Storage, and more.

Why You Should Use It:

Firebase is a backend-as-a-service that offers a wide range of features such as cloud storage, authentication, and real-time databases, all of which can be easily integrated into your Flutter apps with the FlutterFire package.

Key Features:

  • Firebase Authentication.
  • Cloud Firestore.
  • Firebase Analytics and Firebase Cloud Messaging.
  • Firebase Storage.

How to Use:

import 'package:firebase_auth/firebase_auth.dart';

void signUp() async {
FirebaseAuth auth = FirebaseAuth.instance;
UserCredential userCredential = await auth.createUserWithEmailAndPassword(
email: "test@example.com",
password: "password123",
);
}

9. URL Launcher

What It Is:

URL Launcher is a package that allows you to launch a URL in a mobile platform’s default browser or open other apps (like email clients or phone dialers).

Why You Should Use It:

If you need to open web pages, dial numbers, send emails, or even open specific apps, this package provides an easy way to integrate such functionality into your app.

Key Features:

  • Launch URLs in the browser or in apps.
  • Open phone dialer, SMS app, or email clients.
  • Support for both Android and iOS platforms.

How to Use:

import 'package:url_launcher/url_launcher.dart';

void launchURL() async {
const url = 'https://flutter.dev';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

10. Image Picker

What It Is:

The Image Picker package allows you to pick images from the device gallery or take photos using the device camera.

Why You Should Use It:

This package is essential for any app that needs to capture or select images, such as for profile pictures, posts, or product listings.

Key Features:

  • Pick images from the gallery or camera.
  • Supports both Android and iOS.
  • Easy to implement.

How to Use:

import 'package:image_picker/image_picker.dart';

void pickImage() async {
final picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.camera);

if (pickedFile != null) {
print('Picked image: ${pickedFile.path}');
} else {
print('No image selected');
}
}

Testing and Debugging with Packages

Best Practices for Debugging:

When working with multiple packages in Flutter, debugging can become complex. Here are some tips for managing this:

  • Use Flutter DevTools: Flutter DevTools offer a powerful suite of tools to inspect your app’s state, performance, and logs. Use it to troubleshoot issues caused by packages.
  • Isolate Package Issues: If you’re encountering an issue, try to isolate the problem by commenting out certain parts of the code to see if a particular package is causing the issue.
  • Read Logs: Package errors often show up in the logs. Check your console output and error messages carefully when a package fails to behave as expected.

Popular Tools to Use Alongside Flutter Packages

Tools That Enhance Flutter Development:

In addition to Flutter packages, there are several tools that can help you optimize your development process:

  • FlutterFire: For Firebase integration, including authentication, database, storage, and more.
  • Fastlane: Automates the release process, especially for continuous integration (CI/CD) pipelines.
  • Flutter Inspector: Part of Flutter DevTools, this tool helps you visually debug your app’s UI, layout, and performance.
  • Flutter Lints: To ensure that your code follows the recommended style and practices, Flutter Lints provides a set of pre-configured linting rules for better code quality.

Future of Flutter Packages

What’s Coming Next?

As Flutter continues to evolve, the landscape of packages is expected to grow. Here’s what the future holds:

  • More Platform-Specific Packages: As Flutter becomes more robust, expect more packages for platform-specific features like Apple Watch integration or Android Auto.
  • Native Performance Enhancements: Some packages will continue to push the boundaries of performance, allowing Flutter apps to perform on par with fully native apps.
  • More Support for Desktop and Web: With Flutter’s growing support for desktop and web platforms, there will be an increase in packages that target these platforms, allowing developers to create truly cross-platform applications.

Conclusion

Flutter’s ecosystem of packages is one of the strongest aspects of the framework. The above packages provide essential features and tools that can help you build robust, scalable, and high-performance applications. Whether you’re managing state, interacting with APIs, handling notifications, or storing data, these packages can significantly boost your productivity and streamline your development process. By incorporating them into your projects, you can focus more on building great features rather than reinventing the wheel.

❤ ❤ 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:

Top 10 Flutter Packages
Discover the top 10 Flutter packages, from managing user preferences to creating animations, explore how these packages…7span.com

Top 10 Flutter Packages That You Must Know – GeeksforGeeks
A Computer Science portal for geeks. It contains well-written, well thought and well explained computer science and…www.geeksforgeeks.org


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.


Facade Design Pattern In Dart/Flutter

0

In situations where you have numerous subsystems, each with its own straightforward or convoluted interface, it can here and there be profitable to extract away those connection points by binding together them under one normal, generally less difficult simpler interface. This is the embodiment of the Facade pattern.

Furthermore, the Facade pattern is at times used to wrap a complex application programming interface with a less difficult rendition, uncovering just the necessary usefulness or joining several operations into one.

This blog will explore the Facade Design Pattern In Dart/Flutter. We see how to execute a demo program in your Flutter/Dart 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::

What is the Facade Design Pattern?

When to use?

Code Implement

Drawbacks

Conclusion



What is the Facade Design Pattern?

As per the book “Design Patterns, Elements of Reusable Object-Oriented Software“, Facade Gives a brought-together connection point to a set of connection points in a subsystem. Facade characterizes a more significant level point of interaction that makes the subsystem simpler to utilize.

Allow us to consider a situation where you are a visitor looking into a lodging. There, you want to cooperate with individuals at gathering for administrations like registration, room administration, and clothing. The front desk area improves on the cycle, concealing the intricacies of the basic activities (like housekeeping, kitchen, and clothing) and giving a simple connection point to visitors.

When To Use?

  • When you need to make a straightforward connection point for a complex subsystem.?
  • When there are various interdependent classes in a subsystem, it can prompt expanded intricacy.?
  • When you need to isolate clients from the parts of the subsystem.?

Code Implement

This Dart code demonstrates the Facade Design Pattern using a hotel operation scenario. The hotel comprises various subsystems such as housekeeping, kitchen, and laundry. The Facade Design Pattern simplifies the interface to these subsystems, making them easier to use.

This Dart code exhibits the Facade Design Pattern utilizing a lodging activity situation. The lodging involves different subsystems like housekeeping, kitchen, and clothing. The Facade Design Pattern works on the point of interaction with these subsystems, making them simpler to utilize.

class Housekeeping {
void doHousekeeping() {
print('Doing housekeeping...');
}
}

class Kitchen {
void prepareFood() {
print('Preparing food...');
}
}

class Laundry {
void doLaundry() {
print('Doing Laundry...');
}
}

// Facade class
class HotelFacade {
final Housekeeping _housekeeping;
final Kitchen _kitchen;
final Laundry _laundry;

HotelFacade(this._housekeeping, this._kitchen, this._laundry);

void frontDeskService() {
_housekeeping.doHousekeeping();
_kitchen.prepareFood();
_laundry.doLaundry();
}
}

void main() {
Housekeeping housekeepingObj = Housekeeping();
Kitchen kitchenObj = Kitchen();
Laundry laundryObj = Laundry();

HotelFacade hotel = HotelFacade(housekeepingObj, kitchenObj, laundryObj);
hotel.frontDeskService();
}

The HotelFacade example of true excellence as the facade, offers an improved front desk area() technique for interfacing with the subsystems(Housekeeping, Kitchen, and Laundry). This technique exemplifies the intricacies of the subsystems, making them simpler to utilize.

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

Doing housekeeping...
Preparing food...
Doing Laundry...

Process finished with exit code 0

Drawbacks:

  • A facade can misrepresent a framework, which might be tricky for clients who need more control or admittance to the hidden intricacy.
  • Involving a facade in another framework might show fundamental design issues. It is in many cases more reasonable as a refactoring device for existing complex frameworks.
  • As a facade will in general join functionalities, it is fundamental to try not to turn into a “divine being object” that disregards the Single Liability Principle.

Conclusion:

In the article, I have explained the Facade Design Pattern basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to the Facade Design Pattern 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 Facade Design Pattern in your Flutter/Dart projects. It gives a basic connection point to a complicated subsystem by making a higher-level point of interaction, making the subsystem clearer to utilize and understand in your Flutter/Dart 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.