Google search engine
Home Blog Page 57

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.

SQL Database Storage Using Sqlite In Flutter

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.

What’s New in Flutter 2.2 & Dart 2.13

0

Google I/O Company launched is Flutter 2.2, This app is a very reliable and demonstrable app to the planners and focuses on a lot of improvements. Flutter 2.2 also includes a well-developed process for displaying apps on operating systems like Linux, macOS, Windows, and so on. Updates are focused on improving bugs and speed. Many problems have been resolved in Floater such as web app providing background caching using a service worker.

Flutter is a bit version after the update. This latest update of Flutter polishes and optimizes iOS updates. If seen, the Flutter platform is one of the fastest-growing technology as found from the side of slash data that 45% of developers prefer to work on the Flutter platform. On other platforms, this flutter app development shows a lot of its popularity in the development industry. There have been many improvements in the technology of this cross-platform such as bug fix tolling updates etc.

In this blog, we will learn about Flutter 2.2 & Dart 2.13. We will also implement a demo and how to use them in your flutter applications. So let’s get started. so let’s get started.


Table Of Contents :

Flutter 2.2

Dart 2.13

Flutter Web Update

Flutter Platform Adaptive Apps

Flutter Material Icon

Automatic Starting Behavior

Improved Text Headling

Mouse cursor over text spans

Conclusion


Flutter 2.2:

This new update release of Flutter 2.2 includes some improvements such as new updates like Android iOS web with updates like icon updates, text handling and mouse cursor for scrollbar behavior, and TextSpan widgets. Support includes new updates such as.

It supports multiple platforms with a codebase. All these features of the update are stable, which are available for app production, all these we can use in the web app of Flutter. Using Flutter is also popular for people because by using it, we quickly create a new app.

Which displays the same size in the consolidation for all platforms like Android iOS web. Flutter is the best thing that has been built on the dart, which has got a new version of the dart. See below for the new update of the dart.

Dart 2.13:

Dart 2.13 prominence is significantly associated with the release of Flutter 2.2 as in this release Null Safety is its key productivity feature that helps us avoid all kinds of null errors including a class of bugs that are difficult to find is.

This release of Dart also has a variety of nicknames, which allows you to create a variety of nicknames in your works. Dart 2.13 also has a better performance than Dart Fuffy. It has new official images of Docker for Github.

In this, Dart supports native interoperability. This new update of Dart supports FFI arrays and its structure for packaging, this update of Dart has also improved the readability of the code. This release supports short and good names in any complex types. It allows renaming all classes in a non-breaking manner, allowing you to avoid long clumsy names in your classes.

Flutter 2.2 Web Update:

In this release of Flutter 2.2, improvements have been made to the web as well as it experiences mobile content on the web as we know that we can also run Android, iOS, and web from the same Kodebase in earlier versions of Flutter Web. The service worker used to download the app update in the background for the user to access the old version when the app was downloaded.

After that, the user could not see his change until the browser refreshed the page twice but in Flutter 2.2 the service worker detects the change and the user will wait for the app to be updated to use as Web performance has been further improved to top zero security in the Flutter web update. In this web performance platform, HTML, Canvas has also been improved.

This Flutter update has also supported the font features which we can apply from the font feature set, we have used canvas and PPI to implement it so that it appears in the right place to hover. The update to Flutter 2.2 also added support for shader masque and computeLineMetrix, looking at the similarity gaps between the web and the app.

Once the user enables accessibility, it creates a Dom tree similar to the RenderObject DOM and the Aira translates between semantic properties. In this update, there has been some change in the position of the semantic node to close the transform gap between the mobile and the app.

For new web applications of flutter, Layout Explorer now supports the latest version of the version DevTools.

=> For Example:

In the Flutter 2.2 update version, I have created a design for the web in which I have taken an image and text which we have managed both from the column widget, after which we select the select device web chrome and then we run the project when we run When the project is built, a browser opens, in which we see that the design we have created displays the web browser as given in an image above. And below is the reference of the code.

Scaffold(
appBar:AppBar(
title:Text('Flutter Demo'),
),
body:Center(
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:CrossAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/images/logo.png', height:200.0,
fit: BoxFit.scaleDown,), SizedBox(
height:30,
), Text('Welcome To Flutter',style:TextStyle(color:Colors.black,fontSize:18),),
],
),
),
);

