Google search engine
Home Blog Page 7

Custom QR Code Generator in Flutterflow — Custom Widget

0

QR codes offer a quick and convenient way to share data like URLs, contact information, Wi-Fi credentials, and more. By simply scanning a QR code with apps like Google Lens (Android), Apple Camera (iOS), or your own custom-built app, users can instantly access the embedded content.

In this guide, We’ll learn how to create a Custom QR Code Generator using Flutterflow. We’ll walk you through building a reusable widget that can be easily integrated into your FlutterFlow app. With customizable colors, shapes, you can generate QR codes that match your app’s style and branding!

Package overview

Here’s a Flutter package you can use to build your own QR code generator widget.

You can explore Flutter packages on pub.dev, the official package repository for Dart and Flutter. One popular and well-maintained option for generating QR codes is qr_flutter, known for its reliability and community support.

The package maintains strong metrics including Likes, Pub Points (up to 150), and a high Popularity rating (out of 100%). You can learn more about how these scores work here.
 It also supports web, making it easy to preview and test your widget directly in FlutterFlow’s Run/Test mode.

Setup FlutterFlow 

  1. Go to FlutterFlow Website
     Visit flutterflow.io and log in with your Google or GitHub account. If you don’t have an account, sign up for free.
  2.  Create a New Project
  • After logging in, click the “Create New” button on the Flutter Flow dashboard.
  • Choose “Blank App” or select from templates if you want a head start.

3. Name Your Project
 Enter a name for your app and optionally add a project description.

4. Choose a Platform
 Select the platforms you’re building for: Android, iOS, Web, or All.

5. Set Up Firebase (Optional but Recommended)

  • You can skip this for now or connect your Firebase project.
  • Firebase enables authentication, Firestore database, storage, and more.

6. Select a Layout
 Choose a layout like mobile app, tablet, or web view based on your target platform.

7. Start Building Your App
 Once inside the project, you can:

  • Drag and drop widgets from the UI builder
  • Add pages, components, and navigation
  • Connect backend APIs or Firebase
  • Use Custom Functions and Custom Widgets for advanced logic

8. Run/Test Your App

  • Use the Run/Test tab to preview your app in real-time on the web.
  • You can also use the FlutterFlow Preview App on mobile for live testing.

Defining the Custom Action

  1. From the Navigation Menu (present on the left), select Custom Functions.
  2. Go to the Custom Actions tab and click + Create.
  3. Enter the action name as QrCode
  4. Add the package

Most well-known packages provide a simple usage example to help you get started quickly. On the qr_flutter package page, if you scroll down, you’ll find an Examples section. It includes a basic QR code generation snippet that serves as a great starting point for integrating the package into your app.

5. Add this Code in your Custom Code Widget.

// Automatic FlutterFlow imports
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/widgets/index.dart';
import '/flutter_flow/custom_functions.dart';
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:qr_flutter/qr_flutter.dart';

import 'package:qr_flutter/qr_flutter.dart';

class QrCode extends StatefulWidget {
const QrCode({
super.key,
this.width,
this.height,
});

final double? width;
final double? height;

@override
State<QrCode> createState() => _QrCodeState();
}

class _QrCodeState extends State<QrCode> {
TextEditingController qrCodeController = TextEditingController();
String qrData = '';

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

void generateQrCode() {
setState(() {
qrData = qrCodeController.text;
});
}

@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
TextFormField(
controller: qrCodeController,
decoration: InputDecoration(
hintText: "Enter your text",
hintStyle: TextStyle(
color: Colors.black,
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 1),
borderRadius: BorderRadius.circular(20))),
),
const SizedBox(
height: 50,
),

QrImageView(
data: qrData,
version: QrVersions.auto,
size: 300,
),
const SizedBox(
height: 50,
),
Container(
height: 50,
width: 160,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.green,
),
child: MaterialButton(
onPressed: generateQrCode,
child: Text("Generate Qr Code"),
),
)
],
),
);
}
}

You can easily modify this code to support different types of QR code data such as URLs, phone numbers, email addresses, or even vCard/contact information. Instead of just plain text (like a name), predefined data formats allow users to generate QR codes that directly open links, dial numbers, or send emails when scanned. You can also enhance the UI with labels, validation, or by displaying the QR data below the code. Additionally, consider adding download or share functionality to improve usability.

6. After add this code then, Click the Save Button.

7. Go to the Widget Tree and click the add a click to this widget. Then navigate to the Components section, where you’ll find the custom widgets defined in your project. Locate the custom widget named “QrCode”, click on it to add it to your page, and design how you want it to appear within your layout.

8. Click the “Run” button at the top-right corner of the screen to start your FlutterFlow app.

The following shows the expression evaluation in action, running on an android emulator:

Output

Conclusion

The Custom QR Code Generator makes it easy to generate dynamic QR codes within your FlutterFlow app. Using the qr_flutter package, it ensures smooth rendering and user-friendly functionality. You can further enhance it by adding customization options, styling, or even QR scanning features to improve user experience.

References

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 Flutterflow 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 Facebook, GitHub, Twitter, and LinkedIn.

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

Implementing Multimedia Ads In Flutter

0

Introduction

Monetizing a Flutter app effectively requires integrating ads without compromising the user experience. Multimedia ads, including banner, interstitial, rewarded, and native ads, offer various ways to generate revenue. Google AdMob, Facebook Audience Network, and other third-party ad networks provide SDKs for integrating ads into Flutter apps.

This guide covers everything from setting up ad networks to implementing different ad types in Flutter, ensuring a smooth and optimized experience for developers and users.

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

Understanding Multimedia Ads in Mobile Apps

Popular Plugins for Multimedia Ads in Flutter

What is AdMob

Setting Up AdMob in Flutter

Implementing Different Types of Ads in Flutter

Testing Ads in Flutter

Limitations of Multimedia Ads in Flutter

Platform-Specific Limitations

Enhancing Ad Performance & Future Trends

Conclusion

Reference


1. Understanding Multimedia Ads in Mobile Apps

Before diving into implementation, let’s understand the different types of ads available:

 Types of Multimedia Ads

  1. Banner Ads
  • Small, rectangular ads displayed at the top or bottom of the screen.
  • Less intrusive and provide continuous monetization.

2. Interstitial Ads

  • Full-screen ads that appear at natural transition points in an app (e.g., between levels in a game).
  • High engagement but should be used carefully to avoid annoying users.

3. Rewarded Ads

  • Video ads that offer in-app rewards (e.g., extra lives, coins, premium content) when watched.
  • Users voluntarily interact, increasing engagement.

4. Native Ads

  • Ads are designed to blend seamlessly with the app’s UI.
  • Provide a non-disruptive experience but require more customization.

2. Popular Plugins for Multimedia Ads in Flutter

Several ad plugins allow you to integrate multimedia ads into your Flutter app. Here are some of the most commonly used ones:

1. google_mobile_ads: ^5.3.1

Description:
 The official Google AdMob plugin for Flutter allows developers to integrate banner, interstitial, rewarded, and native ads. Supports ad mediation and test ads.

Basic Integration:

dependencies:
google_mobile_ads: ^5.3.1
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(MyApp());
}

Show a Banner Ad:

BannerAd myBanner = BannerAd(
adUnitId: 'your-ad-unit-id',
size: AdSize.banner,
request: AdRequest(),
listener: BannerAdListener(),
)..load();

2. easy_audience_network: ^0.0.7

Description:
 A Flutter plugin for integrating Facebook Audience Network ads. Supports banner, interstitial, and rewarded video ads.

Basic Integration:

dependencies:
easy_audience_network: ^0.0.7
void main() {
WidgetsFlutterBinding.ensureInitialized();
EasyAudienceNetwork.init();
runApp(MyApp());
}

Load a Banner Ad:

EasyBannerAd(
placementId: "YOUR_PLACEMENT_ID",
bannerSize: EasyBannerSize.BANNER,
);

3. unity_ads_plugin: ^0.3.23

Description:
 Flutter plugin for integrating Unity Ads, mainly for rewarded video and interstitial ads in gaming apps.

Basic Integration:

dependencies:
unity_ads_plugin: ^0.3.23
void main() {
WidgetsFlutterBinding.ensureInitialized();
UnityAds.init(gameId: 'your-unity-game-id', testMode: true);
runApp(MyApp());
}

