Google search engine
Home Blog Page 58

Explore Scratch Card Animation In Flutter

0

In this article, we will Explore Scratch Card Animation In Flutter. We see how to execute a demo program. We will tell you the best way how to make an interactive and immersive scratch card animation using the scratcher package in your Flutter applications.

For Scratcher

scratcher | Flutter package
Scratch card widget which temporarily hides content from the user.pub.dev

For Confetti

confetti | Flutter package
Blast colorful confetti all over the screen. Celebrate in app achievements with style. Control the velocity, angle…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



Introduction

A scratch card animation to your Flutter application can be only the remarkable touch you want to enamor users and upgrade engagement. Envision the expectation as clients swipe away to uncover stowed away satisfied, suggestive of lottery scratch cards. Scratch cards are inseparable from fervor and secret.

Scratch cards uncover discounts, extraordinary offers, or selective content, scratch card animations offer a tomfoolery and connecting method for interfacing with your application.

The below demo video shows how to make a scratch card animation in Flutter and how a scratch card animation will work using the scratcher package in your Flutter applications. We will make a scratch card for users when users swipe the card to reveal hidden prices. 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
scratcher: ^2.5.0
confetti: ^0.7.0

Step 2: Import

import 'package:scratcher/scratcher.dart';
import 'package:confetti/confetti.dart';

Step 3: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the main.dart file, we will create a new class ScratchCard() in the same dart file. In this class, we will make a late ConfettiController variable was _controller.

late ConfettiController _controller;

Now, we will add the initState() method. In this method, we will add the _controller is equal to the ConfettiController(). Inside the bracket we will add a duration was 2 seconds.

@override
void initState() {
super.initState();
_controller = ConfettiController(
duration: const Duration(seconds: 2),
);
}

In the body, we will add a Scratcher() method. In this method, we will add brushSize was 50 means the size of the brush. The bigger it is the faster the user can scratch the card, a threshold was 75 means the percentage level of the scratch area that should be revealed to complete. The scratch is finished and reaches the threshold value, ConfettiController will create a confetti animation. 

Center(
child: Scratcher(
brushSize: 50,
threshold: 75,
color: Colors.blue,
image: Image.asset(
"assets/scratch.jpeg",
fit: BoxFit.fill,
),
onChange: (value) => print("Scratch progress: $value%"),
onThreshold: () => _controller.play(),
child: SizedBox(
height: MediaQuery.of(context).size.height*0.3,
width: MediaQuery.of(context).size.width*0.6,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
"assets/reward.png",
fit: BoxFit.cover,
width: MediaQuery.of(context).size.height*0.25,
height: MediaQuery.of(context).size.height*0.25,
),
Column(
children: [
ConfettiWidget(
blastDirectionality: BlastDirectionality.explosive,
confettiController: _controller,
particleDrag: 0.05,
emissionFrequency: 0.05,
numberOfParticles: 100,
gravity: 0.05,
shouldLoop: false,
colors: const [
Colors.green,
Colors.red,
Colors.yellow,
Colors.blue,
Colors.purple
],
),
],
),
],
),
),
),
)

The Scratcher widget has the property “onThreshold” to play confetti animation inside the application. ConfettiWidget and reward picture are added as a child of the Scratcher widget to show the prizes. Modify the confetti animation involving properties in ConfettiWidget as we have added a few properties in our model.

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

Output

Code File:

import 'package:confetti/confetti.dart';
import 'package:flutter/material.dart';
import 'package:flutter_scratch_card_demo/splash_screen.dart';
import 'package:scratcher/scratcher.dart';

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

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

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

),
home: const Splash(),
);
}
}

class ScratchCard extends StatefulWidget {
const ScratchCard({Key? key}) : super(key: key);

@override
State<ScratchCard> createState() => _ScratchCardState();
}

class _ScratchCardState extends State<ScratchCard> {
late ConfettiController _controller;

@override
void initState() {
super.initState();
_controller = ConfettiController(
duration: const Duration(seconds: 2),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: const Text("Flutter Scratch Card Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.tealAccent,),
body: Center(
child: Scratcher(
brushSize: 50,
threshold: 75,
color: Colors.blue,
image: Image.asset(
"assets/scratch.jpeg",
fit: BoxFit.fill,
),
onChange: (value) => print("Scratch progress: $value%"),
onThreshold: () => _controller.play(),
child: SizedBox(
height: MediaQuery.of(context).size.height*0.3,
width: MediaQuery.of(context).size.width*0.6,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
"assets/reward.png",
fit: BoxFit.cover,
width: MediaQuery.of(context).size.height*0.25,
height: MediaQuery.of(context).size.height*0.25,
),
Column(
children: [
ConfettiWidget(
blastDirectionality: BlastDirectionality.explosive,
confettiController: _controller,
particleDrag: 0.05,
emissionFrequency: 0.05,
numberOfParticles: 100,
gravity: 0.05,
shouldLoop: false,
colors: const [
Colors.green,
Colors.red,
Colors.yellow,
Colors.blue,
Colors.purple
],
),
],
),
],
),
),
),
),
);
}
}

Conclusion:

In the article, I have explained the scratch card animation in Flutter; you can modify this code according to your choice. This was a small introduction to the scratch card animation 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 Scratch Card Animation in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Scratch Card Animation using the scratcher package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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


Face Mask Detection App In Flutter With TensorFlow Lite

0

COVID-19 crises have drastically affected our livelihood. There are many guidelines given by WHO to prevent the spread of the COVID-19 virus. This virus is very dangerous and infectious. In today’s scenarios, it has become mandatory to wear a mask in public places. In many countries, people are even charged money for not wearing a mask. So it has become our moral duty to wear a mask in public places, but some people are not following the guidelines. The system can’t identify the people who are not wearing a mask, so it has become important to build a tool to identify the person whether he/she is wearing a mask or not. With the help of Machine Learning & Deep Learning, we can easily build a model and train it with a dataset to solve this problem and help prevent the spread of the COVID-19 virus.

In this blog, we shall learn how to build a Face Mask Detection app with Flutter using tflite package to identify whether the person is wearing a mask or not.


Table of contents:

Install Packages

Configure Project

Download training dataset & train our model

Initializing Camera

Load Model

Run Model

Camera Preview

Full Code


Demo Module:

Install Packages:

To build this app we will need two packages:

camera | Flutter Package
A Flutter plugin for iOS and Android allows access to the device cameras. Note: This plugin is still under…pub.dev

tflite | Flutter Package
A Flutter plugin for accessing TensorFlow Lite API. Supports image classification, object detection ( SSD and YOLO)…pub. dev

  • camera the package is used to get the streaming image buffers.
  • tflite is used to run our trained model.

Configure Project:

  • For Android

In android/app/build.gradle, add the following setting in android block.

aaptOptions {
noCompress 'tflite'
noCompress 'lite'
}
  • Change minSdkVersion 21

Download training dataset & train our model:

  • To download the dataset visit kaggle.com and search for “Face mask detection”.
  • Download the dataset.

COVID Face Mask Detection Dataset
This dataset contains about 1006 equally distributed images of 2 distinct types.www.kaggle.com

  • Upload the images of masked people in With mask class and Without mask images in Without mask class.
  • Then click on Train Model , do not change the settings.
  • Export the model.
  • Click on Tensorflow Lite and download the model.
  • Click on Ok
  • Export the model.tflite and lable.txt file and store them in the assets folder in your project.

Let’s start coding:

Initializing Camera:

Inside the main method initialize the available cameras using availableCameras.

List<CameraDescription> cameras;

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}

camera the package provides us with support for live image streaming. Firstly create an object of the CameraController. CameraController takes two arguments CameraDescription and ResolutionPreset. initialize the cameraController and then we can start our image streaming using the startImageStream method. startImageStream the method that provides us with the images, we will give these images to cameraImage and then we will run our model.

CameraImage cameraImage;
CameraController cameraController;
String result = "";

initCamera() {
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value) {
if (!mounted) return;
setState(() {
cameraController.startImageStream((imageStream) {
cameraImage = imageStream;
runModel();
});
});
});
}

Load Model:

Tflite provides us loadModel method to load our model. It takes two values model file path and labels file path.

loadModel() async {
await Tflite.loadModel(
model: "assets/model.tflite", labels: "assets/labels.txt");
}

Run Model:

In this method, we will run the model using Tflite. Here we are using the live stream of the image so we will have to use runModelOnFrame the method to run our model.

runModel() async {
if (cameraImage != null) {
var recognitions = await Tflite.runModelOnFrame(
bytesList: cameraImage.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: cameraImage.height,
imageWidth: cameraImage.width,
imageMean: 127.5,
imageStd: 127.5,
rotation: 90,
numResults: 2,
threshold: 0.1,
asynch: true);
recognitions.forEach((element) {
setState(() {
result = element["label"];
print(result);
});
});
}
}

recognitions is the list of future so for each element or label text, we will set it to result variable.