Demo Module:

=> Incremental installation and page iOS transition:

After the new release of Flutter 2.2, this flutter has made iOS Cuopartino’s transition much faster and much easier than the previous version, with the flutter animations reducing frame rendering by up to 75%.In this we do not seek the ultimate improvement of the performance of the user, we are looking for the performance of the development, while the development process is growing more incremental iOS installs that provide flutter updates, reduces the time it takes to install the updated version of your iOS application by up to 40%,

Flutter Platform Adaptive Apps:

Flutter is meant to have a customized design for each platform, it supports the same size across all platforms such as mobile, tablet, and desktop in the same code, it allows for different input types (touch vs mouse + keyboard) and Different platform navigation is an app that adjusts its size to different types of devices, this is what we call the app as customized apps.

Platform adaptive apps include model overlays on desktops and sheets on mobile that reflect users’ expectations and allow for easily adaptive and responsive UI on all platforms, such as mobile, with maximum usability pulsing to layout and navigation flow.

It recommends the Folio app on gSkinner Flokk and Flutter platform. You can download Flokk and Folio directly from the App Store or run them directly on the browser.

UX part of Flutter’s customized app for the large screen using which the app is optimized and based on all types of devices. Under the guidance of the material team, the main feature is based on all the big screens, using many layouts as well as updates and updates design kit of many components.

Flutter Material Icons:

The new release of Flutter has added a new icon to Flutter. It has two different PRs adding new icon material. It also includes an icon for the dash itself. This update of Flutter has more than 7000 material icons. You can search for icons by category or name using fonts.google.com/icons. link.

Once you find the right icon, then the new flutter tab tells us how to use it. Either app can download icons to use stand-alone assets as previously it was not so easy to add a dash to an app.

Automatic Scrolling Behavior:

In this Flutter 2.2 latest update version, we see what is the automatic behavior of any design when we scroll Seeing the behavior, both Android and iOS are the same, yet it does not show the same in the default. When we talk about the desktop app, we automatically see its scrollbar when the item is larger than the size. To be shown automatically, we have to add the scrollbar parent widget. This release adds automatic scrollbars to mobile and desktop.

When we run the list on the desktop using Scrolling Behavior:

We see that a scrollbar appears on the side which we can scroll up and down while scrolling, our list is also scrolled. If we do not want to show a scrollbar in our list then we can set its scrollbar theme. You can see the new default scrollbar Behavior and code information, check out docs on flutter. dev.

=> For Example:

As I used the Scrolling Behavior List in a demo in which we took a ListView.builder and wrapped it with ScrollConfiguration, then later in ListViewBuilder we used the ListTile widget which has some icons and text when we run it on the web. Then a scrollbar appears as you can see in the image above. And below is the reference of the code.

ScrollConfiguration(
// behavior: MyCustomScrollBehavior(),
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: true),
child: ListView.builder(
controller: controller,
itemCount:50,
itemBuilder: (BuildContext context, int index) {
//return Text('Item $index');
return ListTile(
leading: Icon(Icons.list),
trailing: Icon(Icons.more_vert),
title:Text("List item No $index")
);
}
),
),

Demo Module:

Improved Text Handling:

As we see, the flutter has improved on every platform like the mobile form factor it is not as important on the mobile compared to the desktop form factor. In this flutter update, we see that it also handles text input such as via widget keystrokes. Features such as eliminate from and enable it to be fully customizable with text actions. You use it to handle any keystrokes.

An example of this is that you can make a tab between TextField and the Flutter app in Flutter.

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Flutter Text Editing Fun',
home: HomePage(),
);
}

class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
body: Column(
children: [
TextField(),
OutlinedButton(onPressed: () {}, child: const Text('Press Me')),
],
),
);
}

Mouse Cursor Over Text Spans:

Previously, when we moved the mouse over any text on the web when you mouse over the cursor over the arrow, the arrow cursor would appear, but you would move the cursor over any given linkless text like a hand. The cursor appears as soon as we click on it, then the link given to it opens on the web, we can go to its web, which we can do differently and differently.