Show an Interstitial Ad:

UnityAds.showVideoAd(placementId: 'video');

4. applovin_max: ^4.3.1

Description:
 AppLovin MAX is a popular ad mediation platform supporting multiple networks for higher ad revenue.

Basic Integration:

dependencies:
applovin_max: ^4.3.1
void main() {
WidgetsFlutterBinding.ensureInitialized();
AppLovinMAX.initialize("YOUR_APPLOVIN_SDK_KEY");
runApp(MyApp());
}

Show an Interstitial Ad:

AppLovinMAX.showInterstitial("INTERSTITIAL_AD_UNIT_ID");

5. ironsource_mediation: ^3.1.0

Description:
 IronSource is an ad mediation platform that combines multiple ad networks to optimize revenue. Supports rewarded, interstitial, and banner ads.

Basic Integration:

dependencies:
ironsource_mediation: ^3.1.0
void main() {
WidgetsFlutterBinding.ensureInitialized();
IronSource.initialize("YOUR_APP_KEY");
runApp(MyApp());
}

Show a Rewarded Ad:

IronSource.showRewardedVideo();

6. gma_mediation_inmobi: ^1.1.0

Description:
 An ad mediation adapter for integrating InMobi ads with Google Mobile Ads SDK.

Basic Integration:

dependencies:
gma_mediation_inmobi: ^1.1.0
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(MyApp());
}

Display an AdMob Interstitial with InMobi Mediation:

InterstitialAd.load(
adUnitId: 'your-admob-ad-unit-id',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) => ad.show(),
onAdFailedToLoad: (error) => print('Ad failed to load: $error'),
),
);

7. vungle: ^0.6.12

Description:
 Vungle provides in-app video ads optimized for monetization in mobile apps. Supports interstitial and rewarded video ads.

Basic Integration:

dependencies:
vungle: ^0.6.12
void main() {
WidgetsFlutterBinding.ensureInitialized();
Vungle.init('YOUR_VUNGLE_APP_ID');
runApp(MyApp());
}

Show a Rewarded Video Ad:

Vungle.playAd(placementId: "REWARDED_AD_PLACEMENT_ID")

3. What is AdMob?

AdMob is a mobile advertising platform by Google that allows app developers to monetize their apps through various ad formats, including banner ads, interstitial ads, rewarded videos, and native ads. It offers high fill rates, intelligent mediation, and detailed performance analytics, making it one of the most popular choices for app monetization.

Key Features:

  • High fill rates and competitive CPMs
  • Supports multiple ad formats
  • Advanced mediation for optimizing ad revenue
  • Integration with Google Analytics for performance tracking

Do You Need AdMob in Flutter for Ads?

AdMob is not mandatory for displaying ads in a Flutter app, but it is one of the most effective and widely used ad networks. If you want global reach, high fill rates, and seamless mediation, AdMob is a strong choice.

When to Use AdMob:

  • If you want a reliable and high-paying ad network
  • If your app targets a global audience
  • If you prefer Google’s ecosystem for analytics and optimization

When Not to Use AdMob:

  • If your app is focused on gaming (Unity Ads or AppLovin might be better)
  • If you have a social media-style app (Facebook Audience Network could be a good fit)
  • If you need aggressive ad mediation and optimization (IronSource excels in this area)

4. Setting Up AdMob in Flutter

Step 1: Create an AdMob Account

Go to AdMob and sign up.
Create a new app and register your Flutter app.
Generate Ad Unit IDs for different ad formats.

Step 2: Add AdMob Dependencies

Add the google_mobile_ads package to your Flutter project:

dependencies:
google_mobile_ads: ^3.0.0

Run:

flutter pub get

Step 3: Initialize AdMob in main.dart

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

5. Implementing Different Types of Ads in Flutter

1. Banner Ads (Static ads at the screen’s top/bottom)

BannerAd myBanner = BannerAd(
adUnitId: 'your-ad-unit-id',
size: AdSize.banner,
request: AdRequest(),
listener: BannerAdListener(),
);
Container(
alignment: Alignment.bottomCenter,
child: AdWidget(ad: myBanner),
width: myBanner.size.width.toDouble(),
height: myBanner.size.height.toDouble(),
)

2. Interstitial Ads (Full-screen ads between content)

InterstitialAd.load(
adUnitId: 'your-ad-unit-id',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (InterstitialAd ad) {
ad.show();
},
onAdFailedToLoad: (LoadAdError error) {
print('Interstitial failed: $error');
},
),
);

3. Rewarded Ads (Users earn rewards after watching an ad)

RewardedAd.load(
adUnitId: 'your-ad-unit-id',
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
ad.show(onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
print("Reward earned: ${reward.amount}");
});
},
onAdFailedToLoad: (LoadAdError error) {
print('Rewarded Ad failed to load: $error');
},
),
);

4. Native Ads (Ads that blend into app UI)

NativeAd(
adUnitId: 'your-ad-unit-id',
factoryId: 'adFactoryExample',
listener: NativeAdListener(),
request: AdRequest(),
);

Best Practices for Ad Integration

Preload Ads — Load ads in advance to minimize user wait time.

Non-Intrusive Placement — Position ads in a way that doesn’t disrupt user interactions.

Rewarded Ads Over Interstitials — Encourage engagement by offering users something in return.

Ad-Free Premium Version — Provide users with an option to remove ads through an in-app purchase.


6. Testing Ads in Flutter

Using Test Ad Unit IDs

To prevent policy violations, Google AdMob provides test Ad Unit IDs. These should be used during development:

Use test Ad Unit IDs to prevent accidental ad revenue violations.

Example test IDs:

  • Banner: ca-app-pub-3940256099942544/6300978111
  • Interstitial: ca-app-pub-3940256099942544/1033173712
  • Rewarded: ca-app-pub-3940256099942544/5224354917
const String testBannerAdUnitId = 'ca-app-pub-3940256099942544/6300978111';

Troubleshooting Common Issues

  • Ads not appearing — Ensure correct Ad Unit IDs and verify an active internet connection.
  • Crashes on startup — Initialize google_mobile_ads before attempting to load ads.
  • Interstitial Ads not displaying — Make sure the ad is fully loaded before calling .show().

7. Limitations of Multimedia Ads in Flutter

Common Challenges & Solutions

  • Ads failing to load — Verify proper configuration and use test ads during development.
  • User complaints about intrusive ads — Implement a balanced ad frequency strategy.
  • Revenue inconsistencies — Experiment with different ad placements to optimize engagement.

8. Platform-Specific Limitations

iOS App Store Policies

  • Apple enforces strict regulations against intrusive advertising.
  • Apps with excessive pop-up ads may face rejection from the App Store.

Google Play Compliance

  • Apps must adhere to Google’s Better Ads Standards.
  • Misplaced or disruptive ads can lead to app suspension.

9. Enhancing Ad Performance & Future Trends

Strategies for Maximizing Ad Revenue

  • A/B Testing — Test different ad placements to improve conversion rates.
  • Controlled Ad Frequency — Avoid overwhelming users with excessive advertisements.
  • Personalized Ad Experience — Provide an ad-free experience via a paid subscription.
  • Strategic Ad Timing — Display ads at logical transition points.

Emerging Trends in Ad Monetization

  • AI-powered ad Targeting — Uses machine learning to optimize ad delivery.
  • Augmented Reality (AR) & Virtual Reality (VR) Ads — More immersive advertising experiences.
  • Blockchain-Based Ad Networks — A decentralized approach for greater transparency.
  • Server-Side Ad Mediation — Dynamically switching between multiple ad networks to maximize revenue.

10. Conclusion

Multimedia ads are a powerful monetization tool for Flutter applications, but they must be implemented thoughtfully to maintain a positive user experience.

Key Takeaways:

  • Utilize Google AdMob or alternative networks for ad integration.
  • Implemented various ad formats effectively, including banner, interstitial, rewarded, and native ads.
  • Follow best practices to balance user engagement and revenue generation.
  • Stay updated with emerging trends to enhance ad monetization strategies.

You can maximize revenue by leveraging smart ad placements, adhering to platform policies, and optimizing performance while keeping your users engaged.