initState method:

@override
void initState() {
super.initState();
initCamera();
loadModel();
}

Camera Preview:

Tflite package provide us CameraPreview widget to preview the camera on the app screen, it takes cameraController .

AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),

Displaying Result

Text(
result,
style: TextStyle(fontWeight: FontWeight.bold,fontSize: 25),
)

Full Code:

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:tflite/tflite.dart';

List<CameraDescription> cameras;

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
CameraImage cameraImage;
CameraController cameraController;
String result = "";

initCamera() {
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value) {
if (!mounted) return;
setState(() {
cameraController.startImageStream((imageStream) {
cameraImage = imageStream;
runModel();
});
});
});
}

loadModel() async {
await Tflite.loadModel(
model: "assets/model.tflite", labels: "assets/labels.txt");
}

runModel() async {
if (cameraImage != null) {
var recognitions = await Tflite.runModelOnFrame(
bytesList: cameraImage.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: cameraImage.height,
imageWidth: cameraImage.width,
imageMean: 127.5,
imageStd: 127.5,
rotation: 90,
numResults: 2,
threshold: 0.1,
asynch: true);
recognitions.forEach((element) {
setState(() {
result = element["label"];
print(result);
});
});
}
}

@override
void initState() {
super.initState();
initCamera();
loadModel();
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Face Mask Detector"),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Container(
height: MediaQuery.of(context).size.height - 170,
width: MediaQuery.of(context).size.width,
child: !cameraController.value.isInitialized
? Container()
: AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),
),
),
Text(
result,
style: TextStyle(fontWeight: FontWeight.bold,fontSize: 25),
)
],
),
),
);
}
}

flutter-devs/flutter_tflite
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


🌸🌼🌸 Thank you for reading. 🌸🌼🌸

From Our Parent Company Aeologic

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

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

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

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

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

Declarative and Imperative Programming in the flutter

0

Maybe after reading the heading you would be thinking about how this core concept is relevant in the flutter. So the answer is “Core Concept remains the same irrespective of language and framework”, and here we are going to take a look at what is this declarative and imperative programming, what are the advantages, and how both things effect or affect the programming approaches.

Declarative programming and imperative programming are two different approaches to get your work done


Table Of Contents::

Declarative Programming

Imperative Programming

Reusability

Managing Errors

Lack Of control

Lack of Efficiency

Conclusion


Declarative Programming:

Declarative programming is a kind of programming or approach where we mainly focus on our desired output or what would be the result irrespective of process, approaches, coding pattern. We simply pay attention to what we are trying to achieve.

Imperative Programming:

Imperative programming is a kind of programming or approach where we make our focus on the process, follow guidelines, patterns step by step and try to compile things in order from where the correct answer can be found.

These definitions of both approaches would have cleared the basic difference between them but let’s take a little glance over this analogy again if you are wanting a final product or output without caring about the path process or pattern and wanting it to get ready for the final version and able to do so it comes under the declarative kind of thing.

While you are not only wanting to get your product done but you are focusing on the thing like skills, you want yourself to get involved with the product make your self able to do thing by your own only just to make up the requirements keeping all legitimate requirements in a best-suited way is comes under imperative programming.

Why you should Prefer Declarative Programming

Reusability:

In declarative programming the main aim to write code that could be reusable. In flutter, there are different ways to do so like using extensions or making custom widgets(at a normal level) however this is not the main aim of declarative programming but making a big whole module that can perform the whole required operation. here we are going to see a simple example of an extension method that we can use in the whole app but write only once.

import 'package:flutter/material.dart';

extension ShapeBorderX on ShapeBorder {
static ShapeBorder roundedRectangle(double radius) {
return RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(radius),
),
);
}
}

extension WidgetPaddingX on Widget {
Widget paddingAll(double padding) => Padding(
padding: EdgeInsets.all(padding),
child: this,
);
}

Managing Errors:

In Declarative programming, we write centralized code and try to manage each and everyone at the same place and does not change the working it helps to reduce errors while maintaining the code compilation and it helps to become your app more stable and make you able to read input-output of method efficiently.

But there are certain drawbacks of Declarative Programming

Lack Of control :

In Declarative programming, you may have a problem when you get something that contains the same thing but some additional features which have not been handled in your centralized code and this is a struggling time for you as a developer but as we know that flutter has a solution for this also, you need to define these new things also as an optional parameter.

import 'package:flutter/material.dart';
import 'package:gamekhelo/custome_widgets/custom_plain_button.dart';
import 'package:gamekhelo/extras/constants/index.dart';
import 'package:gamekhelo/extras/constants/dimensions.dart';
import 'package:gamekhelo/extras/theme/text_themes.dart';

class CustomDialog extends StatelessWidget {
final DialogType dialogType;
final String title;
final Function onOk;
final Function onCancel;
const CustomDialog({this.dialogType, this.title, this.onOk, this.onCancel});
@override
Widget build(BuildContext context) {
return Dialog(
backgroundColor: Colors.transparent,
child: Container(
height: Dimensions.boxHeight * 30,
width: Dimensions.boxWidth * 80,
padding: EdgeInsets.all(Dimensions.boxHeight * 3),
decoration: BoxDecoration(
color: ColorConstants.grey,
borderRadius: BorderRadius.circular(10),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
Text(
title,
style: TextThemes.h17.copyWith(
color: ColorConstants.textWhite70,
),
),
],
),
),
SizedBox(
height: Dimensions.boxHeight * 2,
),
SizedBox(
width: Dimensions.boxWidth * 70,
child: dialogType == DialogType.confirm
? Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 100,
child: CustomPlainButton(
isOutlined: true,
isSmall: true,
onTap: onCancel ??
() {
Navigator.pop(context);
},
label: "CANCEL",
),
),
SizedBox(
width: 100,
child: CustomPlainButton(
isSmall: true,
onTap: onOk ??
() {
Navigator.pop(context);
},
label: "OK",
),
),
],
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 100,
child: Center(
child: CustomPlainButton(
isSmall: true,
onTap: onOk ??
() {
Navigator.pop(context);
},
label: "OK",
),
),
),
],
),
),
],
),
),
);
}
}

for example, in the above code, you can see a Custom Dialogue where the only few required things and it is being used in the whole app but if you need to show an extra text at any place we are not going to design another dialogue but will make that text optional and will show. Now that extra text will be compiled in every dialogue even though it is not being used in other dialogues.

Lack of Efficiency:

When you are doing all these things which have mentioned above and you are making your whole code able to work on all desired features being used in your application but while you also having some part of code that is not being used in some special parts at that time compiler compiles that set of code while you are not using it. So sometimes it can be a little hectic for the compiler.

for example, you are using text field as a custom widget and performing some validation in some part and showing error while at some places you don’t need to do validation but when the code compiler will compile code it will compile at both places. (it can also be managed but it is an example for common understanding)

Conclusion:

In this article, we have understood how declarative programming can empower the working of any application and how it can be beneficial, when it comes to maintaining high-class code architecture however the examples explained above were just understanding of basics, and code snippets were only for a demo, but one thing is clear declarative programming is an approach which has been largely accepted and advocated by the community.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


How To Deal With Unwanted Widget Build In Flutter?

0

The flutter widget is built using a modern framework. It is like a reaction. In this, we start with the widget to create any application. Each component in the screen is a widget. The widget describes what his outlook should be given his present configuration and condition. Widget shows were similar to its idea and current setup and state. Flutter is a free and open-source tool to develop mobile, desktop, web applications with a single code base.

In this blog, we will explore How To Deal With Unwanted Widget Build In Flutter. We will also implement a demo of the unwanted widget build-in flutter and how to use them in your flutter applications. So let’s get started.


Table Of Contents :

Unwanted Widget Build In Flutter

Code Implement

Code File

Conclusion


Unwanted Widget Build-In Flutter :

The flutter build method in flutter describes the user interface represented by this widget when it is inserted in the build context provided in the widget tree and the dependency of the widget is changed. The build method is designed in such a way that it is without side effects It should be because many new widgets can be triggered such as root pop/push, screen size, etc. There are some ways to stop this unwanted widget build calling. Let’s talk about it below.

Now we will use some method to prevent the unwanted build calling which is as follows

  • Create a child Stateful class to create a UI using any widget.
  • Using the provider library, We can stop unwanted build method calling.

In these below situation build method call

  • After calling initState()
  • After calling didUpdateWidget()
  • When setState() is called.
  • When the keyboard is open
  • and When screen orientation changed
  • Parent Widget is built then child widget is rebuild

Code Implement :

You need to implement it in your code respectively:

First of all, we will see how this causes the effect of unwanted widget build. We should understand the design of the widget without any side effects instead of stopping any build call. Let’s understand this with the help of a reference

Future<int> intValue;

@override
void initState() {
intValue = Future.intValue(20);
super.initState();
}