=> For Example:

As you can see in the image above, two different colors are a line of text which we have done with RichText() which has two TextSpan(). One TextSpan is text in, we have defined the URL of the web with the help of urlLauncher library. And below is the reference of the code.

Scaffold(
appBar: AppBar(title: Text('Mouse Cursor Over Text Spans')),
body:Padding(
padding:EdgeInsets.all(20),
child:Center(
child: RichText(
text: TextSpan(
style: TextStyle(fontSize: 48),
children: [
TextSpan(
text: 'This is rcihtext widget line, ',
style: TextStyle(color: Colors.black),
),
TextSpan(
text: 'this line is',
style: TextStyle(color: Colors.red),
recognizer: TapGestureRecognizer()
..onTap = () {
urlLauncher.launch('https://flutter.dev');
},
),
],
),
),
),
),

Demo Module:

Conclusion:

In the article, I have explained What’s new in Flutter 2.2 & Dart 2.13. This was a small introduction to Flutter 2.2 & Dart 2.13 On User Interaction from my side.

I hope this blog will provide you with sufficient information in Trying up the What’s new in Flutter 2.2 & Dart 2.13 in your project. In this, we have told you what is new in the new update of Flutter 2.2 and how it works on the web app, 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.

Pagination using GetX in Flutter

Hello flutter developer, In this blog, we shall discuss how we can use GetX the package for managing the state of pagination. Pagination is also known as paging, is the process of dividing a document into discrete pages. Today in most of the apps we see this feature. It helps in improving the performance of the app. Through pagination we can reduce the read request to our database, hence it reduces the cost of database maintenance. It is a user-friendly feature, interested users can scroll more and more if they deliberately want to load more data.

In this blog, we shall learn how we can implement pagination using GetX the package. We will build an app that will display a fixed number of items and on scrolling more data will be loaded and displayed on the screen in real-time.



Table of contents:

Introduction to GetX

Installing Getx in Flutter project

Pagination Using GetX

Creating a model class

Creating GetxController

Initialize the required objects

Generating initial list

Creating a method executed every time the scroll limit exceeds its limit

Initializing onInit() method

Initializing HomePageController object

Using GetBuilder


Introduction to GetX:

GetX is a state management helper package.

  • It provides us a powerful and reactive state management technique, route management, and dependency Injection.
  • PRODUCTIVITY, PERFORMANCE, AND ORGANIZATION are the three basic principal of the package.
  • It eliminates the dependency on the widget tree.
  • For routing, GetX does not need the context for navigation.
  • Automatically reduce the memory consumption when the resources are not used by default.
  • GetX uses its own dependency injection feature.
  • Simple syntax.

Installing Getx in Flutter project:

get | Flutter Package
Languages: English (this file), Indonesian, Urdu, Chinese, Brazilian Portuguese, Spanish, Russian, Polish, Korean…pub. dev

Add Get to your pubspec.yaml file:

dependencies:
get: ^4.1.4

Import get in files that it will be used:

import 'package:get/get.dart';

Pagination Using GetX:

GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
)

GetMaterialApp is a widget that is a substitute for MaterialApp. Using this widget is not compulsory if you are using the GetX package only for state management, but if you are using GetX for routing then we need to use GetMaterialApp widget.

What do we want?

We want to build an app that displays a list of items and every time the screen scroll it should automatically add some items to the existing list and update the UI in real-time.

Creating a model class:

We have created a very simple model class that has a name property.

class Model {
String name;

Model({
this.name,
});
}

Creating GetxController:

GetxController is a class in which we write all our business logic, variables, and methods used for managing the state of the app screen.

  • It automatically disposes of all the controllers when the screen is popped out of the stack.
  • All the processing logic will be written inside this controller.
  • Like initState() and dispose() method GetX provides us onInit() and onClose() .
  • onReady() is called after the widget is rendered on screen.
  • update() rebuilds the GetBuilder associated with the GetxController. It is similar to notifyListeners() in providers.
  • onInit(): called after the widget is allocated memory.
  • onClose() called just before the controller is deleted from memory.
class HomePageController extends GetxController {
}