11. Reference

Get started | Flutter | Google for Developers
A mobile ads SDK for AdMob publishers who are building Flutter apps.developers.google.com

Add ads to your mobile Flutter app or game
How to use the google_mobile_ads package to show ads in Flutter.docs.flutter.dev

❤ ❤ 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 Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

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


Metadata Annotations in Dart

0

Dart’s metadata annotations provide our code with more details. This information can be used by the Dart runtime, tools, or libraries. Code generation, documentation, and runtime behaviour adjustment are just a few of the things that these annotations can assist with.

This blog will explore Metadata Annotations in Dart. We will also implement a demo program and teach you how to use generation, documentation, and runtime in Dart for your 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 Are Metadata Annotations

Using Metadata Annotations

Code Implement

Conclusion



What Are Metadata Annotations:

The @ symbol and the class name, which may contain constructor arguments, are used in Dart to create metadata annotations. These annotations can be applied to fields, parameters, classes, or methods. Dart comes with several built-in annotations. Custom annotations can be defined by us.

This is an illustration of a basic metadata annotation:

@deprecated
void newMethod() {
}

Using Metadata Annotations:

Developers in Flutter make extensive use of metadata annotations to add more details about classes, methods, and widgets.

  • @required: This signifies that to invoke a method, a parameter must be supplied.
  • @deprecated: Indicates that a feature is no longer supported.
  • @override: Shows that a method in a superclass is being overridden.
  • @optional: This means that a variable or method is only for internal use and shouldn’t be directly accessed.
  • @protected: This signifies that a variable or method is only for internal use and shouldn’t be directly accessed.
  • @visibleForTesting: This signifies that a variable or method is exclusively for testing and shouldn’t be directly accessed.

An illustration of the usage of the @required annotation in Flutter is provided here:

class MyWidget extends StatelessWidget {
  final String title;

  MyWidget(@required this.title);

  @override
  Widget build(BuildContext context) {
    return Text(title);
  }
}

Code Implement:

=> Creating Custom Annotations

It’s easy to create a custom annotation in Dart. We specify a parameter-accepting class. We use instances of this class to annotate our code.

=> Defining a Custom Annotation

To provide classes or methods with descriptive information, we will develop a new annotation named @CustomAnnotations.

class CustomAnnotations {
  final String description;

  const Info(this.description);
}

Here, we define CustomAnnotations, a custom metadata annotation that accepts a description argument. We can apply this annotation to a class or method to use it:

@CustomAnnotations('This is a custom annotation')
class DemoClass {
  @CustomAnnotations('This is a annotation example')
  int add(int a, int b) => a + b;
  @CustomAnnotations('Subtracts the second number from the first.')
  int subtract(int a, int b) => a - b;
}

=> Using Metadata Annotations for Code Generation

By using the dart:mirrors package, we can take advantage of Dart’s reflection capabilities to access metadata annotations at runtime. It’s crucial to remember that dart:mirrors has restrictions, especially when used in online applications that use tree shaking. Here’s how to get our personalised annotations back:

import 'dart:mirrors';

void getAnnotations(Type type) {
  final classMirror = reflectClass(type);
  final classAnnotations = classMirror.metadata;

  for (var annotation in classAnnotations) {
    if (annotation.reflectee is CustomAnnotations) {
      final CustomAnnotations = annotation.reflectee as CustomAnnotations;
      print('Class Annotation: ${CustomAnnotations.description}');
    }
  }

  // Check method annotations
  classMirror.declarations.forEach((key, value) {
    if (value is MethodMirror) {
      final methodAnnotations = value.metadata;
      for (var annotation in methodAnnotations) {
        if (annotation.reflectee is CustomAnnotations) {
          final customAnnotations = annotation.reflectee as CustomAnnotations;
          print('Method ${MirrorSystem.getName(key)} Annotation:             ${customAnnotations.description}');
        }
      }
    }
  });
}

void main() {
  getAnnotations(DemoClass);
}

When we run the application, we ought to get the above code output like the underneath console output the annotations associated with the DemoClass class and its methods:

Class Annotation: This is a custom annotation
Method demo Annotation: This is a annotation example
Method subtract Annotation: Create a demo class for annotation example

Conclusion:

In the article, I have explained the Metadata Annotations basic structure in a dart; you can modify this code according to your choice. This was a small introduction to the Metadata Annotations On User Interaction from my side, and it’s working using Dart.

I hope this blog will provide you with sufficient information on Trying the Metadata Annotations in Dart in your projects. Dart’s robust custom annotations feature lets us add metadata to our classes and functions, making our code easier to read and maintain. 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 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.





Sum Of a List Of Numbers In Dart

0

This blog will explore the Sum Of a List Of Numbers In Dart. We will also implement a demo program, and learn how to calculate the sum of a list of numbers in a dart in your 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::

Using fold() Method

Using a For loop

Using The reduce() Method

Using The Sum From The Collection Package

Using A for-each loop

Conclusion



Using fold() Method:

The fold() technique (for the List class) is a higher-order capability that applies a given function to every component in an assortment and collects the outcomes. In the model above, we pass an anonymous function that adds the two contentions (the aggregator and the ongoing value) together.

void main() {
List<double> numbers = [1, 3, 5, 7, 9, 0.7, -2, 0.38, -0.38];
double sum = numbers.fold(0, (a, b) => a + b);
print(sum);
}

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

23.7

Process finished with exit code 0

Using a For loop:

For loop is a famous flow control that has been around for quite a while in most programming languages, including Dart. This is likewise an incredible asset that assists us with computing numerous things, remembering to track down the sum of the components for a given list.

void main() {
final myListNumbers = [1, 3, 5, 7, 9, 4.2, 6.1, -6, -2.5];

var sum = 0.0;
for (var i = 0; i < myListNumbers.length; i++) {
sum += myListNumbers[i];
}
print(sum);
}

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

26.799999999999997

Process finished with exit code 0

In this methodology, we utilize a for loop to iterate over the list of numbers (the two numbers and pairs) and add every element to a variable named sum.

Using The reduce() Method:

The reduce() method is like the fold() strategy, however, it doesn’t accept an initial value as its most memorable contention. All things considered, it involves the principal element in the collection as the initial value and applies the given capability to the excess elements. For this situation, we pass a similar function as in the fold() example.

void main() {
final numbers = [1, 3, 5, 7.7, -2.2, 3, 4, 5, 6, 7];
var sum = numbers.reduce((a, b) => a + b);
print(sum);
}

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

39.5

Process finished with exit code 0

Using The Sum From The Collection Package:

First imports this package, we need to add this line.

import 'package:collection/collection.dart';

At the main look, this might appear to be the most limited approach. Thus, a few developers favor utilizing different ways to deal with this one.

// ignore: depend_on_referenced_packages
import 'package:collection/collection.dart';

void main() {
final numbers = [150, 80, 0, 35, 2, 95];
var sum = numbers.sum;
print(sum);
}

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

362

Process finished with exit code 0

Using A for-each loop:

In this methodology, we utilize a for-each loop to iterate over the list and add every element to the sum variable.

void main() {
final numbers = [6, 12, 18, 24, 30];
var sum = 0;
numbers.forEach((number) {
sum += number;
});
print(sum);
}

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

90

Process finished with exit code 0

Conclusion:

In the article, I have explained the sum of a list of numbers in dart; you can modify this code according to your choice. This was a small introduction to the sum of a list of numbers 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 Sum Of a List Of Numbers In the Dart of your projects. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire 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 Exception Handling In Flutter

0

In this article, we will Explore Exception Handling In FlutterWe will learn about exception handling. An exception is an unusual state or occurrence that arises during program execution and disrupts the regular flow of code within 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::

What Is Exception In Flutter?

Why Need To Exception Handling?

Type Of Exception In Flutter

How To Handle Exception?

Conclusion



What Is Exception In Flutter?

Exceptions are errors in the code that show something unexpected happened. When an unusual or unwanted situation arises, like when you try to divide a number by zero, access a null reference, encounter a formate exception, lose a network connection, etc., Flutter throws an exception. If the exception is not handled correctly, the program might end.

Why Need To Exception Handling?