@override
Widget build(BuildContext context) {
return FutureBuilder(
future: intValue,
builder: (context, snapshot) {
return
Column(
children: [
Text(
'$intValue',style: TextStyle(fontSize: 15),),Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
onPressed: () {
intValue.value += 1;
},
child: Text('Click Me'),
textColor: Colors.white,
color: Colors.green,
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
)), ],
),
},
);
}

This reference uses FutureBuilder in which if you re-invoke the build method, it will trigger the request by requesting an unwanted widget build method.

Now in this screen, we will see how to deal with the build of the unwanted build as we have used the ValueListenableBuilder class inside the column widget in this screen which allows us to rebuild some of the widgets we need and discard the expensive widgets.

Let us understand this with the help of a reference.

We will add ValueListenableBuilder() method. In this method, we will add a builder means a valueListenable-independent widget that is passed back to the builder. This argument is optional and can be null if the entire widget subtree the builder builds depends on the value of the valueListenable. We will pass parameter context, integer value, and widget child.

ValueListenableBuilder(
builder: (BuildContext context, int value, Widget child) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: [
Text(
'Pushed the button this many times',
style: TextStyle(fontSize: 15),
),
Text(
'$value',
style: TextStyle(fontSize: 15),
),
],
),
SizedBox(
height: 30,
),
AnimatedBuilder(
animation: animationController,
child: child,
builder: (context, child) {
return Transform.rotate(
angle: animationController.value * 6.3,
child: child,
);
},
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
onPressed: () {
startRotation();
_countClick.value -= 1;
},
child: Text(' Start Rotation'),
textColor: Colors.white,
color: Colors.pink.shade300,
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
)),
Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
onPressed: () {
stopRotation();
_countClick.value += 1;
},
child: Text('Stop Rotation'),
textColor: Colors.white,
color: Colors.green,
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
)),
],
),
],
);
},
valueListenable: _countClick,
child: FlutterLogo(
size: 150,
),
),

In this builder, we will return a column widget. Inside the widget, we will add a title and $value. We will add AnimatedBuilder() function, Inside the function, we will add animation, child, and builder. In builder, we will return a Transform. rotate(). Inside, we will add angle and child. We will create two RaisedButtons are ‘ Start Rotation’ and ‘Stop Rotation’. In Start Rotation, we will add onPressed() function. In this function, we will add startRotation() and _countClick.value is equal -1. When the user presses the button then the counter will decrease and rotation start. In Stop Rotation, we will add onPressed() function. In this function, we will add stopRotation() and _countClick.value is equal +1. When the user presses the button then the counter will increase and rotation will be stopped. We will add valueListenable means which builds a widget depending on the valueListenable’s value. Can incorporate a valueListenable value-independent widget subtree from the child parameter into the returned widget tree. We will add _countClick. In the child widget, we will add a flutter logo image.

Code File :

import 'dart:ui';

import 'package:flutter/material.dart';
import 'dart:math' as math;

class UnwantedWidgetDemo extends StatefulWidget {
@override
_UnwantedWidgetDemoState createState() => _UnwantedWidgetDemoState();
}

class _UnwantedWidgetDemoState extends State<UnwantedWidgetDemo>
with SingleTickerProviderStateMixin {
ValueNotifier<int> _countClick = ValueNotifier<int>(0);

AnimationController animationController;

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

animationController = new AnimationController(
vsync: this,
duration: new Duration(seconds: 5),
);

animationController.repeat();
}

stopRotation() {
animationController.stop();
}

startRotation() {
animationController.repeat();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Unwanted Widget Demo'),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ValueListenableBuilder(
builder: (BuildContext context, int value, Widget child) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: [
Text(
'Pushed the button this many times',
style: TextStyle(fontSize: 15),
),
Text(
'$value',
style: TextStyle(fontSize: 15),
),
],
),
SizedBox(
height: 30,
),
AnimatedBuilder(
animation: animationController,
child: child,
builder: (context, child) {
return Transform.rotate(
angle: animationController.value * 6.3,
child: child,
);
},
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
onPressed: () {
startRotation();
_countClick.value -= 1;
},
child: Text(' Start Rotation'),
textColor: Colors.white,
color: Colors.pink.shade300,
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
)),
Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
onPressed: () {
stopRotation();
_countClick.value += 1;
},
child: Text('Stop Rotation'),
textColor: Colors.white,
color: Colors.green,
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
)),
],
),
],
);
},
valueListenable: _countClick,
// The child parameter is most helpful if the child is
// expensive to build and does not depend on the value from
// the notifier.
child: FlutterLogo(
size: 150,
),
),
],
),
),
);
}
}

Conclusion:

In this article, I have explained How To Deal With Unwanted Widget Build In Flutter?, which you can modify and experiment with according to your own, this little introduction was from the How To Deal With Unwanted Widget Build In Flutter?.

I hope this blog will provide you with sufficient information in Trying up the How To Deal With Unwanted Widget Build In Flutter? in your flutter project. We showed you How To Deal With Unwanted Widget Build In Flutter? is and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

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

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

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

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

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

Live Object Detection App With Flutter and TensorFlow Lite

In this blog, we shall learn how to build an app that can detect Objects, and using AI and Deep Learning it can determine what the object is. Tflite provides us access to TensorFlow Lite .TensorFlow Lite is an open-source deep learning framework for on-device inference. To integrate tflite into our flutter app, we need to install tflite package and we need two files model.tflite and labels.txt . model.tflite is the trained model and labels.txt the file is a text file containing all the labels. Many websites provide us facility to train our model with our dataset and deploy them on TensorFlow Lite and we can directly get these two files from there. You can read my blog on Face Mask Detection App with Flutter and TensorFlow Lite to trains your model with your own dataset.

Face Mask Detection App In Flutter With TensorFlow Lite
Let’s learn how to build a flutter app that detects whether the person is wearing a mask or not on a live camera.medium.com


Demo Module:

***Demo Module***

Table of Contents:

Install Packages

Android Configuration

Initializing Camera

Load Model

Run Model

Display Boxes Around Recognized Objects

Camera Preview

Full Code


Install Packages:

camera | Flutter Package
A Flutter plugin for iOS and Android allowing access to the device cameras. Note: This plugin is still under…pub.dev

tflite | Flutter Package
A Flutter plugin for accessing TensorFlow Lite API. Supports image classification, object detection ( SSD and YOLO)…pub. dev

Android Configuration:

Change the minimum Android SDK version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

In android/app/build.gradle, add the following setting in android block.

aaptOptions {
noCompress 'tflite'
noCompress 'lite'
}

Add model and label files in the assets folder, also add them in pubspec.yaml

assets – Google Drive
Edit descriptiondrive.google.com

assets:
- assets/

Initializing Camera:

Inside the main method initialize the available cameras using availableCameras.

List<CameraDescription> cameras;Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}

camera the package provides us support for live image streaming. Firstly create an object of the CameraController . CameraController takes two arguments CameraDescription and ResolutionPreset . initialize the cameraController and then we can start our image streaming using the startImageStream method. startImageStream the method provides us the images, we will give these images to cameraImage, and then we will run our model.

CameraImage cameraImage;
CameraController cameraController;
initCamera() {
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value) {
if (!mounted) return;
setState(() {
cameraController.startImageStream((image) {
cameraImage = image;
runModel();
});
});
});
}

Load Model:

Tflite provides us loadModel method to load our model. It takes two values model file path and labels file path.Future loadModel() async {
Tflite.close();
await Tflite.loadModel(
model: “assets/ssd_mobilenet.tflite”,
labels: “assets/ssd_mobilenet.txt”);
}

Run Model:

In this method, we will run the model using Tflite. Here we are using the live stream of the image so we will have to use the detectObjectOnFrame method to run our model.

runModel() async {
recognitionsList = await Tflite.detectObjectOnFrame(
bytesList: cameraImage.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: cameraImage.height,
imageWidth: cameraImage.width,
imageMean: 127.5,
imageStd: 127.5,
numResultsPerClass: 1,
threshold: 0.4,
);

setState(() {
cameraImage;
});
}

Display Boxes Around Recognized Objects:

List<Widget> displayBoxesAroundRecognizedObjects(Size screen) {
if (recognitionsList == null) return [];

double factorX = screen.width;
double factorY = screen.height;

Color colorPick = Colors.pink;

return recognitionsList.map((result) {
return Positioned(
left: result["rect"]["x"] * factorX,
top: result["rect"]["y"] * factorY,
width: result["rect"]["w"] * factorX,
height: result["rect"]["h"] * factorY,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
border: Border.all(color: Colors.pink, width: 2.0),
),
child: Text(
"${result['detectedClass']} ${(result['confidenceInClass'] * 100).toStringAsFixed(0)}%",
style: TextStyle(
background: Paint()..color = colorPick,
color: Colors.black,
fontSize: 18.0,
),
),
),
);
}).toList();
}

This is the box that will be displayed around the detected object. Each element of recognitionsList contains the following details