We can create a GetxController by extending the class with GetxController like above.

Initialize the required objects:

We need ScrollController to listen to the scrolling of the screen.

list is a list of Models that will be used to map it with the list of widgets.

class HomePageController extends GetxController {
List<Model> list = [];
ScrollController controller = ScrollController();
int listLength = 6;
}

Generating initial list:

Here we have generated a list of Model that we will initially display on the screen. List.generate() takes an integer and function with an integer value. It will add Model for each index in the list.

generateList() {
list = List.generate(
listLength, (index) => Model(name: (index + 1).toString()));
}

Creating a method executed every time the scroll limit exceeds its limit:

This method will be executed every time the scroll limit exceeds its limit.

To measure the scroll limit we use the ScrollController . maxScrollExtent is the number of max pixels and pixels notify when the listener when the pixel changes. controller.position.maxScrollExtent == controller.position.pixels this condition will only return true when the scrolling is max.

addItems() async {
controller.addListener(() {
if (controller.position.maxScrollExtent == controller.position.pixels) {
for (int i = 0; i < 2; i++) {
listLength++;
list.add(Model(name: (listLength).toString()));
update(); //update GetBuilder each time
}
}
});
}

Initializing onInit() method:

This method is called before the widget build.

void onInit() {
generateList();
addItems();
super.onInit();
}

Initializing HomePageController object:

Initialize the HomePageController object in the class where you want to implement the pagination.

Get.put() makes the object available to the child of the widgets and using Get.find() we can find the same object in other classes as well.

HomePageController homePageController = Get.put(HomePageController());

Using GetBuilder:

GetBuilder is rebuilt every time the update() the method is called. It takes the init controller. It takes a builder that returns a Widget. The methods and objects can be accessed using the value . We use the ListView.builder to display the list of widgets. Controller of ListView.builder will be the ScrollController .

GetBuilder(
init: homePageController,
builder: (value) => ListView.builder(
controller: value.controller,
itemCount: value.list.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
color: Colors.red,
height: 100,
child: Center(
child: Text(value.list[index].name),
),
),
);
},
),
),

You might be thinking that here we do not need the GetBuilder as the method of homePageController can be accessed without it as well, yes it is true but in this case, the UI will not be updated, the 2 Model will be added into the list an object that we have created in the HomePageController using the addItems() method. To change the UI we need to use GitBuilder if we are using get for state management as it is rebuilt every time the update() the method is called.

main. dart:

https://gist.github.com/anmolgupta-aeologic/2f1367ce273685b9d76a9553b9722797

homepage_controller.dart:

https://gist.github.com/anmolgupta-aeologic/bb35406fedeeb5ba018d3d7fda1e389e


🌸🌼🌸 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!.

JavaScript In Flutter Web

0

Introduction: 

Flutter, renowned for its expedited development and aesthetically pleasing user interfaces, has been gaining traction among developers for crafting cross-platform applications. With the advent of Flutter Web, developers can now extend their existing Flutter expertise to target web browsers as well. A pivotal aspect of Flutter Web development is JavaScript integration, which facilitates interaction between developers’ applications and the underlying web platform. In this blog, we’ll delve into the realm of JavaScript integration in Flutter Web, exploring its significance, applications, pros and cons, limitations, future scope, best practices, and more.

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


Table of Contents

Introduction 
Understanding Flutter Web Flutter:
Leveraging JavaScript in Flutter Web
Introduction to JavaScript Integration
Demo: Retrieving User’s Location
JavaScript Functions

Showcasing with a Live Demo
Limitations and Future Scope
Conclusion
References


 Understanding Flutter Web Flutter:

 Google’s UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase, has garnered widespread acclaim. Flutter Web extends Flutter’s capabilities to target modern web browsers, empowering developers to create interactive web applications with the same codebase they use for mobile and desktop platforms. Equipped with Flutter’s declarative UI framework and hot reload feature, developers can craft web applications with stellar performance and rapid development cycles.

 Pros:

  • Enables access to browser APIs and third-party JavaScript libraries.
  • Facilitates seamless integration of existing web technologies.
  • Enhances the functionality and interactivity of Flutter Web applications.