There are some needs for exception handling are:

  • > Creating dependable and sturdy Flutter applications requires knowing how to handle exceptions. You can detect exceptions, log them, and take the necessary steps to address problems and offer a positive user experience.
  • > Using Flutter’s exception-handling feature will safeguard your application from crashing in the event of unforeseen errors. It all comes down to handling these errors with ease to keep your app functioning properly and provide a better user experience.
  • > It offers a methodical approach to handling mistakes, enabling you to show error messages that are easy to understand or recover from with grace.
  • > Exception handling improves the maintainability of the application by separating the error-handling code from the regular code.

Type Of Exception In Flutter:

Dart Exceptions

  • FormatException: This happens when you attempt to parse a value in an incorrect format, such as trying to parse an integer from a non-numeric string.
  • RangeError: Raised in situations where a value or index is outside of a valid range, such as when a list’s out-of-bounds index is accessed.

> Flutter-Specific Exceptions

  •  PlatForm Exception: Encountered frequently when working with code specific to a platform, such as when calling native platform functions. Errors about device features, like location, permissions, camera access, and so forth, could be among them.

> Custom Exceptions

By defining new exception classes in Flutter that extend pre-existing Dart exception classes, like “Exception” or “Error,” you can create your exceptions. It is beneficial in assisting you in better classifying and managing particular application errors.

> Async/Await Exceptions

Exceptions that can happen when using asynchronous functions such as async/await and future. Errors about database queries, network requests, timeouts, etc. could be among them.

Async/await is frequently used for network requests and asynchronous operations, and try-catch blocks are used to handle exceptions. Async/await and Dart’s Future offer an organized method for managing asynchronous errors.

How To Handle Exception?

There are several ways we can deal with exceptions, some of which are listed below.

> Using Try And Catch.

We can handle the exception with the help of the Try/Catch block.

  •  Try: The code block where an exception can happen is called a try block. You can insert those codes that allow exceptions to occur in the try block. while the program is running.
  • Catch: Any exceptions thrown in the try block are caught and handled in a catch block. To use the catch keyword to identify particular exceptions.
  •  Finally: The finally block is optional and is always run, regardless of whether an exception arises. The try/catch block is followed by the execution of a block.
Future<void> youMethod() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');

try {
final response = await http.get(url).timeout(Duration(seconds: 5));

if (response.statusCode == 200) {
print("You response data is here==->${response.body}");
} else {
print("Not Getting success");
}
}catch (error, _) {
print(error.toString());
}finally {
print('API call completed.');
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Exception Handling In Flutter of your projects. Using exception handling in Flutter is essential to improving, simplifying, and managing your application. Exception handling is a crucial part of creating a dependable and adaptable Flutter application. 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.


Securing Your Flutter App By Adding SSL Pinning

0

Introduction

As cyber threats continue to rise, it is crucial to ensure secure communication between your Flutter app and the backend server. While HTTPS encrypts data in transit, it does not protect against Man-in-the-Middle (MITM) attacks, where hackers intercept and modify network traffic.

SSL Pinning is one of the most effective security measures to prevent unauthorized connections, ensuring your app communicates only with trusted servers.

By the end of this guide, you’ll be equipped with advanced security techniques to protect your Flutter app from API hijacking and MITM attacks.

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

Understanding SSL/TLS and Its Vulnerabilities

How SSL Pinning Works

Implementing SSL Pinning in Flutter

Challenges & Limitations

Future Improvements & Scope

Final Thoughts


1. Understanding SSL/TLS and Its Vulnerabilities

What is SSL/TLS?

SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are cryptographic protocols that secure communication between a client (Flutter app) and a server. They encrypt data to prevent interception and modification by malicious actors. TLS is the modern and more secure successor to SSL.

Why Default SSL/TLS is Not Enough?

Even with HTTPS, attackers can still exploit security loopholes. Some common threats include:

  • Proxy-Based Man-in-the-Middle (MITM) Attacks — Tools like Burp Suite and Charles Proxy can intercept API traffic, even when HTTPS is enabled.
  • Compromised Certificate Authorities (CA) — If a trusted CA is hacked, attackers can issue fraudulent certificates to impersonate legitimate websites.
  • Weak SSL Implementations — Older versions like TLS 1.0 and 1.1 have security flaws that make them vulnerable to attacks such as POODLE and BEAST.

2. How SSL Pinning Works

SSL Pinning ensures that your app only trusts a specific SSL certificate or public key, even if a trusted CA issues a different valid certificate. This protects against MITM attacks.

How SSL Pinning Validates Secure Connections:

  1. The app requests data from the server over HTTPS.
  2. The server presents its SSL certificate.
  3. The app verifies the presented certificate against a pinned certificate or public key stored in the app.
  4. If they match, the connection is established; otherwise, the request is blocked.

Without SSL Pinning, an attacker can use a fake certificate to intercept requests and steal sensitive data, including login credentials and payment details.


3. Types of SSL Pinning

1. Certificate Pinning (Recommended)

  • Stores and verifies the entire SSL certificate.
  • Provides the highest security as certificates change less frequently.

Limitation: The app must be updated when the certificate expires.

2. Public Key Pinning

  • Pins only the public key extracted from the SSL certificate.
  • Allows certificate renewal without requiring an app update (as long as the public key remains the same).

Limitation: If the backend changes the public key, the app will reject requests until updated.

3. CA Pinning (Least Secure)

  • Pins the Certificate Authority (CA) that issued the SSL certificate.
  • Allows multiple certificates signed by the CA.

Limitation: If the CA is compromised, attackers can issue fraudulent certificates that pass validation.


3. Implementing SSL Pinning in Flutter

We will implement SSL pinning using two popular networking libraries:

  • http – For simple HTTP requests.
  • Dio – For advanced networking with interceptors.

Step 1: Extract the SSL Certificate Hash

Before implementing SSL pinning, you need to retrieve your server’s SSL certificate fingerprint. Run the following command in a terminal:

openssl s_client -connect your-api.com:443 -showcerts </dev/null 2>/dev/null | openssl x509 -fingerprint -sha256 -noout

 Example Output:

SHA256 Fingerprint=AB:CD:EF:12:34:56:78:90:AA:BB:CC:DD:EE:FF:11:22:33:44:55:66

Copy this fingerprint; it will be used in the Flutter implementation.

Step 2: SSL Pinning with http Package

  1. Add Dependencies

Update pubspec.yaml:

dependencies:
http: ^0.13.4

2. Create a Secure HTTP Client

import 'dart:io';
import 'package:http/http.dart' as http;
class SecureHttpClient extends http.BaseClient {
  final HttpClient _httpClient = HttpClient();
SecureHttpClient() {
    _httpClient.badCertificateCallback = (cert, host, port) {
      final pinnedCert =
          "AB:CD:EF:12:34:56:78:90:AA:BB:CC:DD:EE:FF:11:22:33:44:55:66"; 
      final certFingerprint = cert.sha256.toString().toUpperCase();
      return certFingerprint == pinnedCert;
    };
  }
@override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    return _httpClient
        .getUrl(Uri.parse(request.url.toString()))
        .then((req) => req.close())
        .then((resp) => http.StreamedResponse(resp, resp.statusCode));
  }
}
void main() async {
  final client = SecureHttpClient();
try {
    final response = await client.get(Uri.parse('https://your-api.com'));
    if (response.statusCode == 200) {
      print('Secure Connection Established');
    }
  } catch (e) {
    print('SSL Pinning Failed: $e');
  }
}

Improvements:

  • Converts the SSL certificate fingerprint dynamically for comparison.
  • Uses an override method to ensure all requests pass through the secured client.

Step 3: Implement SSL Pinning with Dio Package

1. Add Dependencies

Update pubspec.yaml:

dependencies:
dio: ^5.0.0
flutter_ssl_pinning: ^2.0.0

2. Implement SSL Pinning with Dio Interceptor

import 'package:dio/dio.dart';
import 'package:flutter_ssl_pinning/flutter_ssl_pinning.dart';
Future<void> setupDioWithSslPinning() async {
  Dio dio = Dio();
dio.interceptors.add(
    DioFlutterSSLPinning(
      allowedSHAFingerprints: [
        "AB:CD:EF:12:34:56:78:90:AA:BB:CC:DD:EE:FF:11:22:33:44:55:66"
      ],
      onBadCertificate: () => print('SSL Pinning Failed'),
      onValidCertificate: () => print('Secure Connection Established'),
    ),
  );
try {
    final response = await dio.get("https://your-api.com");
    print('Response: ${response.data}');
  } catch (e) {
    print('Error: $e');
  }
}