{
detectedClass: "hot dog",
confidenceInClass: 0.123,
rect: {
x: 0.15,
y: 0.33,
w: 0.80,
h: 0.27
}
}

detectedClass is the name of the object detected. confidenceInClass *100 is the % of correctness. rect are the dimensions of the object. We can use these params to display boxes around the identified object.

Camera Preview:

Tflite the package provides us CameraPreview a widget to preview the camera on the app screen, it takes cameraController .

AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController)

To display the boxes and camera preview together we need Stack . displayBoxesAroundRecognizedObjects return a list of boxes, we need to add this list into the Stack so we have created a list variable. Add the boxes in the list .

List<Widget> list = [];

list.add(
Positioned(
top: 0.0,
left: 0.0,
width: size.width,
height: size.height - 100,
child: Container(
height: size.height - 100,
child: (!cameraController.value.isInitialized)
? new Container()
: AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),
),
),
);

if (cameraImage != null) {
list.addAll(displayBoxesAroundRecognizedObjects(size));
}

Full Code :

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:tflite/tflite.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}

List<CameraDescription> cameras;

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
CameraController cameraController;
CameraImage cameraImage;
List recognitionsList;

initCamera() {
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value) {
setState(() {
cameraController.startImageStream((image) => {
cameraImage = image,
runModel(),
});
});
});
}

runModel() async {
recognitionsList = await Tflite.detectObjectOnFrame(
bytesList: cameraImage.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: cameraImage.height,
imageWidth: cameraImage.width,
imageMean: 127.5,
imageStd: 127.5,
numResultsPerClass: 1,
threshold: 0.4,
);

setState(() {
cameraImage;
});
}

Future loadModel() async {
Tflite.close();
await Tflite.loadModel(
model: "assets/ssd_mobilenet.tflite",
labels: "assets/ssd_mobilenet.txt");
}

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

cameraController.stopImageStream();
Tflite.close();
}

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

loadModel();
initCamera();
}

List<Widget> displayBoxesAroundRecognizedObjects(Size screen) {
if (recognitionsList == null) return [];

double factorX = screen.width;
double factorY = screen.height;

Color colorPick = Colors.pink;

return recognitionsList.map((result) {
return Positioned(
left: result["rect"]["x"] * factorX,
top: result["rect"]["y"] * factorY,
width: result["rect"]["w"] * factorX,
height: result["rect"]["h"] * factorY,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
border: Border.all(color: Colors.pink, width: 2.0),
),
child: Text(
"${result['detectedClass']} ${(result['confidenceInClass'] * 100).toStringAsFixed(0)}%",
style: TextStyle(
background: Paint()..color = colorPick,
color: Colors.black,
fontSize: 18.0,
),
),
),
);
}).toList();
}

@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
List<Widget> list = [];

list.add(
Positioned(
top: 0.0,
left: 0.0,
width: size.width,
height: size.height - 100,
child: Container(
height: size.height - 100,
child: (!cameraController.value.isInitialized)
? new Container()
: AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),
),
),
);

if (cameraImage != null) {
list.addAll(displayBoxesAroundRecognizedObjects(size));
}

return SafeArea(
child: Scaffold(
backgroundColor: Colors.black,
body: Container(
margin: EdgeInsets.only(top: 50),
color: Colors.black,
child: Stack(
children: list,
),
),
),
);
}
}}

🌸🌼🌸 Thank you for reading. 🌸🌼🌸

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 987tr project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

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

Adaptive Apps In Flutter

0

The same code base in flutter allows us to run on different platforms but different screen sizes, guidelines, and different ways of user interaction, so we have to create adaptive and responsive UI to create any UI which Looks and feels the same for all our operating systems.

In this blog, we will explore Adaptive Apps In Flutter. We will also implement a demo program and how to use them in your flutter applications. So let’s get started.


Table Of Contents :

Adaptive Apps

Demo Module

Code Implement

Code File

Conclusion


Adaptive Apps:

There is no clear definition of adaptive design in flutter but Platform adaptive apps include model overlays on desktops and sheets on mobile that reflect users’ expectations and allows layout and navigation flow from maximum utility flutter to easily adaptive and responsive UI across all platforms such as mobile, desktop devices.

Mobile Demo Module 

In this mobile demo video, an image list is shown in the background and using the SlidingUpPanel(), inside which the vertical and horizontal data list is displayed and SlidingUpPanel() is scrolling upwards.

Tablet Demo Module :

Mobile demo video and tablet video are the same, in this also an image list is shown in the background and the SlidingUpPanel() is used.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file calledadaptive_app_demo inside the lib folder.

Before creating the pulsating adaptive design, we have created a dart file inside which we have MediaQuery.of (reference). To test different mobile and tablet sizes. Which will manage our UI on screen size so we will use these functions inside the build function.

As we have taken a bool value for mobile when the width of our device is less than 800 then it will display the size of mobile.

static bool isMobile(BuildContext context) =>
MediaQuery.of(context).size.width < 800;

Similarly, we have taken a bool value for the tablet when the width of our device is more than 800 and less than 1200 then it will display the size of the tablet

static bool isTablet(BuildContext context) =>
MediaQuery.of(context).size.width >= 800 &&
MediaQuery.of(context).size.width < 1200;

After that, we have used two different widgets to deal with different shapes and we have created different dart files for these widgets.

Expanded(
child:isMobile(context)
? MobileScreen()
: isTablet(context)
? TabletScreen()
: MobileScreen(),
),

For Mobile View:

Now we have created a UI for mobile, inside which we have created a list containing some text and images. Let us understand this in detail.

First, we have created some model classes for the data list.

class HomeTestPanelModel{
String _img;
String _title;
String _subTitle;
HomeTestPanelModel(this._img,this._title,this._subTitle);
String get img=>_img;
String get title=>_title;
String get subTitle=>_subTitle;

}

After this, we have created a list with the help of the ListViewBuilder() widget, which contains the image and the title.

ListView.builder(
itemCount:homeScreenBackground.length,
scrollDirection:Axis.vertical,
shrinkWrap:true,
itemBuilder:(BuildContext context,int index){
return _buildHomeScreenBackground(homeScreenBackground[index]);
}
),

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

Mobile Output

For Tablet View:

We have created the same UI for both mobile and tablet, in this, we have also made a list and defined some data, So both the UI will be known only when the adaptive and responsive UI will be detected.

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

Tab Output

Code File :

import 'package:adaptive_app_demo/Constants/Constants.dart';
import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:adaptive_app_demo/model/home_screen_background.dart';
import 'package:adaptive_app_demo/model/home_test_panel_model.dart';
import 'package:adaptive_app_demo/model/home_test_type_model.dart';
import 'package:adaptive_app_demo/themes/appthemes.dart';
import 'package:adaptive_app_demo/themes/device_size.dart';

class MobileScreen extends StatefulWidget {
@override
_MobileScreenState createState() => _MobileScreenState();
}

class _MobileScreenState extends State<MobileScreen> {
List<HomeScreenBackground> homeScreenBackground;
List<HomeTestTypeModel> homeTestTypeModel;
List<HomeTestPanelModel> homeTestPanelModel;

@override
void initState() {
homeScreenBackground = Constants.getHomeScreenBackground();
homeTestTypeModel = Constants.getHomeTestTypeModel();
homeTestPanelModel = Constants.getHomeTestPanelModel();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Stack(
children: [
Container(
height: DeviceSize.height(context),
child: ListView.builder(
itemCount: homeScreenBackground.length,
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return _buildHomeScreenBackground(
homeScreenBackground[index]);
}),
),
Container(
padding: EdgeInsets.only(top: 20.0, left: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisAlignment:MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: Text(
'Welcome,',
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
letterSpacing: 0.5),
),
),
SizedBox(
height: 10,
),
Flexible(
child: Text(
'Aeomedix',
style: TextStyle(
fontSize: 19,
color: Colors.white,
fontWeight: FontWeight.bold,
letterSpacing: 0.5),
),
),
],
),
),
SlidingUpPanel(
defaultPanelState: PanelState.CLOSED,
parallaxEnabled: true,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0)),
maxHeight: DeviceSize.height(context) / 1,
minHeight: DeviceSize.height(context) / 1.5,
panel: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Column(
// mainAxisAlignment:MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: DeviceSize.height(context) / 6,
width: DeviceSize.width(context),
child: ListView.builder(
itemCount: homeTestTypeModel.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return _buildHomeTestModel(
homeTestTypeModel[index]);
}),
),
Container(
padding: EdgeInsets.only(top: 20, left: 15, right: 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: Text(
'Tests Panel',
style: TextStyle(
fontFamily: 'Roboto Medium',
fontWeight: FontWeight.w700,
fontSize: 13.0),
),
),
Flexible(
child: Text(
'See all',
style: TextStyle(
fontFamily: 'Roboto Regular',
color: AppTheme.color1,
fontSize: 13.0,
fontWeight: FontWeight.w600),
),
),
],
),
),
Container(
height: DeviceSize.height(context),
padding: EdgeInsets.only(left: 15, right: 15),
child: ListView.builder(
itemCount: homeTestPanelModel.length,
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
return _buildHomeTestPanelModel(
homeTestPanelModel[index]);
}),
),
],
),
),
),
],
),
),
);
}