Cons:

  • Introduces complexity and potential errors when interacting with JavaScript code.
  • May increase application size and affect performance if not optimized properly.
  • Requires understanding of both Dart and JavaScript languages for effective integration.

Leveraging JavaScript in Flutter Web

Using JavaScript in Flutter Web allows developers to leverage existing web technologies and libraries while building web applications with Flutter. Here are some reasons why integrating JavaScript into Flutter web can be beneficial:

  1. Access to Web APIs: JavaScript provides access to a wide range of web APIs and browser functionalities that may not be directly available in Flutter. By integrating JavaScript, developers can tap into these APIs and leverage features such as geolocation, device orientation, and more.
  2. Third-Party Libraries: Many third-party libraries and frameworks are written in JavaScript and designed for web development. Integrating JavaScript in Flutter web allows developers to use these libraries seamlessly within their Flutter applications, expanding the range of available tools and resources.
  3. Web-specific Functionality: Certain web-specific functionality, such as interacting with the browser’s Document Object Model (DOM) or handling events like mouse clicks and keyboard input, can be more efficiently implemented using JavaScript. Integrating JavaScript in Flutter web enables developers to handle these tasks effectively.
  4. Hybrid Development: In some cases, developers may want to build hybrid applications that combine Flutter components with existing web content or JavaScript-based frameworks like React or Angular. Integrating JavaScript in Flutter web facilitates the creation of hybrid applications that leverage the strengths of both Flutter and web technologies.
  5. Legacy Code Integration: For projects that involve migrating or integrating with existing web applications or codebases, using JavaScript in Flutter web can streamline the integration process and ensure compatibility with legacy systems.

Overall, integrating JavaScript in Flutter web opens up new possibilities for building feature-rich, interactive web applications that leverage the strengths of both Flutter and web technologies.


Introduction to JavaScript Integration

JavaScript integration serves as a cornerstone in Flutter Web development, facilitating seamless communication between Flutter code and the underlying web platform. By harnessing JavaScript interop, developers can access browser APIs, incorporate third-party JavaScript libraries, and execute other web-specific tasks from within their Flutter applications. In Flutter, JavaScript interop is realized through the dart:js library, which establishes a bridge between Dart and JavaScript environments.

import 'dart:js' as js;void main() {
js.context.callMethod('console.log', ['Hello from Dart!']);
}

Use Cases for JavaScript Integration

JavaScript integration in Flutter Web unlocks a myriad of possibilities for developers. Common applications include accessing browser APIs like geolocation or local storage, integrating third-party JavaScript libraries for enhanced functionality, and interfacing with web services via JavaScript functions. By seamlessly integrating JavaScript code into their Flutter applications, developers can leverage existing web technologies to enrich the user experience.

dartCopy code// Example of accessing browser's geolocation API using JavaScript interop
void getCurrentLocation() {
var position = js.context.callMethod('getCurrentPosition', []);
// Process position data
}

 Interfacing with JavaScript Code 

Interfacing with JavaScript code in Flutter Web entails invoking JavaScript functions from Dart and vice versa. With dart:js, developers can invoke JavaScript functions and exchange data between Dart and JavaScript environments. This bidirectional communication empowers developers to seamlessly integrate JavaScript functionalities into Flutter applications, thereby harnessing the full potential of the web platform.

dartCopy code// Example of invoking a JavaScript function from Dart code
void callJavaScriptFunction() {
js.context.callMethod('myJavaScriptFunction', ['argument']);
}

Integrating Third-Party JavaScript Libraries 

Flutter Web developers can tap into the expansive ecosystem of third-party JavaScript libraries to augment their applications. Integration of these libraries into Flutter projects is facilitated through JavaScript interop. Whether it involves data visualization with Chart.js or DOM manipulation with jQuery, developers can seamlessly incorporate popular JavaScript libraries into their Flutter Web applications and leverage their robust features.


Demo: Retrieving User’s Location 

To demonstrate JavaScript integration in Flutter Web, let’s create a simple application that retrieves the user’s location using JavaScript’s geolocation API:

To get geolocation using JavaScript in Flutter Web, we can use the Geolocation API provided by modern web browsers. Here’s a step-by-step guide:

Step 1: Import dart:js Libraryi

mport 'dart:js' as js;

Step 2: Call JavaScript Geolocation API

void getLocation() {
if (js.context.hasProperty('navigator') &&
js.context['navigator'].hasProperty('geolocation')) {
js.context.callMethod('navigator.geolocation.getCurrentPosition',
[showPosition, showError]);
} else {
print('Geolocation is not supported by this browser.');
}
}

Step 3: Define Callback Functions

void showPosition(js.JsObject position) {
double latitude = position['coords']['latitude'];
double longitude = position['coords']['longitude'];
print('Latitude: $latitude, Longitude: $longitude');
}void showError(js.JsObject error) {
String errorMessage;
switch (error['code']) {
case 1:
errorMessage = 'Permission denied.';
break;
case 2:
errorMessage = 'Position unavailable.';
break;
case 3:
errorMessage = 'Timeout.';
break;
default:
errorMessage = 'Unknown error.';
break;
}
print('Error: $errorMessage');
}

Step 4: Trigger Geolocation Retrieval

You can trigger the getLocation function when the user interacts with a button or at any appropriate event in your Flutter web application.

ElevatedButton(
onPressed: getLocation,
child: Text('Get Location'),
)

Keep In Mind:

  • Dependency on the user’s device and browser settings.
  • Limited support in some older browsers or in environments where geolocation services are restricted.
  • Geolocation accuracy may vary based on factors such as device capabilities, network conditions, and user consent.
  • Privacy concerns may arise due to the collection of location data from users.

JavaScript Functions

Flutter Web provides developers with the capability to seamlessly integrate custom JavaScript functions into their applications, thereby extending the functionality and interactivity of their web experiences. Let’s explore some JavaScript functions that can be effectively integrated into Flutter Web applications.

 1. getPlatform(): This function leverages JavaScript’s navigator.platform to retrieve essential platform information. By accessing the user’s device platform, developers can tailor their application’s behavior to provide a more personalized experience. For example, they can adjust layout, content, or feature availability based on whether the user is on a desktop, mobile device, or tablet.

function getPlatform() {
return navigator.platform;
}

Usage Scenario: Adapting UI layout and feature availability based on whether the user is on a desktop, mobile device, or tablet.

2. jsPromiseFunction(message): Demonstrating the usage of JavaScript promises within Flutter Web, this function showcases the power of asynchronous programming. Promises enable developers to handle asynchronous operations more efficiently, such as fetching data from a server or executing time-consuming tasks. By integrating JavaScript promises into Flutter Web applications, developers can ensure smooth and responsive user interactions, even when dealing with complex asynchronous tasks.

async function jsPromiseFunction(message) {
let promise = new Promise(function(resolve, reject) {
resolve('Hello : ' + message);
});
let result = await promise;
return result;
}

Usage Scenario: Fetching data from a server or executing complex tasks asynchronously while maintaining app responsiveness.

 3. jsOpenTabFunction(url): By employing this function, developers can enhance user navigation within their Flutter Web applications. It opens a new browser tab with the specified URL and resolves a promise when the tab is closed. This functionality is particularly useful for scenarios where users need to interact with external content or perform tasks in parallel without disrupting their current workflow. For instance, developers can implement features like opening documentation pages, external links, or multimedia content in separate tabs, providing users with a seamless browsing experience.

async function jsOpenTabFunction(url) {
let promise = new Promise(function(resolve, reject) {
var win = window.open(url, "New Popup Window", "width=800,height=800");
var timer = setInterval(function() {
if (win.closed) {
clearInterval(timer);
resolve('Closed');
}
}, 300);
});
let result = await promise;
return result;
}

Usage Scenario: Opening external links, documentation pages, or multimedia content in separate tabs without interrupting the user’s workflow.

Integrating these JavaScript functions into Flutter Web applications empowers developers to leverage the full potential of web technologies and browser capabilities. Whether it’s accessing device-specific information, handling asynchronous tasks, or enhancing navigation, JavaScript integration opens up a world of possibilities for crafting rich and immersive web experiences with Flutter.

import 'package:flutter/material.dart';
import 'package:js_flutter_web/js/js_helper.dart';
import 'dart:js' as js;
void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

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

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
final JSHelper _jsHelper = JSHelper();