3. Call this function in main.dart:

void main() {
setupDioWithSslPinning();
}

Improvements:

  • Uses Dio’s interceptor to enforce SSL pinning globally.
  • Provides callback methods for failed or successful pinning verification.

4. Challenges & Limitations

SSL pinning enhances security, but it comes with certain challenges and limitations that developers must address:

Certificate Expiry

SSL certificates have expiration dates, usually every one or two years. If an expired certificate remains pinned in the app, it will cause connection failures.
Solution: Implement automated certificate renewal using services like Let’s Encrypt. Additionally, notify users to update the app before the certificate expires by tracking expiration dates programmatically.

Debugging Issues

When SSL pinning fails, diagnosing the issue in production becomes difficult, as the app may not provide detailed error messages.
Solution: Implement extensive logging for SSL failures in debug mode. Use feature flags to disable SSL pinning temporarily in testing environments but enforce it in production.

Device Compatibility

Older Android and iOS devices may not support modern SSL/TLS standards, leading to connection issues.
Solution: Ensure that the app enforces at least TLS 1.2 or higher. Perform testing across a range of devices and OS versions to check for compatibility issues.

Manually Updating Certificates

If a certificate changes, users must update the app to continue using SSL pinning, which can cause disruptions.
Solution: Instead of pinning the entire certificate, use public key pinning, which remains valid even if the certificate is reissued. Alternatively, configure the app to fetch updated certificates securely from a remote server.

Man-in-the-Middle (MITM) Bypass

Attackers using rooted or jailbroken devices may attempt to bypass SSL pinning by modifying the app’s network configurations.
Solution: Implement root and jailbreak detection tools. For Android, libraries like RootBeer can detect rooted devices, while iOS can use JailMonkey. Additionally, encrypt sensitive data within the app to minimize risks.

App Store Rejections

Both Apple and Google have strict security policies. Improper SSL pinning implementation can lead to app store rejections, particularly if it restricts connections too aggressively.
Solution: Follow best practices by allowing fallback mechanisms. Avoid hardcoding certificates directly in the code and ensure a smooth user experience even if SSL pinning fails.


5. Future Improvements & Scope

Automated Certificate Management

To reduce manual updates, SSL certificates can be managed dynamically using automation tools. Services like Let’s Encrypt provide automatic renewal, ensuring that applications always use valid certificates.

AI-Driven Threat Detection

Advanced security measures will likely integrate AI-powered monitoring to detect MITM attacks in real time. Future applications may analyze network behaviors to identify suspicious activities and enhance protection dynamically.

Zero-Trust Security Model

A zero-trust approach requires continuous authentication and verification for all network requests rather than relying solely on SSL pinning. Implementing this model can further improve app security.

Post-Quantum Cryptography

With advancements in quantum computing, traditional SSL encryption methods may become vulnerable. The adoption of post-quantum cryptographic standards will ensure long-term security for encrypted communications.

Dynamic SSL Pinning

Instead of hardcoding SSL certificates, future implementations may allow apps to retrieve and update SSL pinning configurations dynamically from a trusted backend. This would eliminate the need for frequent app updates while maintaining security.


6. Final Thoughts

SSL pinning is a powerful security feature that protects Flutter applications from MITM attacks, ensuring encrypted communications remain secure. However, it introduces challenges such as certificate expiration, debugging difficulties, and update management. Developers should implement best practices, such as automated certificate updates, dynamic SSL pinning, and fallback mechanisms, to maintain a balance between security and usability.

Would you like me to add implementation code examples for automated certificate updates or root detection? Let me know!

❤ ❤ 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 hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

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


Explore Advanced Dart Enum

0

Dart’s enums are more than just a collection of constants. If you want your code to look neat, secure, and expressive, Dart Enum can help. Dart provides additional capabilities that can take enums even further, even though the basics of Dart Enum are fairly well-known throughout its development.

In this article, we’ll Explore Advanced Dart Enum. We see how to execute a demo program, like adding properties, methods, and using switch expressions effectively in a project.

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 Dart Enum?

Adding Dart Enum properties

Methods added to enums

Using enums with switch expressions

Extending enums with mixins

Using enums in data structures

Enum-driven state management

Conclusion



What is Dart Enum?

A method for defining a limited collection of constants is provided by Dart Enum. They are ideal for situations when you need to represent a set of related choices that are closed.

An easy illustration:

enum UserRole {  
  admin,  
  editor,  
  viewer,  
}  

void main() {  
  UserRole role = UserRole.admin;  

  print(role); 
}

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

UserRole.admin 

Process finished with exit code 0

Adding properties to Dart Enum:

Dart enum is more than just a list of values. You can also bind properties to it.

Adding descriptions:-

Assume that each of the following roles requires you to submit an annotation.

A description is included in the instantiation of every admin, editor, and viewer enum value. Since the description property is fixed, it cannot be changed. The enum’s const constructor ensures that it is a compile-time constant.

enum UserRole {
admin('Administrator with full access'),
editor('Editor with content management access'),
viewer('Viewer with read-only access');
final String description;
const UserRole(this.description);
}
void main() {
print(UserRole.admin.description);
}

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

Administrator with full access

Process finished with exit code 0

Methods added to enums:

Methods can also be included in Dart Enum. It is also useful, for instance, when the enum’s behavior needs to be contained within a box. The canEdit method determines whether a role has edit permission. The current enum value is referred to by this keyword.

enum UserRole {  
  admin,  
  editor,  
  viewer;  

  bool canEdit() => this == UserRole.admin || this == UserRole.editor;  
}  

void main() {  
  print(UserRole.admin.canEdit()); 
  print(UserRole.viewer.canEdit());  
}

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

true
false  

Process finished with exit code 0

Using enums with switch expressions:

As a result, the Dart switch expression cases directly interface with enums and can be implemented in a minimal and type-safe manner. The switch expression guarantees that every enum case is addressed. Dart will generate a compile-time error and your program will be safe if you neglect to handle a case.

enum UserRole {  
  admin,  
  editor,  
  viewer;  

  bool canEdit() => this == UserRole.admin || this == UserRole.editor;  
}  

void main() {  
  UserRole role = UserRole.editor;  

  String message = switch (role) {  
    UserRole.admin => 'Welcome, Admin!',  
    UserRole.editor => 'Hello, Editor!',  
    UserRole.viewer => 'Greetings, Viewer!'  
  };  

  print(message); 
}

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

Hello, Editor!   

Process finished with exit code 0

Extending enums with mixins:

You can add reusable behaviour to enums by extending them with mixins for more complex use cases.Every enum value has access to a logging action thanks to the Loggable mixin. This method maintains the modularity and  keeps your code DRY.

mixin Loggable {  
  void log(String message) {  
    print('LOG: $message');  
  }  
}  

enum UserRole with Loggable {  
  admin,  
  editor,  
  viewer;  
}  

void main() {  
  UserRole.admin.log('Admin has logged in.');  
}

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

LOG: Admin has logged in.

Process finished with exit code 0

Using enums in data structures:

Additionally, enums can serve as keys for more intricate data structures like maps. Each role is mapped to a set of authorisation actions that it is capable of performing. Managing permissions is simple and type-safe with this method.

enum UserRole {  
  admin,  
  editor,  
  viewer;  
}  
void main() {  
  Map<UserRole, List<String>> permissions = {  
    UserRole.admin: ['read', 'write', 'delete'],  
    UserRole.editor: ['read', 'write'],  
    UserRole.viewer: ['read'],  
  };  

  print(permissions[UserRole.editor]); 
} 

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

[read, write] 

Process finished with exit code 0

Enum-driven state management:

Consider creating a shopping application that shows the order status. Using an enum to control the state and its state transitions is also possible. The logic for transitioning between states is defined in the following procedure. There is a descriptive message for each state. The lifecycle of an order is simulated by the while loop.

enum OrderStatus {
  pending('Order received, awaiting confirmation'),
  confirmed('Order confirmed, preparing for shipment'),
  shipped('Order shipped, on its way'),
  delivered('Order delivered, enjoy!');