Widget _buildHomeScreenBackground(HomeScreenBackground items) {
return Container(
width: DeviceSize.width(context),
child: Image.asset(
items.img,
height: DeviceSize.height(context) / 2.8,
width: DeviceSize.width(context),
fit: BoxFit.fill,
),
);
}

Widget _buildHomeTestModel(HomeTestTypeModel items) {
return Container(
padding: EdgeInsets.only(left: 30, top: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: CircleAvatar(
backgroundColor: AppTheme.color3.withOpacity(0.2),
maxRadius: 30,
child: Image.asset(
items.img,
scale: 6,
),
)),
// / SizedBox(height:DeviceSize.height(context)/30,),
Flexible(
child: Text(
items.title,
style: TextStyle(
fontSize: DeviceSize.height(context) / 60,
fontWeight: FontWeight.w700,
fontFamily: 'Roboto Medium'),
),
),
],
),
);
}

Widget _buildHomeTestPanelModel(HomeTestPanelModel items) {
return Container(
height: DeviceSize.height(context) / 10,
child: Card(
child: Padding(
padding: EdgeInsets.all(6),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
height: 60,
width: 60,
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(4)),
color: AppTheme.color3.withOpacity(0.2),
),
child: Image.asset(
items.img,
scale: 10,
),
),
SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Flexible(
child: Text(
items.title,
style: TextStyle(
fontSize: DeviceSize.height(context) / 60,
fontWeight: FontWeight.w700,
fontFamily: 'Roboto Medium'),
),
),
Flexible(
child: Text(
items.subTitle,
style: TextStyle(
fontSize: DeviceSize.height(context) / 60,
fontWeight: FontWeight.w700,
fontFamily: 'Roboto Medium',
color: AppTheme.color1),
),
),
],
),
],
),
Icon(
Icons.arrow_forward_ios,
size: 15,
)
],
),
),
),
);
}
}

Conclusion:

In this article, I have explained Adaptive Apps In Flutter, which you can modify and experiment with according to your own, this little introduction was from the Adaptive Apps In Flutter demo from our side.

I hope this blog will provide you with sufficient information in Trying up the Adaptive Apps In Flutter in your flutter project. We showed you what the Adaptive Apps In Flutter is and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

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

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

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

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

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

2026 Best Practices: SQLite Database Storage for Flutter Begin…

0

Hi Flutter developers, Today we shall learn how to build an app that uses SQLite to store the data locally. SQLite is a relational database management system contained in a C library. SQLite is not a client-server database engine. sqflite the package provides us to implement SQLite into our flutter app. This package provides various methods to insert, update, edit, and fetch queries from the database. Everything in this package is asynchronous.


Table of Contents:

About the sqflite

Create Model Class

Create Database Method

Create an ItemCard

Create a Form

Display the data

End Result

GitHub


About the sqflite:

sqflite | Flutter Package
SQLite plugin for Flutter. Supports iOS, Android, and macOS. Support transactions and batches Automatic version…pub. dev

  1. SQLite package provides us openDatabase a method to open the database at a specified path. the version property helps us to assign a version to the database. onCreate the property takes a Database and version . Inside the onCreate property, we can build our database table using execute method.
  2. To insert the data or model inside the database we use the insert method. It takes a table name and JSON value.
  3. To fetch the data from the database we use the query method. this method takes the name of the table that is needed to be fetched.
  4. To update the table query we use update the method. It takes the table name and id of the query that we want to update. Similarly, we can use the delete method to delete the query.

In this blog, we shall build an app that uses the above method to manage our local database.

Create Model Class:

Make a new file inside your lib folder, create a model inside it with the required properties. To convert the model to JSON we use the toJson method, which maps the Model properties into JSON format. fromJson method id used to convert the JSON data that is fetched from the database to Model class. Both methods are user-defined methods.

class Model {
int id;
String fruitName;
String quantity;

Model({this.id, this.fruitName, this.quantity});

Model fromJson(json) {
return Model(
id: json['id'], fruitName: json['fruitName'], quantity: json['quantity']);
}
Map<String, dynamic> toJson() {
return {'fruitName': fruitName, 'quantity': quantity};
}

}

Create Database Method:

Open the database

To open the database we use openDatabase the method takes the path and returns a Database object.

"CREATE TABLE name_of_table(id INTEGER PRIMARY KEY autoincrement, field_name_1 field_data_type, field_name_2 field_data_type)"

Using the following string we can execute and create a table in the local database by the name specified in the string (eg. model) and properties specified.

Database _database;
Future openDb() async {
_database = await openDatabase(join(await getDatabasesPath(), "ss.db"),
version: 1, onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE model(id INTEGER PRIMARY KEY autoincrement, fruitName TEXT, quantity TEXT)",
);
});
return _database;
}

Insert Data in the Database

To perform any operation on the database we need to open the database and then we can use the returned database object to perform the desired operation.

We can insert the data in JSON format using the insert method.

Future insertModel(Model model) async {
await openDb();
return await _database.insert('model', model.toJson());
}

Fetch the data

The query method gets the database data and return it in JSON format. To map the data with the model we can use the map method or we can use List.generate it to create a list of the model with the JSON data.

Future<List<Model>> getModelList() async {
await openDb();
final List<Map<String, dynamic>> maps = await _database.query('model');

return List.generate(maps.length, (i) {
return Model(
id: maps[i]['id'],
fruitName: maps[i]['fruitName'],
quantity: maps[i]['quantity']);
});
// return maps
// .map((e) => Model(
// id: e["id"], fruitName: e["fruitName"], quantity: e["quantity"]))
// .toList();
}

Update the data

Future<int> updateModel(Model model) async {
await openDb();
return await _database.update('model', model.toJson(),
where: "id = ?", whereArgs: [model.id]);
}

Delete database

Future<void> deleteModel(Model model) async {
await openDb();
await _database.delete('model', where: "id = ?", whereArgs: [model.id]);
}

database.dart

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

import 'model.dart';

class DbManager {
Database _database;

Future openDb() async {
_database = await openDatabase(join(await getDatabasesPath(), "ss.db"),
version: 1, onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE model(id INTEGER PRIMARY KEY autoincrement, fruitName TEXT, quantity TEXT)",
);
});
return _database;
}

Future insertModel(Model model) async {
await openDb();
return await _database.insert('model', model.toJson());
}

Future<List<Model>> getModelList() async {
await openDb();
final List<Map<String, dynamic>> maps = await _database.query('model');

return List.generate(maps.length, (i) {
return Model(
id: maps[i]['id'],
fruitName: maps[i]['fruitName'],
quantity: maps[i]['quantity']);
});
// return maps
// .map((e) => Model(
// id: e["id"], fruitName: e["fruitName"], quantity: e["quantity"]))
// .toList();
}

Future<int> updateModel(Model model) async {
await openDb();
return await _database.update('model', model.toJson(),
where: "id = ?", whereArgs: [model.id]);
}

Future<void> deleteModel(Model model) async {
await openDb();
await _database.delete('model', where: "id = ?", whereArgs: [model.id]);
}
}

You can use the above method to help you to build our app with a local database now we will see how to implement it will UI. Let’s Create an ItemCard widget that will display the data stored in the database.

Create an ItemCard:

class ItemCard extends StatefulWidget {
Model model;
TextEditingController input1;
TextEditingController input2;
Function onDeletePress;
Function onEditPress;

ItemCard(
{this.model,
this.input1,
this.input2,
this.onDeletePress,
this.onEditPress});

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

class _ItemCardState extends State<ItemCard> {
final DbManager dbManager = new DbManager();

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Name: ${widget.model.fruitName}',
style: TextStyle(fontSize: 15),
),
Text(
'Quantity: ${widget.model.quantity}',
style: TextStyle(
fontSize: 15,
),
),
],
),
Row(
children: [
CircleAvatar(
backgroundColor: Colors.white,
child: IconButton(
onPressed: widget.onEditPress,
icon: Icon(
Icons.edit,
color: Colors.blueAccent,
),
),
),
SizedBox(
width: 15,
),
CircleAvatar(
backgroundColor: Colors.white,
child: IconButton(
onPressed: widget.onDeletePress,
icon: Icon(
Icons.delete,
color: Colors.red,
),
),
)
],
),
],
),
),
),
);
}
}

This widget will display the fruitName and quantity. It will have an edit and delete a button that will handle deletes and edit functionality.

On pressing the edit button the user form will open with the respective item details and using that from we can update the data. On pressing the delete button the model will be deleted from the database and update the UI accordingly.

Create a Form:

The input form that the user will use to enter the details will be a dialogBox. This dialog box will be displayed when the user clicks the floatingActionButton and ItemCard edit button. It contains two TextFormField that takes the input from the user and two-button Cancel and Submit.

I have also implemented the focus node functionality. It will display the Done button on the keyboard on pressing the Done button the focus will be shifted to the specified TextField

focus.FocusScope.of(context).requestFocus(input2FocusNode);

class DialogBox {
Widget dialog(
{BuildContext context,
Function onPressed,
TextEditingController textEditingController1,
TextEditingController textEditingController2,
FocusNode input1FocusNode,
FocusNode input2FocusNode}) {
return AlertDialog(
title: Text("Enter Data"),
content: Container(
height: 100,
child: Column(
children: [
TextFormField(
controller: textEditingController1,
keyboardType: TextInputType.text,
focusNode: input1FocusNode,
decoration: InputDecoration(hintText: "Fruit Name"),
autofocus: true,
onFieldSubmitted: (value) {
input1FocusNode.unfocus();
FocusScope.of(context).requestFocus(input2FocusNode);
},
),
TextFormField(
controller: textEditingController2,
keyboardType: TextInputType.number,
focusNode: input2FocusNode,
decoration: InputDecoration(hintText: "Quantity"),
onFieldSubmitted: (value) {
input2FocusNode.unfocus();
},
),
],
),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blueGrey,
child: Text(
"Cancel",
),
),
MaterialButton(
onPressed: onPressed,
child: Text("Submit"),
color: Colors.blue,
)
],
);
}
}

Display the Data:

Everything in sqflite is asynchronous so we need FutureBuilder . The method getModelList returns a future of List of Model .

We will return the ItemCard for each _model . onDeletePress we will execute the delete method and onDeletePress we will perform the form edit.

//initialize the TextEditingController for both the input fields
TextEditingController input1 = TextEditingController();
TextEditingController input2 = TextEditingController();return FutureBuilder(
future: dbManager.getModelList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
modelList = snapshot.data;
return ListView.builder(
itemCount: modelList.length,
itemBuilder: (context, index) {
Model _model = modelList[index];
return ItemCard(
model: _model,
input1: input1,
input2: input2,
onDeletePress: () {
dbManager.deleteModel(_model);
setState(() {});
},
onEditPress: () {
input1.text = _model.fruitName;
input2.text = _model.quantity;
showDialog(
context: context,
builder: (context) {
return DialogBox().dialog(
context: context,
onPressed: () {
Model __model = Model(
id: _model.id,
fruitName: input1.text,
quantity: input2.text);
dbManager.updateModel(__model);

setState(() {
input1.text = "";
input2.text = "";
});
Navigator.of(context).pop();
},
textEditingController2: input2,
textEditingController1: input1);
});
},
);
},
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),

End Result:

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

Final Output Video

GitHub:

flutter-devs/sqflite_flutter
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

🌸🌼🌸 Thank you for reading. 🌸🌼🌸

From Our Parent Company Aeologic

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

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

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

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

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

Explore Shadows and Neumorphism in Flutter

0

Flutter is an open-source User Interface SDK that is Software Development Kit. Flutter is an open-source project, and it is maintained by Google. Currently, in March 2021. Google has been released another new version of flutter that is Flutter 2. Flutter as a software development kit is great, but while building a big application, there will be some problems or bugs in the code that has to be debugged. Flutter provides multiple debugging tools such as timeline inspector, memory and performance inspector, and else. These tools ease up the debugging process for a developer, below are listed different tools for debugging flutter apps.

In this blog, we will explore Explore Shadows and Neumorphism in Flutter. We will also implement a demo of the Shadows and Neumorphism in Flutter. How to use them in your flutter applications. So let’s get started.


Table Of Contents :

Shadows and Neumorphism in Flutter

Code Implement

Code File

Conclusion



Shadows and Neumorphism :

Flutter has another UI design trend just like the neumorphism gradient. It provides a soft and natural feel to the UI. It carefully selects the color of the background. There are also a lot of libraries to get neumorphism using which we can easily neumorphism effects can be obtained.

Neumorphism is probably the most trending design a year ago. It gives a delicate and characteristic inclination to your UI. It is a cautious choice of shadows, foundation color/gradient, and the general climate. At the point when you need a widget in Flutter to have this neumorphic impact, it’s pretty much as straightforward as messing with the boxShadow or shadows. If any widget has that property obviously, on the off chance that it doesn’t, you’ll need to discover a workaround, giving it a dull hued shadow and a light-hued shadow to accomplish this steady emblazon impact.

Code Implement:

You need to implement it in your code respectively:

First of all, we have used shadows in the text with the help of text widgets using shadows and neumorphism which gives us a blurs text effect. Flutter has great support for all the integral parts of Neumorphic UI: Shadows and Gradients.

Let us understand this with the help of a reference.

Neumorphic text:

Neumorphic components are constantly made at any rate out of two shadows are one lighter than the widget color, the other somewhat hazier. Underneath the snippet, we will add the content ‘Futter’ with shadows impact property. It’s very simple to add shadows to text. You define it directly through its style property.

Text(
'Futter',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 60,
shadows: [
Shadow(
offset: Offset(3, 3),
color: Colors.black38,
blurRadius: 10),
Shadow(
offset: Offset(-3, -3),
color: Colors.white.withOpacity(0.85),
blurRadius: 10)
],
color: Colors.grey.shade300),
),

Shadows are put somewhat moved from the center, and went against one another. The widget color should be basically the same as the background color, somewhat lighter, to make this “rise (height?) insight”.

Neumorphic basic shape:

That design infers drawing various shadows. So as composed before, PhysicalModel will not have the option to do the work. We can utilize DecoratedBox and Container for that reason. We will add a container widget. Inside the widget, we will set the height and width of the container. We will add alignment to the center. We will create a rectangular shape box with four different box-shadow colors.

Container(
height: 100,
width: 200,
alignment:Alignment.center,
decoration:BoxDecoration(
borderRadius: BorderRadius.circular(6.0),
color: Colors.grey.shade50,
shape: BoxShape.rectangle,
boxShadow: [
BoxShadow(
color: Colors.grey.shade300,
spreadRadius: 0.0,
blurRadius:10,
offset: Offset(3.0, 3.0)),
BoxShadow(
color: Colors.grey.shade400,
spreadRadius: 0.0,
blurRadius: 10 / 2.0,
offset: Offset(3.0, 3.0)),
BoxShadow(
color: Colors.white,
spreadRadius: 2.0,
blurRadius: 10,
offset: Offset(-3.0, -3.0)),
BoxShadow(
color: Colors.white,
spreadRadius: 2.0,
blurRadius: 10 / 2,
offset: Offset(-3.0, -3.0)),
],
),
child:Icon(Icons.star,color:Colors.yellow,),
),

Complex shapes:

If you need to add shadows to a more unpredictable shape, like a star, at that point the past widget will not get the job done. The main arrangement is PhysicalShape, identical to PhysicalModel, then again, actually, you can characterize appropriately your shape with a CustomClipper object. The other one is the CustomPaint, more intricate to deal with, yet in addition all the more remarkable.

Code File :

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

class NeumorphismDemo extends StatefulWidget {
@override
_NeumorphismDemoState createState() => _NeumorphismDemoState();
}

class _NeumorphismDemoState extends State<NeumorphismDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor:Colors.grey.shade100,
//backgroundColor: NeumorphicTheme.baseColor(context),
appBar:AppBar(
title:Text('Neumorphism Demo'),
),
body:Container(
child:Column(
mainAxisAlignment:MainAxisAlignment.center,
children: [
Container(
height: 100,
width: 200,
alignment:Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: Colors.grey.shade300,
boxShadow: [
BoxShadow(
offset: Offset(10, 10),
color: Colors.black38,
blurRadius: 20)
]),
child:Container(
alignment:Alignment.center,
child:Text(
'Futter',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 60,
shadows: [
Shadow(
offset: Offset(3, 3),
color: Colors.black38,
blurRadius: 10),
Shadow(
offset: Offset(-3, -3),
color: Colors.white.withOpacity(0.85),
blurRadius: 10)
],
color: Colors.grey.shade300),
),
),
),

Container(
height: 100,
width: 200,
alignment:Alignment.center,
decoration:BoxDecoration(
borderRadius: BorderRadius.circular(6.0),
color: Colors.grey.shade50,
shape: BoxShape.rectangle,
boxShadow: [
BoxShadow(
color: Colors.grey.shade300,
spreadRadius: 0.0,
blurRadius:10,
offset: Offset(3.0, 3.0)),
BoxShadow(
color: Colors.grey.shade400,
spreadRadius: 0.0,
blurRadius: 10 / 2.0,
offset: Offset(3.0, 3.0)),
BoxShadow(
color: Colors.white,
spreadRadius: 2.0,
blurRadius: 10,
offset: Offset(-3.0, -3.0)),
BoxShadow(
color: Colors.white,
spreadRadius: 2.0,
blurRadius: 10 / 2,
offset: Offset(-3.0, -3.0)),
],
),
child:Icon(Icons.star,color:Colors.yellow,),
),
],
),
),
);
}
}