String platForm = '';
String dataFromJS = '';
String locationMessage = '';

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
backgroundColor: Colors.red.shade400,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade400,
),
child: const Text(
"Click to Check Platform",
style: TextStyle(color: Colors.white),
),
onPressed: () {
getPlatform();
},
),
const SizedBox(height: 16),
if (platForm.isNotEmpty) ...[
Text(
'Current Platform is : $platForm',
style: const TextStyle(
fontSize: 20, color: Colors.deepOrangeAccent),
),
const SizedBox(height: 16),
],
const SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade400,
),
child: const Text(
"Explore Flutter",
style: TextStyle(color: Colors.white),
),
onPressed: () async {
// Loader
String dataFromJS = await _jsHelper.callOpenTab();
print("callDataFromJS ----------- $dataFromJS");
},
),
const SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade400,
),
child: const Text(
"Call JS Promise Function",
style: TextStyle(color: Colors.white),
),
onPressed: () async {
setState(() {});
dataFromJS = await _jsHelper.callJSPromise();
print("dataFromJS ----------- $dataFromJS");
},
),
const SizedBox(height: 16),
Text(
dataFromJS.toString(),
style:
const TextStyle(fontSize: 20, color: Colors.deepOrangeAccent),
),
const SizedBox(height: 20),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade400,
),
onPressed: getLocation,
child: const Text('Get Location'),
),
const SizedBox(height: 16),
Text(
locationMessage,
style:
const TextStyle(fontSize: 20, color: Colors.deepOrangeAccent),
),
],
),
),
);
}

void getPlatform() {
setState(() {});
platForm = _jsHelper.getPlatformFromJS();
print(platForm);
}

void getLocation() {
if (js.context.hasProperty('navigator') &&
js.context['navigator'].hasProperty('geolocation') &&
js.context['navigator']['geolocation']
.hasProperty('getCurrentPosition')) {
js.context['navigator']['geolocation']
.callMethod('getCurrentPosition', [showPosition, showError]);
} else {
setState(() {
locationMessage = 'Geolocation is not supported by this browser.';
});
}
}

void showPosition(js.JsObject position) {
double latitude = position['coords']['latitude'];
double longitude = position['coords']['longitude'];
setState(() {
locationMessage = 'Latitude: $latitude, Longitude: $longitude';
});
}

void showError(js.JsObject error) {
String errorMessage;
switch (error['code']) {
case 1:
errorMessage = 'Permission denied.';
break;
case 2:
errorMessage = 'Position unavailable.';
break;
case 3:
errorMessage = 'Timeout.';
break;
default:
errorMessage = 'Unknown error.';
break;
}
setState(() {
locationMessage = 'Error: $errorMessage';
});
}
}


Showcasing with a Live Demo


Limitations and Future Scope:

While JavaScript integration in Flutter Web offers numerous benefits, it also comes with certain limitations. These include potential compatibility issues with future Flutter versions, overhead associated with maintaining JavaScript interoperability, and limitations in accessing certain browser APIs directly from Dart code. However, with ongoing improvements in Flutter Web and Dart language features, these limitations are expected to diminish over time. Additionally, the future scope of JavaScript integration in Flutter Web holds promise for further enhancing web application development, with potential advancements in performance optimization, tooling support, and expanded JavaScript interoperability.


Conclusion:

 JavaScript integration plays a pivotal role in Flutter Web development, empowering developers to harness the capabilities of the web platform within their Flutter applications. By comprehending the fundamentals of JavaScript interop and exploring its applications, developers can craft resilient and feature-rich web applications with Flutter. As Flutter Web continues to evolve, JavaScript integration will remain instrumental, enabling developers to create immersive and captivating user experiences on the web.


References:

  • Official Flutter Documentation: Flutter Web
  • Dart Documentation: JavaScript Interop

In this blog, we’ve delved into the intricacies of JavaScript integration in Flutter Web, from its significance and applications to pros and cons, limitations, future scope, best practices, and more. Armed with this knowledge, developers can confidently explore and leverage JavaScript integration to craft innovative web applications with Flutter.

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