  final String message;

  const OrderStatus(this.message);

  OrderStatus? next() {
    switch (this) {
      case OrderStatus.pending:
        return OrderStatus.confirmed;
      case OrderStatus.confirmed:
        return OrderStatus.shipped;
      case OrderStatus.shipped:
        return OrderStatus.delivered;
      case OrderStatus.delivered:
        return null;
    }
  }
}

void main() {
  OrderStatus? status = OrderStatus.pending;

  while (status != null) {
    print(status.message);
    status = status.next();
  }
}

Conclusion:

In the article, I have explained the Explore Advanced Dart Enum basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to the Explore Advanced Dart Enum 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 Explore Advanced Dart Enum in your projects. Dart enums are a flexible tool for writing expressive and maintainable code; they are more than just a list of values.  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.


Serverpod in Flutter

0

Introduction

As a Flutter developer, choosing the right backend solution is crucial for building scalable, secure, and high-performance applications. Traditional backend options like Firebase, Node.js, and Django work well, but they often require switching between multiple languages, frameworks, and dependencies.

This is where Serverpod comes in — a Dart-based backend framework specifically designed for Flutter applications. With automatic API generation, PostgreSQL integration, authentication, WebSockets, and caching, Serverpod makes backend development seamless and efficient while allowing developers to stay within the Flutter ecosystem.

This blog will cover everything you need to know about integrating Serverpod with Flutter, from setup to advanced features like database handling, authentication, and real-time updates.

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 Choose Serverpod for Your Flutter Backend?

Setting Up Serverpod in Flutter

Creating API Endpoints in Serverpod

Working with the Database in Serverpod

Authentication & User Management in Serverpod

WebSockets & Real-time Features

Deployment & Scaling Serverpod

Challenges in Using Serverpod

Limitations of Serverpod

Future Scope of Serverpod

Conclusion

Reference


1. Why Choose Serverpod for Your Flutter Backend?

As a Flutter developer, using Serverpod has several advantages over other backend solutions:

1. Dart-Powered Backend

  • No need to switch between multiple languages like Node.js or Python.
  • Full control over backend logic while staying within the Flutter ecosystem.

2. Seamless API Integration

  • Serverpod automatically generates type-safe API endpoints, reducing manual work.
  • Easy-to-use client SDK for Flutter apps.

3. Built-in Authentication & Security

  • OAuth, JWT, and role-based access control (RBAC) out of the box.
  • Secure API endpoints with authentication middleware.

4. Database & ORM Support

  • Uses PostgreSQL as the database with an intuitive ORM.
  • Supports relations, migrations, and query building using Dart.

5. WebSocket & Real-time Features

  • Built-in WebSocket support for real-time apps like chat, notifications, and live updates.

6. Performance & Scalability

  • Serverpod is optimized for speed and supports Redis caching to improve performance.
  • Can be deployed on Docker, AWS, Google Cloud, or DigitalOcean for production scaling.

2. Setting Up Serverpod in Flutter

1. Install Serverpod CLI

First, install the Serverpod CLI tool globally:

dart pub global activate serverpod_cli

Verify the installation:

serverpod --version

2. Create a Serverpod Project

Run the following command to generate a new Serverpod project:

serverpod create my_serverpod_project

This will create three directories:

  1. my_serverpod_project_server → Backend server
  2. my_serverpod_project_client → Generated Flutter client SDK
  3. my_serverpod_project_flutter → A sample Flutter app (optional)

3. Set Up PostgreSQL

Serverpod requires PostgreSQL as the database. Install it based on your OS:

Create a new database:

psql -U postgres
CREATE DATABASE my_serverpod_db;

Then, configure my_serverpod_project_server/config/development.yaml:

database:
host: localhost
port: 5432
name: my_serverpod_db
user: postgres
password: yourpassword

4. Start the Server

Navigate to the server folder and run:

cd my_serverpod_project_server
serverpod run

Expected output:

Server listening on port 8080

5. Integrate Serverpod with Flutter

In your Flutter project, add the generated client SDK:

dependencies:
my_serverpod_project_client:
path: ../my_serverpod_project_client

Then, initialize the Serverpod client in Flutter:

import 'package:my_serverpod_project_client/my_serverpod_project_client.dart';

final client = Client('http://localhost:8080/')
..connectivityMonitor = ServerpodClientShared().connectivityMonitor;

3. Creating API Endpoints in Serverpod

1. Define an API Endpoint

Edit my_serverpod_project_server/lib/src/endpoints/example.dart:

import 'package:serverpod/serverpod.dart';

class ExampleEndpoint extends Endpoint {
Future<String> sayHello(Session session, String name) async {
return 'Hello, $name! Welcome to Serverpod!';
}
}

Run:

serverpod generate

2. Call the API from Flutter

Use the generated client in Flutter to call the API:

void fetchGreeting() async {
final message = await client.example.sayHello('Flutter Dev');
print(message); // Outputs: Hello, Flutter Dev! Welcome to Serverpod!
}

4. Working with the Database in Serverpod

  1. Define a Database Model Edit my_serverpod_project_server/protocol/user.yaml:
class: User
table: users
fields:
name: String
email: String

Generate the database migration and apply it

serverpod generate
serverpod migrate

2. Insert and Retrieve Data

Modify example.dart:

import 'package:serverpod/serverpod.dart';
import '../generated/protocol.dart';

class ExampleEndpoint extends Endpoint {
Future<void> createUser(Session session, String name, String email) async {
final user = User(name: name, email: email);
await User.insert(session, user);
}

Future<List<User>> getUsers(Session session) async {
return await User.find(session);
}
}

3. Fetch Data in Flutter

Use the Flutter client to retrieve users:

void getUsers() async {
final users = await client.example.getUsers();
for (var user in users) {
print('${user.name} - ${user.email}');
}
}

5. Authentication & User Management in Serverpod

1. Enable Authentication

In server config, enable authentication:

authentication:
enabled: true
providers:
- type: password

2. Register a User

Modify auth.dart in server:

class AuthEndpoint extends Endpoint {
  Future<bool> register(Session session, String email, String password) async 

{
    return await Users.createUser(session, email, password);
  }
   Future<User?> login(Session session, String email, String password) async {
    return await Users.signIn(session, email, password);
  }
}

3. Call Authentication API in Flutter

Use the client SDK in Flutter:

void registerUser() async {
bool success = await client.auth.register('user@example.com', 'password123');
print(success ? 'Registered successfully' : 'Registration failed');
}

6. WebSockets & Real-time Features

1. Enable WebSockets

Modify server settings:

websockets:
enabled: true

2. Create a WebSocket Listener

In server:

class ChatEndpoint extends Endpoint {
void sendMessage(Session session, String message) {
session.messages.postMessage('chat', message);
}
}

3. Listen to WebSocket Messages in Flutter

In Flutter, listen for updates:

client.chat.stream.listen((message) {
print('New message: $message');
});

7. Deployment & Scaling Serverpod

Deploying on Docker

Generate a Docker image:

serverpod generate
serverpod docker build
serverpod docker run

Supports AWS, Google Cloud, and DigitalOcean for production.


8. Challenges in Using Serverpod

 Limited Ecosystem

  • Since Serverpod is relatively new, it lacks third-party plugins and integrations compared to Firebase or Node.js.

 Hosting & DevOps Complexity

  • Unlike Firebase, Serverpod requires a VPS or cloud setup (AWS, Google Cloud, or DigitalOcean).

 Learning Curve

  • While it’s Dart-based, understanding ORM, database migrations, and WebSockets may take time for new developers.

9. Limitations of Serverpod

 Lack of NoSQL Support

  • Serverpod only supports PostgreSQL, meaning MongoDB or Firestore users need an alternative approach.

 Limited Documentation & Community

  • Serverpod doesn’t have as large a community as Firebase or Node.js, leading to fewer tutorials and StackOverflow answers.

 Not Ideal for Low-Code Development

  • Serverpod is developer-focused and not a low-code backend like Firebase, meaning you need backend coding experience.

10. Future Scope of Serverpod