Conclusion :

In this article, I have explained Explore Shadows and Neumorphism in Flutter?, which you can modify and experiment with according to your own, this little introduction was from the Explore Shadows and Neumorphism in Flutter?.

I hope this blog will provide you with sufficient information in Trying up the Explore Shadows and Neumorphism in Flutter? in your flutter project. We showed you Explore Shadows and Neumorphism in Flutter? is and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

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

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

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

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

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

Firebase Data Modeling Tips

0

Firestore is a flexible, scalable database for mobile, web, and server development from firebase and googles cloud. Like firebase’s real-time database, it keeps your data in-sync across client apps through real-time listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. cloud Firestore also offers seamless integration with other Firebase and google cloud products, including cloud functions.

Hello friends In this blog, we will learn about Firebase data modeling tips. How to store your data in a big tree-like structure like a real-time database and how it is stored in documents and collections. so let’s get started.


Table Of Contents :

Firestore Database Model

Cloud Firestore Database Structure

Normalization & Denormalization

Security In Firestore

Conclusion



Firestore Database Model:

When we create any mobile application, it is necessary to save the input data by the user, you have to save it in the cloud. To save in the cloud, we use Google’s Firebase Firestore Database. Firestore is a kind of nozzle database that your iOS, Can be accessed directly through the native SDK for Android web apps using Cloud Firestore’s NoSql data model, storing data in all documents in which the data is mapped to the data.

Choose a Cloud Firestore Data Structure:

For any app, we have to create archives and documents in the Cloud Firestore database. If it is not in both databases, Cloud Firestore creates it. Which are used to organize the structure and formulate queries. Documents may also contain a sub collection and nested objects that may contain strings, primitive fields, or data from some lists. The document is a light-weighted record that measures all values. Which identifies each document and we can treat the document as a JSON record. For this, you have a few different options. Let’s look at the benefits of each of its options.

=> Collection:

When a user signs into the Firebase platform, each user data must be saved in the archive and we save some basic information of the user, and the user unique ID is used as the key to the document. As one can create many documents in one collection. Collections are schema-less. When a document is in the same collection, those fields can contain and store different fields and different types of data.

Let us discuss some rules of collection.

  • A collection can only contain a document and not a collection of strings, binaries, or anything else.
  • The names of his documents are unique inside the collection.
  • No document can contain any other document but it can point to sub-collections.
  • When we create the first document, a collection already exists.
  • When all documents in the collection are deleted, the collection no longer exists.
//Colection
users
//Document 1
user1
first : "Mac"
last : "Anthony"
born : 1990//Document 2
user2
first : "Abdul"
last : "Ahamed"
born : 1987

=> Document:

In the Cloud Firestore, the storage unit is a document. A document is a type of light record that contains certain fields that map to all values ​​because it can recognize it by a single name. Can nest complex objects such as arrays or maps within documents. If we have a simple and definite list of data then it is even easier to set up and streamline our data structure. The document list also increases when the document list increases, which can slow down the document recovery time.

//Document
user1
first : "Mac"
last : "Anthony"
born : 1990

=> Subcollection:

In this scenario, the correct way to store a message is to use a sub-collection. A subcollection is a collection associated with specific documents. Documents reside in collections, which are very simple containers for documents. And we can create a subcollection for each document in our collection.

Let us discuss some rules of sub collection.

  • Subcollections allow us to structure data in a hierarchy, making it easier to access data.
  • Cannot reference collection and document in the collection.
  • We can also have sub-collections in documents in sub-collections, allowing us to nest the data more.
//Collection
Rooms
//Document 1
roomAname: "my chat room"
messages
//Sub-collection 1
message1
from : "Shubham"
msg : "Hello Shubham"
//Sub-collection 2
message2
from : "Mac"
msg : "Hello Mac"//Document 2
roomB
name: "my chat room two"
messages
//Sub-collection 1
message1
from : "Sam"
msg : "Hello Sam"
//Sub-collection 2
message2
from : "Mac"
msg : "Hello Mac"

=> Nested Data Document:

We can nest complex objects such as arrays or maps using a nested data document when we have a fixed list that we want to keep in our documents. Then it becomes easy to set up and streamline the data structure It is not scalable like other options. If the data grows over time then the document grows with an increasing list.

In any chat app, we can access the 3 most recently visited chat rooms of any user in their profile as a nested list. As given in a reference below

//Document
alovelace
name :
first : "Abdul"
last : "Samad"
born : 1990
rooms :
0 : "Software Chat"
1 : "Famous Figures"
2 : "Famous SWEs"

=> Root-level Collection:

To organize individual data sets into a root level collection, we create a root level collection for our database and provide a powerful query inside each collection for good engagement with the root level collection. Cloud Firestore Root Level Allows adding more than one collection. As the database grows, acquiring naturally hierarchical data can become more complex.

As mentioned below, in a context the chat app which has a collection of users name has two different documents inside it and a collection of rooms name that makes up the root level collection, inside it is a collection of messages named Message has different documents.

//Collection
users//Document
 alovelace
first : "Abdul"
last : "Samad"
born : 1815

//Document
sride
first : "Sally"
last : "Ride"
born : 1951//Another root level collection
rooms
//Document
software
//Sub-collection
messages
//Document
message1
from : "srastogi"
content : "..."
//Document
message2
from : "srastogi"
content : "..."

With the root tag collection, in the root level collection, each tag needs to store its message ID. This flips the direction of convenience pointers.

collection("tags").whereEqualTo("messageId", messageId)

Normalization & Denormalization:

It is a technique utilized in databases that are utilized to reduce information repetition and information contradiction from a table. This is the procedure where non-repetition and dependability information is put away in the set construction. When utilizing normalization the quantity of tables increments instead of diminishes.

{
"students": {
"students1": {
"name": "john thomas"
}
},
"attendance": {
"students1": {
"attendance1": {
"total": "20",
"absents": {
"leave1": "medical emergency",
"leave2": "not verified"
}
},
"attendance2": {
"total": "18",
"absents": {
"leave1": "sports game",
"leave2": "verified"
}
}
}
}
}

Denormalization isn’t simply identified with the Cloud Firestore, however, it is additionally an innovation regularly utilized in NoSQL databases and there is the contrary interaction of normalization, where changing summed up constructions over to a solitary pattern that contains repetitive data. It is the way toward taking a standardized information base and adjusting table designs to permit controlled excess for expanded data set execution. Endeavoring to improve execution is the solitary motivation to ever denormalize an information base.

This is the way toward enhancing the presentation of a NoSQL database, called redundancy, by adding repetitive information to other various areas in the database.

=> What are the Benefits & Advantages of Normalization:

Normalization gives various advantages and benefits to a firebase. A portion of the significant advantages incorporate the following :

  • > More prominent by and large database association.
  • > Decrease of repetitive information
  • > Better execution is ensured which can be associated with the above point. As data-bases become lesser in size, the goes through the data end up being faster and more restricted in this manner improving response time and speed.
  • > Smaller tables are possible as normalized tables will be changed and will have lesser fragments that consider more data records per page.
  • > A considerably more adaptable information database plan.
  • > A superior handle on database security.

=> When and Why to Use Denormalization:

As with almost anything, you ought to be sure why you need to apply denormalization.

  • > Maintaining history: Information can change over the long run, and we need to store esteems that were substantial when a record was made. What sort of changes do we mean? All things considered, an individual’s first and last name can change; a customer likewise can change their business name or some other information. We could tackle this issue by adding a table containing the historical backdrop of these changes. Around there, a select question returning the errand and a valid customer name would turn out to be more muddled.
  • > Improving query performance: A portion of the queries may utilize different tables to get to the information that we now and again need. Think about a circumstance where we’d need to join 10 tables to return the customer’s name and the items that were offered to them.
  • > Speeding up reporting: We need certain measurements often. Making them from live information is very tedious and can influence generally framework execution. Suppose that we need to follow customer deals over specific years for a few or all customers. Creating such reports out of lived information would “dig” nearly all through the entire database and back it off a ton.
  • > Computing commonly-needed values upfront: We need to have a few qualities prepared processed so we don’t need to produce them progressively.

=> What Are the Disadvantages of Denormalization?:

Clearly, the greatest benefit of the denormalization cycle is expanded execution.

  • > space: This is normal, as we’ll have copy information.
  • > Data anomalies: We must be exceptionally mindful of the way that information currently can be changed in more than one spot. We should change each piece of copy information as needs are. We can accomplish this by utilizing triggers, exchanges, and additional methods for all tasks that should be finished together.
  • > Documentation: We should appropriately archive each denormalization decision that we have applied. On the off chance that we change the information base plan later, we’ll need to take a gander at all our exemptions and contemplate them by and by. Perhaps we needn’t bother with them any longer since we’ve settled the issue. Or then again perhaps we need to add to existing denormalization rules.
  • > Slowing other operations: We can expect that we’ll slow down information insert, modification, and deletion operations. On the off chance that these activities happen generally seldom, this could be an advantage. Fundamentally, we would isolate one lethargic select into a bigger number of more slow insert/update/delete queries.
  • > More coding: Rules 2 and 3 will require extra coding, and yet they will improve on some select inquiries a ton. In case we’re denormalizing a current information base we’ll need to alter these select inquiries to get the advantages of our work. We’ll likewise need to refresh values in recently added credits for existing records.

Security In Firestore:

Cloud Firestore security is very important for an app or web. This security rule allows us to control access to documents and collections in your database. This rule allows you to create files that can be written from all the writing to the entire database and any Matches anything until operating on a specific document.

=> How to work security rules?

The Firestore security rule checks all requests in the database. It looks for requests that meet criteria that it does not meet, such as your database. It allows the same client to write data authenticated and unauthorized. If the user writes something in the database, it rejects it.

To see how the security rules look, we will open our database in the console. As soon as it opens, a rule appears at the top, then click on it and we will allow the read and write. As shown on the screen below.

=> Security rules Types:

The Basic security rules of firestore are two reads and write. But each of its rules can be broken into subtypes.

> Read Rules Types:

  • Get (Read single document).
  • List (Read queries & collection).

> Write Rules Types:

  • Create (Write to nonexistent documents)
  • Update (Write to existing documents)
  • Delete

=> Read Rules:

The Read Rule provides both access to and listing documents in grant collections. The permission rule in this allows the user to read a document, But it does not list all the documents. But the permission list allows the user to read the entire collection and query the collection gives.

=> Write Rules:

Cloud Firestore security rules include match details. Allow write rules to create and allow grant privileges so that the user can create, update and delete something. The entire request fails if writing is not allowed.

=> Testing Rules:

Cloud Firestore offers a rules simulator that you can use to test your rules. This is a very nice feature that provides a firestore. It allows authenticated and unauthorized read, write and delete operations. When you simulate an authenticated request, you can use it to test your rule.

Default Security Rules Declaration (Default-No Read and No Write):

// DefaultFirestore Service Declaration
service cloud.firestore {
// Database Declaration
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}

Security Rules Declaration (Read-Only and Write Only):

// Cloud Firestore Service Declaration
service cloud.firestore {
// Database Declaration
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if false;
}
}
}

After that we publish it and Firestore provides a good facility to check our rules so that we can test our rules

Let’s understand these rules by breaking them line by line.

  • > service cloud. firestore — It defines the service, in which case it is the cloud.firestore.
  • > match /databases/{database}/documents —It defines the database. This database clause indicates this rule applies to all Firestore project databases.
  • > match /uploads/{document=**} —Creates a new rule block to apply to the uploaded archive and all documents contained in it.
  • > allow read: — It allows the public to read access.
  • > allow write: — allow public write access

Conclusion:

In the article, I have explained the structure of the Firebase Data Modeling Tips; you can modify this code according to your choice. This was a small introduction to Firebase Data Modeling Tips On User Interaction from my side.

I hope this blog will provide you with sufficient information in Trying up the Firebase Data Modeling Tips in your project. We showed you what the Firebase Data Modeling Tips is and how it is stored in documents and collections, So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Semantics Widgets In Flutter

0

At the point when Flutter Mobile application hot reloads each time Flutter renders tree it likewise widgets tree, it additionally keeps a subsequent tree, called Semantics Tree which is utilized by the Mobile Device assistive innovation. Every hub of this Semantics tree is a SemanticsNode which may compare to one or a gathering of Widgets.

Hello friends, I will talk about my new blog on Semantics Widget In Flutter. We will also implement a demo of the Semantics Widget, and describes its properties, and how to use them in your flutter applications. So let’s get started.


Table of Contents :

Flutter

Semantics Widget

Attributes

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time ,Flutter offers great developer tools, with amazing hot reload”

Semantics Widget :

Semantics is a widget that annotates the widget tree with a description of the meaning of the widgets. It is used by accessibility tools, search engines, and other semantic analysis software to determine the meaning of the application.

For more info on Sematics Widget,Watch this video By Flutter :

Attributes :

Semantic components contain many functions, Here I introduce some important attributes:

  • label: Provide a text description of the Widget. That is the basic semantic information.
  • container: Whether this node introduces a new semantic node (SemanticsNode) in the semantic tree. It can not be separated or merged by upper layer semantics, that is, independent.
  • explicitChildNodes: The default is false, indicating whether to force the display of the semantic information of the child widget. It can be understood as split semantics.
  • scopesRoute: If it is not empty, whether the node corresponds to the root of the subtree, the subtree should declare the route name. Usually withexplicitChildNodesSet it to true together, and use it in routing jumps, such as page jumps,DialogBottomSheetPopupMenuThe pop-up part.

Code Implementation :

You need to implement it in your code respectively:

Create a new dart file called semantics_widget_demo.dart inside the libfolder.

In the below snippets, we will add the Semantics method. Inside the method, we will add a ClipOval widget. In this widget, we will add the CircleAvatar widget with maxRadius is 70 and add CachedNetworkImage. Let’s understand it with the help of a reference.

Semantics(
child:ClipOval(
child:CircleAvatar(
maxRadius:70,
child: CachedNetworkImage(
imageUrl: 'https://picsum.photos/250?image=9', height:DeviceSize.height(context),
width:DeviceSize.width(context),fit:BoxFit.cover,
),
),
),
label:'Company logo',
),

=> MergeSemantics:

It is a widget that consolidations the semantics of its relatives. It will cause all the semantics of the subtree attached to this hub to be merged into one hub in the semantics tree. In some cases combining the semantics of certain widgets can bring about a more fitting semantics tree.

Utilizing MergeSemantics is straightforward. You just need to pass the widget the subtree to be converged as child a contention when considering MergeSemantics the constructor.

Let’s say if there’s an account details section in the app that displays the user’s email address, name, and company,

Here, by default the user has to tap on every widget to know what that is, but wouldn’t it be more helpful if the entire section is read to the user when they select it? Enter MergeSemantics. We can wrap the column widget with this widget and all the static data will be read one by one in one tap.

MergeSemantics(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ListTile(
leading: Icon(Icons.account_circle, semanticLabel: 'name'),
title: Text("John Doe", style: TextStyle(color: Colors.blue),),
onTap: () {},
),
ListTile(
leading: Icon(Icons.email, semanticLabel: 'email',),
title: Text("johndoe@test.com", style: TextStyle(color: Colors.blue),),
onTap: () {},
),
ListTile(
leading: Icon(Icons.business, semanticLabel: 'company name'),
title: Text("ABC Inc.", style: TextStyle(color: Colors.blue),),
onTap: () {},
),

],
),
),

Code File:

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_semantics_demo/themes/device_size.dart';

class SemanticsWidgetDemo extends StatefulWidget {
@override
_SemanticsWidgetDemoState createState() => _SemanticsWidgetDemoState();
}

class _SemanticsWidgetDemoState extends State<SemanticsWidgetDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Semantics Widget Demo'),
),
body: Container(
height: DeviceSize.height(context),
width: DeviceSize.width(context),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Text(
'Semantics Widget',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
),
SizedBox(
height: 20,
),
Semantics(
child: ClipOval(
child: CircleAvatar(
maxRadius: 70,
child: CachedNetworkImage(
imageUrl: 'https://picsum.photos/250?image=9',
height: DeviceSize.height(context),
width: DeviceSize.width(context),
fit: BoxFit.cover,
),
),
),
label: 'Company logo',
),
],
),
Column(
children: [
Text(
'MergeSemantics',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
),
SizedBox(
height: 20,
),
MergeSemantics(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ListTile(
leading:
Icon(Icons.account_circle, semanticLabel: 'name'),
title: Text(
"John Doe",
style: TextStyle(color: Colors.blue),
),
onTap: () {},
),
ListTile(
leading: Icon(
Icons.email,
semanticLabel: 'email',
),
title: Text(
"johndoe@test.com",
style: TextStyle(color: Colors.blue),
),
onTap: () {},
),
ListTile(
leading:
Icon(Icons.business, semanticLabel: 'company name'),
title: Text(
"ABC Inc.",
style: TextStyle(color: Colors.blue),
),
onTap: () {},
),
],
),
),
],
),
],
),
),
);
}
}

Conclusion:

In this article, I have explained a Semantics Widget in a flutter, which you can modify and experiment with according to your own, this little introduction was from the Semantics Widget demo from our side.

I hope this blog will provide you with sufficient information on Trying up the Semantics Widget in your flutter project. We showed you what the Semantics Widget is and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

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

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

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

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

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