More Database Support

  • Future versions may add support for MySQL and NoSQL databases.

 Improved DevOps & Hosting

  • A one-click deployment solution (like Firebase Hosting) could make it easier to use.

 More Third-Party Integrations

  • Adding payment gateways, analytics tools, and cloud storage support will improve its adoption.

 Better Mobile & Web Support

  • Improved WebSockets and GraphQL support will enhance real-time applications.

11. Conclusion

Serverpod is a powerful Dart-based backend framework that simplifies backend development for Flutter apps. With features like automatic API generation, database integration, authentication, caching, and WebSockets, it’s an excellent alternative to traditional backend solutions.

If you’re looking for a Flutter-first backend that’s scalable and easy to manage, Serverpod is worth exploring.

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


12. Reference

Get started | Serverpod
This page will help you understand how a Serverpod project is structured, how to make calls to endpoints, and how to…docs.serverpod.dev

serverpod | Dart package
Serverpod is an open-source, scalable app server, written in Dart for the Flutter community.pub.dev


From Our Parent Company Aeologic

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

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

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

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

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


Explore Adapter Design Pattern In Flutter

0

In software development, the adapter design pattern, also known as Wrapper, is a popular structural design pattern. Check out my previous articles on the design pattern if you’re not sure what a design pattern is.

This blog will Explore Adapter Design Pattern In Flutter. We see how to execute a demo program 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::

What is the Adapter Design Pattern?

When to use?

Code Implement

Drawbacks

Conclusion



What is the Adapter Design Pattern?

The Adapter design pattern, as described in the book “Design Patterns, Elements of Reusable Object-Oriented Software,” transforms a class’s interface into a different interface that clients expect. Classes that would not be able to work together without the adapter can now do so due to incompatible interfaces.

Let’s attempt to comprehend using a real-world example. Imagine that the music player in your car only plays cassettes, but you still want to listen to music on your smartphone. In this case, a cassette adaptor would be utilized. You can use your smartphone through the adapter’s interface, which also functions with the tape player.

We can therefore conclude that adapter design patterns are similar to actual adapters that provide a variety of functions.

When to use?

  • In situations where you must utilize an existing class whose interface differs from your needs.
  • When you wish to design a reusable class that works with unexpected or unrelated classes—that is, classes that may not have compatible interfaces.
  • You can use an adapter to modify the interface of its parent class when it is not feasible to modify the interface of several existing subclasses by subclassing each one.

Code Implement

Let’s now attempt to comprehend using an example of code. Consider that you have two data sources at your disposal: UserAPI, which delivers data in JSON format, and EmployeeAPI, which gives data in XML format. But your application needs JSON-formatted data. The Adapter Design Pattern is applicable in this situation.

The XML data from EmployeeAPI can be converted into JSON format by creating an adapter called XMLToJSONAdapter. Even though the original data formats were different, this enables your application to handle data from both APIs consistently.

import 'dart:convert';

abstract class JSONDataInterface {
  String getData();
}

class UserAPI implements JSONDataInterface {
  @override
  String getData() {
    return jsonEncode({"name": "Sam", "age": 25});
  }
}

class EmployeeAPI {
  String getData() {
    return "<employee><name>Roy</name><age>22</age></employee>";
  }
}

class XMLToJSONAdapter implements JSONDataInterface {
  EmployeeAPI _employeeApi;
  XMLToJSONAdapter(this._employeeApi);

  @override
  String getData() {
    var xmlData = _employeeApi.getData();
    var name = xmlData.split("<name>")[1].split("</name>")[0];
    var age = xmlData.split("<age>")[1].split("</age>")[0];
    var jsonData = jsonEncode({"name": name, "age": age});
    return jsonData;
  }
}

void displayData(JSONDataInterface api) {
  print(api.getData());
}

void main() {
  var userApi = UserAPI();
  var employeeApi = EmployeeAPI();
  var adapter = XMLToJSONAdapter(employeeApi);

  displayData(userApi); 
  displayData(adapter);
}

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

{"name":"Sam","age":25}
{"name":"Roy","age":"22"}

Process finished with exit code 0

EmployeeAPI returns XML data, whereas UserAPI returns JSON data directly. To make the XML data from EmployeeAPI compatible with the rest of the system that requires JSON data, the XMLToJSONAdapter class transforms it into JSON format.

Drawbacks:

  • By adding numerous small, related classes, the Adapter Pattern can complicate the program structure and make it more difficult to understand the code at first look.
  • Performance-wise, data adaptation can be costly, particularly when working with big data sets or intricate data structures.

Conclusion:

In the article, I have explained the Adapter Design Pattern basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to the Adapter 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 Explore Adapter Design Pattern in your Flutter projects. To guarantee compatibility across classes with mismatched interfaces, the Adapter Design Pattern is helpful. It makes it easier to combine new classes with old code by increasing the flexibility and reusability of existing code. 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.


CRUD Operation With SQLite In Flutter

0

Here I don’t have to tell the worth of the Flutter cross-platform framework over and over. It is primarily for building Android and IOS applications with Dart. Could it be said that you are searching for a method for utilizing your Flutter project’s mobile device storage as a database? Simply integrating a SQLite package will do it for you. For all local SQL storage purposes, Flutter has presented the sqflite plugin. So we can accomplish all the nearby local storage-related capabilities through that plugin.

In this article, we will explore the CRUD Operation With SQLite In Flutter. We perceive how to execute a demo program. We will show you the simplest way to put away CRUD, create, update, read, and delete your data on the SQLite database utilizing sqflite package and provider state management. We will utilize an implanted SQLite database engine to store the database in Flutter Android and iOS in your Flutter applications.

For Sqflite:

sqflite 2.2.8+4 | Flutter Package
Flutter plugin for SQLite, a self-contained, high-reliability, embedded, SQL database engine.pub.dev

For path_provider:

path_provider | Flutter Package
Flutter plugin for getting commonly used locations on host platform file systems, such as the temp and app data…pub.dev

For Provider:

provider | Flutter Package
A wrapper around InheritedWidget to make them easier to use and more reusable.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

Implementation

Code Implement

Code File

Conclusion

Github Link



Introduction:

This demo video shows how to perform a CRUD Operation With SQLite in Flutter and how CRUD Operation will work using the sqflite package and provider state management in your Flutter applications. We will show you the simplest way to store away CRUD, create, update, read, and delete your data on the SQLite database. 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
sqflite: ^2.2.8+4
path_provider: ^2.1.1
provider: ^6.0.1

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 user_model.dart inside the lib folder.

Create the user model which demonstrates the data structure that we want to manipulate inside the database. For this, we should create a class with the required properties and a method to map the data before inserting it into the database.

class UserModel {
int? id;
String name;
String email;
String desc;

UserModel({this.id, required this.name, required this.email, required this.desc});

Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'email': email,
'desc': desc,
};
}

factory UserModel.fromMap(Map<String, dynamic> map) {
return UserModel(
id: map['id'],
name: map['name'],
email: map['email'],
desc: map['desc'],
);
}
}

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

Declare a function that uses imports to open a database connection. Use a user model class and create insertUser()getUsers()updateUser(), and deleteUser() functions.

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

import '../model/user_model.dart';

class DatabaseHelper {
Database? _database;

Future<Database?> get database async {
if (_database != null) return _database;

_database = await initDatabase();
return _database;
}

Future<Database> initDatabase() async {
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'users.db');

return await openDatabase(path, version: 1, onCreate: _onCreate);
}

Future<void> _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT,
desc TEXT
)
''');
}

Future<int> insertUser(UserModel user) async {
Database? db = await database;
return await db!.insert('users', user.toMap());
}

Future<List<UserModel>> getUsers() async {
Database? db = await database;
List<Map<String, dynamic>> maps = await db!.query('users');
return List.generate(maps.length, (i) {
return UserModel.fromMap(maps[i]);
});
}

Future<int> updateUser(UserModel user) async {
Database? db = await database;
return await db!.update(
'users',
user.toMap(),
where: 'id = ?',
whereArgs: [user.id],
);
}

Future<int> deleteUser(int id) async {
Database? db = await database;
return await db!.delete('users', where: 'id = ?', whereArgs: [id]);
}
}

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

We will create the class UserProvider with ChangeNotifier and add it to the inside database function and also create loadUsers()addUser()updateUser(), and deleteUser() with notifyListeners().

import 'package:flutter/material.dart';
import 'package:flutter_sqlite_demo/database/database_helper.dart';
import 'package:flutter_sqlite_demo/model/user_model.dart';

class UserProvider with ChangeNotifier {
bool isLoading = false;
List<UserModel> _users = [];
final DatabaseHelper _databaseHelper = DatabaseHelper();

List<UserModel> get users => _users;

Future<void> loadUsers() async {
isLoading = true;
_users = await _databaseHelper.getUsers();
isLoading = false;
notifyListeners();
}

Future<void> addUser(UserModel user) async {
await _databaseHelper.insertUser(user);
notifyListeners();
}

Future<void> updateUser(UserModel user) async {
await _databaseHelper.updateUser(user);
notifyListeners();
}

Future<void> deleteUser(int id) async {
await _databaseHelper.deleteUser(id);
await loadUsers();
}
}

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

In this screen, we will show data when the user creates the data and then show a list of data on this screen. We will add the ListView.builder() method. In this method, we will add the itemCount and itemBuilder. In itemBuilder, we will add a ListTile widget. In this widget, we will add a title, on the subtitle we will add two texts, on the trailing we will add two icons delete, and edit icons.

Consumer<UserProvider>(builder: (context, userProvider, _) {
return userProvider.isLoading
? const Center(child: CircularProgressIndicator())
: userProvider.users.isEmpty
? const Center(
child: Text(
"Data Not Found",
style: TextStyle(fontSize: 18),
))
: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView.builder(
itemCount: userProvider.users.length,
itemBuilder: (context, index) {
final user = userProvider.users[index];
return Card(
elevation: 3,
color: Colors.teal.shade300,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListTile(
title: Padding(
padding: const EdgeInsets.only(bottom: 5.0),
child: Text(
user.name,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
user.email,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
const SizedBox(
height: 5,
),
Text(
user.desc,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(
Icons.edit,
color: Colors.black,
),
onPressed: () {
_navigateToEditUser(context, user);
},
),
IconButton(
icon: const Icon(Icons.delete,
color: Colors.black),
onPressed: () {
userProvider.deleteUser(user.id ?? 0);
},
),
],
),
),
),
);
},
),
);
})

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

Output

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

In this screen, the user will create a database. The user fills in all the textformfield and presses the save button then the database creates and shows the data on UserListScreen().

import 'package:flutter/material.dart';
import 'package:flutter_sqlite_demo/database/database_helper.dart';
import 'package:flutter_sqlite_demo/model/user_model.dart';
import 'package:flutter_sqlite_demo/provider/user_provider.dart';
import 'package:flutter_sqlite_demo/screens/user_list_screen.dart';
import 'package:provider/provider.dart';

class CreateUserScreen extends StatefulWidget {

const CreateUserScreen({super.key});

@override
State<CreateUserScreen> createState() => _CreateUserScreenState();
}

class _CreateUserScreenState extends State<CreateUserScreen> {
final TextEditingController nameController = TextEditingController();

final TextEditingController emailController = TextEditingController();

final TextEditingController descController = TextEditingController();

final _formKey = GlobalKey<FormState>();


void _submitForm() async {
if (_formKey.currentState?.validate() ?? false) {
final user = UserModel(
name: nameController.text,
email: emailController.text,
desc: descController.text,
);
Provider.of<UserProvider>(context, listen: false).addUser(user);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const UserListScreen(),),
);
nameController.clear();
emailController.clear();
descController.clear();
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Create User'),

),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: nameController,
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter a name';
}
return null;
},
decoration: const InputDecoration(labelText: 'Name'),
),
TextFormField(
controller: emailController,
validator: (input) => !input!.contains('@')
? 'Please enter a valid email'
: null,
//onSaved: (input) => _email = input!,
decoration: const InputDecoration(labelText: 'Email'),
),
TextFormField(
controller: descController,
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter a description';
}
return null;
},
decoration: const InputDecoration(labelText: 'Desc'),
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: _submitForm,
child: const Text('Save'),
),
],
),
),
),
);
}
}

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

Output

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

In this screen, the user will update the current data, save the new data from the database, and show the updated data on UserListScreen().

import 'package:flutter/material.dart';
import 'package:flutter_sqlite_demo/model/user_model.dart';
import 'package:flutter_sqlite_demo/provider/user_provider.dart';
import 'package:flutter_sqlite_demo/screens/user_list_screen.dart';
import 'package:provider/provider.dart';

class EditUserScreen extends StatefulWidget {
final UserModel user;

const EditUserScreen({super.key, required this.user});

@override
State<EditUserScreen> createState() => _EditUserScreenState();
}

class _EditUserScreenState extends State<EditUserScreen> {
final _formKey = GlobalKey<FormState>();
final nameController = TextEditingController();
final emailController = TextEditingController();
final descController = TextEditingController();

@override
void initState() {
super.initState();
nameController.text = widget.user.name;
emailController.text = widget.user.email;
descController.text = widget.user.desc;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Edit User'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: nameController,
decoration: const InputDecoration(labelText: 'Name'),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter a name';
}
return null;
},
),
TextFormField(
controller: emailController,
decoration: const InputDecoration(labelText: 'Email'),
validator: (input) =>
!input!.contains('@') ? 'Please enter a valid email' : null,
//onSaved: (input) => _email = input!,
),
TextFormField(
controller: descController,
decoration: const InputDecoration(labelText: 'Desc'),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter a description';
}
return null;
},
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
if (_formKey.currentState?.validate() ?? false) {
final updatedUser = UserModel(
id: widget.user.id,
name: nameController.text,
email: emailController.text,
desc: descController.text,
);
Provider.of<UserProvider>(context, listen: false)
.updateUser(updatedUser);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UserListScreen(),
),
);
}
},
child: const Text('Save'),
),
],
),
),
),
);
}
}

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

Output

Code File:


import 'package:flutter/material.dart';
import 'package:flutter_sqlite_demo/model/user_model.dart';
import 'package:flutter_sqlite_demo/provider/user_provider.dart';
import 'package:flutter_sqlite_demo/screens/create_user_screen.dart';
import 'package:flutter_sqlite_demo/screens/edit_user_screen.dart';
import 'package:provider/provider.dart';

import '../app_constants.dart';

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

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

class _UserListScreenState extends State<UserListScreen> {
final userProvider =
Provider.of<UserProvider>(AppConstants.globalNavKey.currentContext!);

@override
void initState() {
// TODO: implement initState
userProvider.loadUsers();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('User List'),
),
body: Consumer<UserProvider>(builder: (context, userProvider, _) {
return userProvider.isLoading
? const Center(child: CircularProgressIndicator())
: userProvider.users.isEmpty
? const Center(
child: Text(
"Data Not Found",
style: TextStyle(fontSize: 18),
))
: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView.builder(
itemCount: userProvider.users.length,
itemBuilder: (context, index) {
final user = userProvider.users[index];
return Card(
elevation: 3,
color: Colors.teal.shade300,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListTile(
title: Padding(
padding: const EdgeInsets.only(bottom: 5.0),
child: Text(
user.name,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
user.email,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
const SizedBox(
height: 5,
),
Text(
user.desc,
style: const TextStyle(
fontSize: 18, color: Colors.white),
),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(
Icons.edit,
color: Colors.black,
),
onPressed: () {
_navigateToEditUser(context, user);
},
),
IconButton(
icon: const Icon(Icons.delete,
color: Colors.black),
onPressed: () {
userProvider.deleteUser(user.id ?? 0);
},
),
],
),
),
),
);
},
),
);
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
_navigateToCreateUser(context);
},
child: const Icon(Icons.add),
),
);
}

void _navigateToCreateUser(BuildContext context) async {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CreateUserScreen()),
);
setState(() {});
}

void _navigateToEditUser(BuildContext context, UserModel user) async {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => EditUserScreen(user: user)),
);
setusing firebaseState(() {});
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the CRUD Operation With SQLite in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on CRUD Operation With SQLite 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.Conclusion:


GitHub Link:

find the source code of the Flutter Sqlite Demo:

GitHub – flutter-devs/flutter_sqlite_demo
Contribute to flutter-devs/flutter_sqlite_demo 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! 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.