Google search engine
Home Blog Page 15

Explore Flutter Bloc 8.0.1 Design Pattern In Flutter

0

State Management in Flutter has been a hot topic since Flutter hit the mobile development scene. Apps are built on state, and using no state-management solution is tough to scale and tougher to test. Flutter is a comparatively new cross-platform software development framework with an incredible amount of high-quality, well-supported open-sourced packages released during its short lifespan.

One area of Flutter that these packages support state management, and BLoC is one of the most seasoned types of state the executives inside Flutter, initially delivered to the general public towards the finish of 2019.

Flutter Bloc 8.0.1 Design Pattern is the new form of the bloc pattern.
This rendition has a few enhancements from the past version. Over version 7 flutter bloc pattern turned out to be exceptionally powerful.

In this blog, we will Explore Flutter Bloc 8.0.1 Design Pattern In Flutter. We will see how to implement a demo program of the flutter bloc and how to use the Flutter Bloc 8.0.1 Design Pattern using the flutter_bloc package in your flutter applications.

flutter_bloc | Flutter Package
Widgets that make it easy to integrate blocs and cubits into Flutter. Built to work with package: bloc. Learn more at…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

Flutter bloc 8.0.1 design pattern gives a superior method for dealing with the states utilizing events. This design pattern assists with isolating the show from business logic. Following the Bloc pattern works with testability and reusability. This package abstracts receptive parts of the pattern permitting developers to zero in on composing the business logic.

Flutter Bloc was the primary state management answer for getting steam (Provider was additionally up there as well, credit where it is expected) — yet like all MVPs, version 1.0 was a little harsh around the edges. With more than 7 versions, Bloc turned out to be endlessly better until it turned into the superb environment of state management arrangements: highlight rich, simple to test, and advanced adaptable architecture.

Demo Module :

The above demo video shows how to implement the Flutter bloc 8.0.1 design pattern and shows how the Flutter bloc 8.0 design pattern will work using the flutter_bloc package in your flutter applications. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
flutter_bloc:

Step 2: Import

import 'package:flutter_bloc/flutter_bloc.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

Fluter bloc 8.0 acquaints the event handler with dealing with the states. Here we are utilizing the counter update project utilizing the bloc 8.0 pattern.

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

We will create an IncrementEvent class. In this class, we will extend CounterEvent for performing the increment operation.

abstract class CounterEvent {}

class IncrementEvent extends CounterEvent {

}

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

We will make a CounterValueState class. In this class, we will extend CounterState for the counter, and on the increment event, we will produce the CounterValueState.

abstract class CounterState {
int? counter;
}
class CounterValueState extends CounterState {
final int counter;

CounterValueState(this.counter);

}

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

Presently, we will make the CounterBloc class and add the counter-event with the mapEventToState function. Then, at that point, produce the state according to the event.

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_design_patterrn_demo/counter_event.dart';
import 'package:flutter_bloc_design_patterrn_demo/counter_state.dart';

class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterValueState(0)) {

on<CounterEvent>(mapEventToState);
}
@override
void mapEventToState(
CounterEvent event, Emitter<CounterState> emit) async {
if (event is IncrementEvent) {
emit(CounterValueState(state.counter! + 1));
}
}
}

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

In the main. dart file, we will create a new class CounterBlocDemo. In this class, first, we will create a CounterBloc variable was a bloc.

CounterBloc? bloc;

Now, we will create an initState() method. In this method, we will add a bloc that is equal to the BlocProvider. of<CounterBloc>(context).

@override
void initState() {
bloc = BlocProvider.of<CounterBloc>(context);
super.initState();
}

Now, we will use the bloc builder widget for state updates according to the event. In the builder. we will add if currentState is CounterValueState then return a Center widget. In this widget, we will add the Column widget with the mainAxisAlignment as the center. We will add simple text and the currentState.counter.toString() for show update value on our screen.

BlocBuilder<CounterBloc, CounterState>(
builder: (context, currentState) {
if (currentState is CounterValueState) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
style:TextStyle(fontSize: 18),
),
const SizedBox(height: 10,),
Text(
currentState.counter.toString(),
style:const TextStyle(color: Colors.blueGrey,fontSize: 30),
),
],
),
);
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text(
'You have pushed the button this many times:',
),
SizedBox(height: 10,),
Text(
"0",
style:TextStyle(color: Colors.blueGrey,fontSize: 30),
),
],
),
);
},
),

Else, it will show the return Center widget. Inside the widget, we will add a Column widget with text. When the user runs a code then, first show this part, and when they will tap on the button then, show the current state part with the update counter with the help of the bloc builder widget.

Now, we will make a FloatingActionButton. In this button, we will add backgroundColor was pinkAccent, the tooltip was increment, add an icon on it a child, and onPressed function. In this function, we will add bloc?.add(IncrementEvent()). When the user presses the button then, the counter value will be increasing.

floatingActionButton: FloatingActionButton(
backgroundColor: Colors.pinkAccent,
onPressed: () {
bloc?.add(IncrementEvent());
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_design_patterrn_demo/counter_bloc.dart';
import 'package:flutter_bloc_design_patterrn_demo/counter_event.dart';
import 'package:flutter_bloc_design_patterrn_demo/counter_state.dart';
import 'package:flutter_bloc_design_patterrn_demo/splash_screen.dart';

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return BlocProvider<CounterBloc>(
create: (context) => CounterBloc(),
child: const MaterialApp(
home: Splash(),
debugShowCheckedModeBanner: false,
));
}
}

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

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

class _CounterBlocDemoState extends State<CounterBlocDemo> {
CounterBloc? bloc;

@override
void initState() {
bloc = BlocProvider.of<CounterBloc>(context);
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.pinkAccent,
title: const Text("Flutter Bloc 8.0.1 Design Pattern"),
centerTitle: true,
automaticallyImplyLeading: false,
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.pinkAccent,
onPressed: () {
bloc?.add(IncrementEvent());
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
'assets/logo.png',
height: 150,
),
const SizedBox(height: 40,),
BlocBuilder<CounterBloc, CounterState>(
builder: (context, currentState) {
if (currentState is CounterValueState) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
style:TextStyle(fontSize: 18),
),
const SizedBox(height: 10,),
Text(
currentState.counter.toString(),
style:const TextStyle(color: Colors.blueGrey,fontSize: 30),
),
],
),
);
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text(
'You have pushed the button this many times:',
),
SizedBox(height: 10,),
Text(
"0",
style:TextStyle(color: Colors.blueGrey,fontSize: 30),
),
],
),
);
},
),
],
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Flutter Bloc 8.0.1 Design Pattern in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working with Flutter Bloc 8.0.1 Design Pattern will work using the flutter_bloc package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Animate Dialogs In Flutter

0

Flutter offers extraordinary help for animations. Nonetheless, this isn’t true with Dialogs. The default animations in Flutter’s dialogs are straightforward and foreordained due to this we really want to do a ton of work to animate dialogs.

The dialog is a kind of widget that comes on the window or the screen which contains any basic data or can request any choice. At the point when a dialog put away is popped the wide range of various functions get disabled until you close the dialog box or give an answer. We utilize an animated dialog box for straightforward pop-up messages which are shown.

In this blog, we will explore the Animate Dialogs In Flutter. We will see how to implement an animate dialog demo program and we are going to learn how to animate dialogs without using any third-party package in your flutter applications.

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introduction:

A dialog resembles a popup window to give a few alternatives to users(options like acknowledging/decay). Basic Alert Dialog won’t be helpful for each necessity. We will animate dialog without using any third-party plugin.

Demo Module :

The above demo output shows how to animate dialogs in flutter and shows how to animate dialogs will work without using any third-party plugin in your flutter applications. We will show a user when clicking on the button and then, show animate dialogs on your screens. It will be shown on your device.

Constructor:

To utilize showGeneralDialog, you need to call the constructor underneath:

Future<T?> showGeneralDialog<T extends Object?>({
required BuildContext context,
required RoutePageBuilder pageBuilder,
bool barrierDismissible = false,
String? barrierLabel,
Color barrierColor = const Color(0x80000000),
Duration transitionDuration = const Duration(milliseconds: 200),
RouteTransitionsBuilder? transitionBuilder,
bool useRootNavigator = true,
RouteSettings? routeSettings,
Offset? anchorPoint,
})

All fields marked with @required must not be empty in the above Constructor.

Parameters:

There are some parameters of showGeneralDialog are:

  • > barrierDismissible: This parameter is used to define whether dialog may be dismissible or not
  • > barrierColor: This parameter is used for the Background color of dialog.
  • > transitionDuration: This parameter is used Duration of animation when the dialog appears and disappears. Also, used to determine how long it takes for the route to arrive on or leave off the screen. This argument defaults to 200 milliseconds.
  • > transitionBuilder: This parameter is used to define how the route arrives on and leaves off the screen. By default, the transition is a linear fade off the page’s contents.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the main. dart file, we will create a MyHomePage class. In this class, we will create two ElevatedButton. First, we will create a Rotate Dialog. We will create a button with style and add the text ‘Rotate Dialog’. Also, the onPressed function. In this function, we will add _rotateDialog() method. We will below define this method with the code.

SizedBox(
height: 45,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.teal,
),
onPressed: () => _rotateDialog(),
child: const Text('Rotate Dialog',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold))),
),

Now we will deeply define _rotateDialog() method:

In this method, we will add the showGeneralDialog() function. Inside the function, we will add context, pageBuilder, transitionBuilder, and transitionDuration. In transitionBuilder, we will return Transform.rotate() method. In this method, we will add angle and its child we will add the _dialog(ctx) widget method.

void _rotateDialog() {
showGeneralDialog(
context: context,
pageBuilder: (ctx, a1, a2) {
return Container();
},
transitionBuilder: (ctx, a1, a2, child) {
return Transform.rotate(
angle: math.radians(a1.value * 360),
child: _dialog(ctx),
);
},
transitionDuration: const Duration(milliseconds: 300),
);
}

In this _dialog() method. This method was common for rotate and scale dialog. This will return an AlertDialog() widget. In this widget, we will add title, content, and actions: <Widget>.

Widget _dialog(BuildContext context) {
return AlertDialog(
title: const Text("Flutter Dev's"),
content: const Text("FlutterDevs specializes in creating cost-effective "
"and efficient applications with our perfectly crafted, creative and "
"leading-edge flutter app development solutions for customers all around "
"the globe."),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
"Okay",
style: TextStyle(color: Colors.red, fontSize: 17),
))
],
);
}

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

Next, we will create a Scale Dialog. We will create a button with style and add the text ‘Scale Dialog’. Also, the onPressed function. In this function, we will add _scaleDialog() method. We will below define this method with the code.

SizedBox(
  height: 45,
  child: ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: Colors.teal,
      ),
      onPressed: () => _scaleDialog(),
      child: const Text('Scale Dialog',
          style: TextStyle(
              fontSize: 17, fontWeight: FontWeight.bold))),
),

Now we will deeply define _scaleDialog() method:

In this method, we will add the showGeneralDialog() function. Inside the function, we will add context, pageBuilder, transitionBuilder, and transitionDuration. In transitionBuilder, we will return Transform.scale() method. In this method, we will add a curve and its child we will add the _dialog(ctx) widget method.

void _scaleDialog() {
showGeneralDialog(
context: context,
pageBuilder: (ctx, a1, a2) {
return Container();
},
transitionBuilder: (ctx, a1, a2, child) {
var curve = Curves.easeInOut.transform(a1.value);
return Transform.scale(
scale: curve,
child: _dialog(ctx),
);
},
transitionDuration: const Duration(milliseconds: 300),
);
}

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


Code File:

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

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
Widget _dialog(BuildContext context) {
return AlertDialog(
title: const Text("Flutter Dev's"),
content: const Text("FlutterDevs specializes in creating cost-effective "
"and efficient applications with our perfectly crafted, creative and "
"leading-edge flutter app development solutions for customers all around "
"the globe."),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
"Okay",
style: TextStyle(color: Colors.red, fontSize: 17),
))
],
);
}

void _rotateDialog() {
showGeneralDialog(
context: context,
pageBuilder: (ctx, a1, a2) {
return Container();
},
transitionBuilder: (ctx, a1, a2, child) {
return Transform.rotate(
angle: math.radians(a1.value * 360),
child: _dialog(ctx),
);
},
transitionDuration: const Duration(milliseconds: 300),
);
}

void _scaleDialog() {
showGeneralDialog(
context: context,
pageBuilder: (ctx, a1, a2) {
return Container();
},
transitionBuilder: (ctx, a1, a2, child) {
var curve = Curves.easeInOut.transform(a1.value);
return Transform.scale(
scale: curve,
child: _dialog(ctx),
);
},
transitionDuration: const Duration(milliseconds: 300),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
automaticallyImplyLeading: false,
title: const Text('Flutter Animate Dialogs Demo'),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Image(
image: AssetImage("assets/logo.png"),
height: 150,
),
const SizedBox(
height: 50,
),
SizedBox(
height: 45,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.teal,
),
onPressed: () => _rotateDialog(),
child: const Text('Rotate Dialog',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold))),
),
const SizedBox(
height: 20,
),
SizedBox(
height: 45,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.teal,
),
onPressed: () => _scaleDialog(),
child: const Text('Scale Dialog',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold))),
),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

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

Final Output

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Animate Dialog in your flutter projectsWe will show you what the Introduction is?. What are the construction and parameters of Animate Dialog, make a demo program for working with Animate Dialog without using any third-party plugin in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

We welcome feedback and hope 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 Barcode Scanner In Flutter

0

Scan by mobile is in pattern in many applications, the Easiest method for sending/getting data from code that can be scanned by the camera. Assuming you believe that individuals should utilize your application to rapidly outwardly perceive information, you can’t move beyond utilizing standardized barcodes. They’ve been around from now onward, indefinitely quite a while to perceive bits of information without any opportunity of error or misinterpretation.

Most the utilizations use Barcodes and QR codes for scanning item information, transferring money to someone, keeping the data in QR code design so on. we will store messages, SMS, URLs, telephone contacts, photographs, and a ton of different configurations in QR codes

In this article, we will Explore Barcode Scanner In Flutter. We will see how to implement a demo program for a barcode scanner and how we can integrate a Barcode scanner using the flutter_barcode_scanner there in the pub. dev to achieve this functionality in your flutter applications.

Table Of Contents:

Introduction
Method
Implementation
Code Implement
Code File
Conclusion

Introduction:

Barcode scanners are machine-lucid codes addressed outwardly as numbers and equal lines. At this point when checked by the laser beam emission barcode scanner, these symbols produce an extraordinary computerized digital code. Barcode scanners are fastened to and related to items to recognize and recognize them.

Barcode scanner identifications are utilized in POS frameworks, distribution centers, stock administration frameworks, or whatever other data set that requires stock information collection and storage.

Demo Module :

The above demo video shows how to integrate a barcode scanner in a flutter. It shows how the barcode scanner will work using the flutter_barcode_scanner package in your flutter applications. It shows when the user scans the barcode and then shows the result on your devices.

Methods:

In order to achieve functionality, we have two important methods in this package.

> scanBarcode:

The camera is utilized to scan the barcode /QR code till it is recognized. It will return the outcome as String.

static Future<String> scanBarcode(String lineColor, String cancelButtonText,
    bool isShowFlashIcon, ScanMode scanMode
  • String lineColor: This property allows us to provide a color to a scan line within a scan window.
  • String cancelButtonText: This property allows us to specify a string to cancel an action.
  • bool isShowFlashIcon: If it is true, the Flas icon will appear on the screen, otherwise not.
  • ScanMode scanMode: We can use this property to control the scan mode. [QR, BARCODE, DEFAULT] mods are available here.

> getBarcodeStreamReceiver:

It will return the persistent stream of standardized barcode scans until the client drops the activity. Returns a stream of barcode strings that were recognized.

static Stream? getBarcodeStreamReceiver(String lineColor,
    String cancelButtonText, bool isShowFlashIcon, ScanMode scanMode)

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
  flutter:
    sdk: flutter
  flutter_barcode_scanner:

Step 2: Import

import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

Step 3: For ios

Add add this line in Info.plist.Because you will use the camera of an iOS device and you have to mention why you will use it.

<key>NSCameraUsageDescription</key>
<string>Camera permission is required for barcode scanning.</string>

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In main. dart file, we will add BarcodeScannerDemo class. In this class, we will add a String variable _scanBarcode is equal to string text.

String _scanBarcode = 'Unknown';

In the body, we will add the Builder method. In this method, we will return a Container widget. Inside the widget, we will add alignment in was center and also a Flex widget. in this widget, we will add direction as the vertical axis and mainAxisalignmnet was the center.

Builder(builder: (BuildContext context) {
  return Container(
      alignment: Alignment.center,
      child: Flex(
          direction: Axis.vertical,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Image(
              image: AssetImage("assets/logo.png"),
              height: 150,
            ),
            const SizedBox(
              height: 50,
            ),
            Text('Scan result : $_scanBarcode\n',
                style: const TextStyle(
                    fontSize: 20, fontWeight: FontWeight.bold)),
            SizedBox(
              height: 45,
              child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.cyan,
                  ),
                  onPressed: () => barcodeScan(),
                  child: const Text('Barcode Scan',
                      style: TextStyle(
                          fontSize: 17, fontWeight: FontWeight.bold))),
            ),
          ]));
})

In the children, we will add an image, text ‘Scan result: $_scanBarcode\n’, and ElevatedButton. In this button, we will add the text ‘Barcode Scan’ and the onPressed method. In this method, we will add barcodeScan() function. We will define below the code.

Now, we will deeply define barcodeScan() function are:

In this function, we will add a String barcodeScanRes and we can pass scan mode as — { QR, BARCODE, DEFAULT } for graphic overlay for QR or Barcode.

Future<void> barcodeScan() async {
  String barcodeScanRes;
  // Platform messages may fail, so we use a try/catch PlatformException.
  try {
    barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
        '#ff6666', 'Cancel', true, ScanMode.QR);
    print(barcodeScanRes);
  } on PlatformException {
    barcodeScanRes = 'Failed to get platform version.';
  }
  if (!mounted) return;
  setState(() {
    _scanBarcode = barcodeScanRes;
  });
}

In this function, we will add setState()method. In this method, we will add _scanBarcode is equal to the barcodeScanRes. When the user scans the code then the result will be shown otherwise it is shown as an empty/unknown result.

For continuous scanning, you can use :

If you want to scan barcodes constantly without shutting the camera use FlutterBarcodeScanner.getBarcodeStreamReceive params will be similar like FlutterBarcodeScanner.scanBarcodefor example

Future<void> startBarcodeScanStream() async {
  FlutterBarcodeScanner.getBarcodeStreamReceiver(
          '#ff6666', 'Cancel', true, ScanMode.BARCODE)!
      .listen((barcode) => print(barcode));
}

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

Final Output

Code File:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode/splash_screen.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Splash(),
    );
  }
}
class BarcodeScannerDemo extends StatefulWidget {
  const BarcodeScannerDemo({Key? key}) : super(key: key);
  @override
  _BarcodeScannerDemoState createState() => _BarcodeScannerDemoState();
}
class _BarcodeScannerDemoState extends State<BarcodeScannerDemo> {
  String _scanBarcode = 'Unknown';
  /// For Continuous scan
  Future<void> startBarcodeScanStream() async {
    FlutterBarcodeScanner.getBarcodeStreamReceiver(
            '#ff6666', 'Cancel', true, ScanMode.BARCODE)!
        .listen((barcode) => print(barcode));
  }
  Future<void> barcodeScan() async {
    String barcodeScanRes;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
          '#ff6666', 'Cancel', true, ScanMode.QR);
      print(barcodeScanRes);
    } on PlatformException {
      barcodeScanRes = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() {
      _scanBarcode = barcodeScanRes;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Barcode Scanner Demo'),
          centerTitle: true,
          automaticallyImplyLeading: false,
          backgroundColor: Colors.cyan,
        ),
        body: Builder(builder: (BuildContext context) {
          return Container(
              alignment: Alignment.center,
              child: Flex(
                  direction: Axis.vertical,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const Image(
                      image: AssetImage("assets/logo.png"),
                      height: 150,
                    ),
                    const SizedBox(
                      height: 50,
                    ),
                    Text('Scan result : $_scanBarcode\n',
                        style: const TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold)),
                    SizedBox(
                      height: 45,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            primary: Colors.cyan,
                          ),
                          onPressed: () => barcodeScan(),
                          child: const Text('Barcode Scan',
                              style: TextStyle(
                                  fontSize: 17, fontWeight: FontWeight.bold))),
                    ),
                  ]));
        }));
  }
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Barcode Scanner in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Barcode Scanner using the flutter_barcode_scanner package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


IndexedStack In Flutter

0

Flutter offers a lot of built-in widgets that can assist us with making dazzling applications without composing an excess of code or installing such a large number of third-party libraries only for building UIs.

In Flutter, almost everything is a widget — even format models are widgets. The photos, symbols, and text you find in a Flutter application are on the widgets. Anyway, things you don’t see are extra widgets, similar to the rows, columns, and grids that arrange, oblige and align the conspicuous widgets.

In this article, we will explore the IndexedStack In Flutter. We will implement an indexedstack demo program and how to use it in your flutter applications.

Table Of Contents::

What is IndexedStack?

Constructor

Properties

Implementation

Code File

Conclusion



What is IndexedStack?

An IndexedStack is a stack where just one component is displayed at one time by its index. It accepts children as ordinary Stack. Yet, it just shows one child at one time. IndexedStack is a subclass of Stack. You can determine which child widget to be shown through the index property. Assuming the index is null, child widgets will be shown.

To use IndexedStack, we can simply wrap the list of widgets inside the IndexedStack widget. Then, add an index parameter with a variable that can be changed with some action.

To utilize IndexedStack, we can just wrap the list of widgets inside the IndexedStack widget. Then, at that point, add an index parameter with a variable that can be changed with some activity.

Demo Module::

The above demo video shows how to use indexedstack in a flutter. It shows how the indexedstack will work using the IndexedStack in your flutter applications. It shows when the user clicks the button then, the images will be changed because it shows only one component at one time by index. It will be shown on your device.

Constructor:

To utilize IndexedStack, you need to call the constructor underneath:

IndexedStack({
  Key? key,
  AlignmentGeometry alignment = AlignmentDirectional.topStart,
  TextDirection? textDirection,
  StackFit sizing = StackFit.loose,
  this.index = 0,
  List<Widget> children = const <Widget>[],
})

Properties:

There are some properties of IndexedStack are:

  • > index: This property is used to assign the index to the child. Defaults to 0.
  • > List<Widget> children: This property is used to below list the widgets in the tree. Defaults to const <Widget>[].
  • > StackFit sizing: This property is used to size the non-positioned children in the stack. Defaults to StackFit.loose.
  • > AlignmentGeometry alignment: This property is used to align the non-positioned and partially-positioned children.
  • > TextDirection? textDirection: This property is used to text direction to resolve the alignment.
  • > Key? key: This property is used to control how a widget is replaced with another widget.

Implementation:

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

In the main. dart file, we will create a new class IndexedStackDemo. In this class, we will create an integer value equal to zero.

int value = 0;

In the body, we will add the IndexedStack method. In this method, we will add an index equal to a value. In children, we will add four different texts and four different images.

IndexedStack(
  index: value,
  children: [
    Column(
      children: const [
        Text(
          "Image 1",
          style: TextStyle(
              color: Colors.red,
              fontSize: 22.0,
              fontWeight: FontWeight.bold),
        ),
        SizedBox(
          width: 300,
          height: 300,
          child: Center(
            child: Image(
              image: AssetImage("assets/logo.png"),
            ),
          ),
        )
      ],
    ),
    Column(
      children: const [
        Text(
          "Image 2",
          style: TextStyle(
              color: Colors.red,
              fontSize: 22.0,
              fontWeight: FontWeight.bold),
        ),
        SizedBox(
          width: 300,
          height: 300,
          child: Center(
            child: Image(
              image: AssetImage("assets/powered_by.png"),
            ),
          ),
        )
      ],
    ),
    Column(
      children: const [
        Text(
          "Image 3",
          style: TextStyle(
              color: Colors.red,
              fontSize: 22.0,
              fontWeight: FontWeight.bold),
        ),
        SizedBox(
          width: 300,
          height: 300,
          child: Center(
            child: Image(
              image: AssetImage("assets/flutter.png"),
            ),
          ),
        )
      ],
    ),
    Column(
      children: const [
        Text(
          "Image 4",
          style: TextStyle(
              color: Colors.red,
              fontSize: 22.0,
              fontWeight: FontWeight.bold),
        ),
        SizedBox(
          width: 300,
          height: 300,
          child: Center(
            child: Image(
              image: AssetImage("assets/demo.png"),
            ),
          ),
        )
      ],
    )
  ],
),

Now, we will add the SizedBox widget with height and width. Its child, we will add ElevatedButton. In this button, we will add style and the onPressed method. Inside the method, we will add setState() function. In this function, we will add if (value < 3) then, value++. Else, the value is equal to zero. Its child, we will add the text ”CLICK”.

SizedBox(
  height: 65,
  width: 130,
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: Colors.cyan,
      ),
      onPressed: () {
        setState(() {
          if (value < 3) {
            value++;
          } else {
            value = 0;
          }
        });
      },
      child: const Text(
        "CLICK",
        style: TextStyle(
            color: Colors.white,
            fontSize: 21.0,
            fontWeight: FontWeight.bold),
      ),
    ),
  ),
)

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

Final Output

Code File:

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

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

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

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

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

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

class _IndexedStackDemoState extends State<IndexedStackDemo> {
  int value = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueGrey[100],
      appBar: AppBar(
        backgroundColor: Colors.cyan,
        automaticallyImplyLeading: false,
        title: const Text("Flutter Indexed Stack Demo"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IndexedStack(
              index: value,
              children: [
                Column(
                  children: const [
                    Text(
                      "Image 1",
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 22.0,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 300,
                      height: 300,
                      child: Center(
                        child: Image(
                          image: AssetImage("assets/logo.png"),
                        ),
                      ),
                    )
                  ],
                ),
                Column(
                  children: const [
                    Text(
                      "Image 2",
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 22.0,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 300,
                      height: 300,
                      child: Center(
                        child: Image(
                          image: AssetImage("assets/powered_by.png"),
                        ),
                      ),
                    )
                  ],
                ),
                Column(
                  children: const [
                    Text(
                      "Image 3",
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 22.0,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 300,
                      height: 300,
                      child: Center(
                        child: Image(
                          image: AssetImage("assets/flutter.png"),
                        ),
                      ),
                    )
                  ],
                ),
                Column(
                  children: const [
                    Text(
                      "Image 4",
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 22.0,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 300,
                      height: 300,
                      child: Center(
                        child: Image(
                          image: AssetImage("assets/demo.png"),
                        ),
                      ),
                    )
                  ],
                )
              ],
            ),
            SizedBox(
              height: 65,
              width: 130,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.cyan,
                  ),
                  onPressed: () {
                    setState(() {
                      if (value < 3) {
                        value++;
                      } else {
                        value = 0;
                      }
                    });
                  },
                  child: const Text(
                    "CLICK",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 21.0,
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the IndexedStack in your flutter projectsWe will show you what IndexedStack is?. Make a demo program for working IndexedStack using the IndexedStack in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Implementing Voice Searching In Flutter

0

In today’s world, everybody needs the mobile application they are utilizing to be more alluring and contain more features. Voice Searching is one of the main highlights which makes any application more responsive and intuitive to the user.

It involves a broad array of exploration in computer science, semantics, and computer engineering. Numerous modern devices and text-focused programs have speech recognition functions in them to consider more straightforward or hands-free utilization of a device.

In this blog, we will explore Implementing Voice Searching In Flutter. We will see how to implement a demo program of voice searching and we’ll use our voice to enter the text rather than typing text using the flutter_speech package in your flutter applications.

flutter_speech | Flutter Package
Flutter plugin to support voice recognition on Android, iOS, and Mac OSXpub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

Voice/Speech recognition, or speech-to-text, is the capacity of a machine or program to distinguish words expressed out loud and convert them into readable text. The simple flutter_speech package may recognize words and expressions when expressed clearly. The more modern package can deal with normal speech, various accents, and different languages.

Demo Module :

The above demo video shows how to implement Voice Searching in a flutter. It shows how voice searching will work using the flutter_speech package in your flutter applications. It shows our voice to enter the text rather than typing text. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
flutter_speech:

Step 2: Import

import 'package:drop_shadow/drop_shadow.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we will create a Language class in the main. dart file. In this class, we will add two final String names and code.

class Language {
final String name;
final String code;

const Language(this.name, this.code);
}

Now, we will create languages that are equal to the bracket. Inside the bracket, we will add some Language().

const languages = [
Language('English', 'en_US'),
Language('Hindi', 'hi'),
Language('Francais', 'fr_FR'),
Language('Pусский', 'ru_RU'),
Language('Italiano', 'it_IT'),
Language('Español', 'es_ES'),
];

In main. dart file, we will create a new VoiceSearchingDemo class. In this class, we will add a late SpeechRecognition variable that was _speech, bool _speechRecognitionAvailable that is equal to the false, bool _isListening that is equal to the false, String transcription is equal to an empty string, and Language variable selectedLang is equal to languages. first.

late SpeechRecognition _speech;
bool _speechRecognitionAvailable = false;
bool _isListening = false;
String transcription = '';
Language selectedLang = languages.first;

Now, we will create an initState() method. In this method, we will add activateSpeechRecognizer()method. Inside this method, we will add _speech. setAvailabilityHandler, setErrorHandler, activate setRecognitionResultHandler and etc.

@override
initState() {
super.initState();
activateSpeechRecognizer();
}

void activateSpeechRecognizer() {
print('_MyAppState.activateSpeechRecognizer... ');
_speech = SpeechRecognition();
_speech.setAvailabilityHandler(onSpeechAvailability);
_speech.setRecognitionStartedHandler(onRecognitionStarted);
_speech.setRecognitionResultHandler(onRecognitionResult);
_speech.setRecognitionCompleteHandler(onRecognitionComplete);
_speech.setErrorHandler(errorHandler);
_speech.activate('en_US').then((res) {
setState(() => _speechRecognitionAvailable = res);
});
}

Now, we need to create all these handler methods. So, let’s make them one by one method. All the below methods will handle the multiple cases.

void onSpeechAvailability(bool result) =>
setState(() => _speechRecognitionAvailable = result);

void onRecognitionStarted() {
setState(() => _isListening = true);
}

void onRecognitionResult(String text) {
print('_MyAppState.onRecognitionResult... $text');
setState(() => transcription = text);
}

void onRecognitionComplete(String text) {
print('_MyAppState.onRecognitionComplete... $text');
setState(() => _isListening = false);
}

void errorHandler() => activateSpeechRecognizer();

We will also create a custom _buildButton() widget. In this widget, we will add ElevatedButton. Inside the button, we will add onPressed and text.

Widget _buildButton({required String label, VoidCallback? onPressed}) =>
Padding(
padding: EdgeInsets.all(12.0),
child: ElevatedButton(
onPressed: onPressed,
child: Text(
label,
style: const TextStyle(color: Colors.white),
),
));

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

You can see that initially, it will ask for record audio permission. Allow it.

Now, we need to create the methods which will we call on the button click on start, stop, cancel. That’s great, now we will call these methods on button clicks.

void start() => _speech.activate(selectedLang.code).then((_) {
return _speech.listen().then((result) {
print('_MyAppState.start => result $result');
setState(() {
_isListening = result;
});
});
});

void cancel() =>
_speech.cancel().then((_) => setState(() => _isListening = false));

void stop() => _speech.stop().then((_) {
setState(() => _isListening = false);
});

void onCurrentLocale(String locale) {
print('_MyAppState.onCurrentLocale... $locale');
setState(
() => selectedLang = languages.firstWhere((l) => l.code == locale));
}

Add all these methods to your build method. In AppBar, we will add the actions widget. In this widget add PopupMenuButton(). In the body part, we will add the Column widget. Inside the widget, we will use three custom _buildButton() for start, stop and cancel. Also, the Column widget wrap to the Center widget, and the Center widget wrap to the Padding.

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Voice Searching Demo'),
actions: [
PopupMenuButton<Language>(
onSelected: _selectLangHandler,
itemBuilder: (BuildContext context) => _buildLanguagesWidgets,
)
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Container(
padding: const EdgeInsets.all(8.0),
color: Colors.grey.shade200,
child: Text(transcription))),
_buildButton(
onPressed: _speechRecognitionAvailable && !_isListening
? () => start()
: null,
label: _isListening
? 'Listening...'
: 'Listen (${selectedLang.code})',
),
_buildButton(
onPressed: _isListening ? () => cancel() : null,
label: 'Cancel',
),
_buildButton(
onPressed: _isListening ? () => stop() : null,
label: 'Stop',
),
],
),
)),
);
}

List<CheckedPopupMenuItem<Language>> get _buildLanguagesWidgets => languages
.map((l) => CheckedPopupMenuItem<Language>(
value: l,
checked: selectedLang == l,
child: Text(l.name),
))
.toList();

void _selectLangHandler(Language lang) {
setState(() => selectedLang = lang);
}

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

Final Output

Code File:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_speech/flutter_speech.dart';
import 'package:flutter_voice_search_demo/splash_screen.dart';

void main() {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
runApp(const MyApp());
}

class Language {
final String name;
final String code;

const Language(this.name, this.code);
}

const languages = [
Language('English', 'en_US'),
Language('Hindi', 'hi'),
Language('Francais', 'fr_FR'),
Language('Pусский', 'ru_RU'),
Language('Italiano', 'it_IT'),
Language('Español', 'es_ES'),
];

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

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash());
}
}

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

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

class _VoiceSearchingDemoState extends State<VoiceSearchingDemo> {
late SpeechRecognition _speech;

bool _speechRecognitionAvailable = false;
bool _isListening = false;

String transcription = '';

//String _currentLocale = 'en_US';
Language selectedLang = languages.first;

@override
initState() {
super.initState();
activateSpeechRecognizer();
}

// Platform messages are asynchronous, so we initialize in an async method.
void activateSpeechRecognizer() {
print('_MyAppState.activateSpeechRecognizer... ');
_speech = SpeechRecognition();
_speech.setAvailabilityHandler(onSpeechAvailability);
_speech.setRecognitionStartedHandler(onRecognitionStarted);
_speech.setRecognitionResultHandler(onRecognitionResult);
_speech.setRecognitionCompleteHandler(onRecognitionComplete);
_speech.setErrorHandler(errorHandler);
_speech.activate('en_US').then((res) {
setState(() => _speechRecognitionAvailable = res);
});
}

Widget _buildButton({required String label, VoidCallback? onPressed}) =>
Padding(
padding: EdgeInsets.all(12.0),
child: ElevatedButton(
onPressed: onPressed,
child: Text(
label,
style: const TextStyle(color: Colors.white),
),
));

void start() => _speech.activate(selectedLang.code).then((_) {
return _speech.listen().then((result) {
print('_MyAppState.start => result $result');
setState(() {
_isListening = result;
});
});
});

void cancel() =>
_speech.cancel().then((_) => setState(() => _isListening = false));

void stop() => _speech.stop().then((_) {
setState(() => _isListening = false);
});

void onCurrentLocale(String locale) {
print('_MyAppState.onCurrentLocale... $locale');
setState(
() => selectedLang = languages.firstWhere((l) => l.code == locale));
}

void onSpeechAvailability(bool result) =>
setState(() => _speechRecognitionAvailable = result);

void onRecognitionStarted() {
setState(() => _isListening = true);
}

void onRecognitionResult(String text) {
print('_MyAppState.onRecognitionResult... $text');
setState(() => transcription = text);
}

void onRecognitionComplete(String text) {
print('_MyAppState.onRecognitionComplete... $text');
setState(() => _isListening = false);
}

void errorHandler() => activateSpeechRecognizer();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Voice Searching Demo'),
actions: [
PopupMenuButton<Language>(
onSelected: _selectLangHandler,
itemBuilder: (BuildContext context) => _buildLanguagesWidgets,
)
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Container(
padding: const EdgeInsets.all(8.0),
color: Colors.grey.shade200,
child: Text(transcription))),
_buildButton(
onPressed: _speechRecognitionAvailable && !_isListening
? () => start()
: null,
label: _isListening
? 'Listening...'
: 'Listen (${selectedLang.code})',
),
_buildButton(
onPressed: _isListening ? () => cancel() : null,
label: 'Cancel',
),
_buildButton(
onPressed: _isListening ? () => stop() : null,
label: 'Stop',
),
],
),
)),
);
}

List<CheckedPopupMenuItem<Language>> get _buildLanguagesWidgets => languages
.map((l) => CheckedPopupMenuItem<Language>(
value: l,
checked: selectedLang == l,
child: Text(l.name),
))
.toList();

void _selectLangHandler(Language lang) {
setState(() => selectedLang = lang);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Implementing Voice Searching in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Voice Searching using the flutter_speech package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Flutter Rendering Widgets Using JSON Data

0

Flutter is Google’s free, open-source software development kit (SDK) for cross-stage mobile application advancement. Utilizing a solitary stage rationalist codebase, Flutter assists developers with building superior execution, and versatile applications with alluring and utilitarian UIs for Android or IOS. Flutter depends on a library of pre-made widgets that simplify it for even individuals with restricted programming or development experience to rapidly send off their mobile applications.

From network requests packages to entire architecture patternspub. dev (the Dart/Flutter package manager) has turned into an incredible wellspring of open-source code, libraries, and thoughts.

This article will explore the Flutter Rendering Widgets Using JSON Data. We will see how to implement a demo program. We will be displaying the widgets on screen with the help of JSON Data using the json_dynamic_widget package in your flutter applications.

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

Flutter furnishes us with countless in-built widgets, which we can straightforwardly use to make a delightful and engaging UI for our applications. In any case, the Rendering of UI through JSON Data comes into the image when we have distributed the applications onto PlayStore and AppStore and some principal UI Changes should be finished.

As of now, we need to upload the applications again on PlayStore and AppStore after rolling out the expected improvements yet if we are utilizing JSON Data for example through an API, we simply have to roll out the improvements in JSON Data, not in the applications.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
json_dynamic_widget:

In order to bring data from the server API, we will also need to add a networking package. Here, we can use the HTTP package.

http: 

Step 2: Import

import 'package:json_dynamic_widget/json_dynamic_widget.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

First, we will be rendering the data with the help of the sample.json file on the assets folder, we can create the API for the same and render data.

{
"args": {
"appBar": {
"args": {
"title": {
"args": {
"text": "Flutter Rendering UI Using JSON Data"
},
"type": "text"
}
},
"type": "app_bar"
},
"body": {
"child": {
"type": "network_image",
"args": {
"fit": "cover",
"src": "https://tech.pelmorex.com/wp-content/uploads/2020/10/flutter.png"
}
},
"type": "center"
}
},
"type": "scaffold"
}

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

Inside main. dart file, we will create RenderingWidget class. In this class, first, we will add Map <dynamic, dynamic> mapData is equal to the curly bracket. Also, we will create a var registry that is equal to the JsonWidgetRegistry.instance.

Map<dynamic, dynamic> mapData = {};
var registry = JsonWidgetRegistry.instance;

Now, we will create a readJson() widget with Future<Map>. In this widget, we will add the final String response is equal to the await rootBundle.loadString (‘’your json file path‘). Then, we will add the final data is equal to the await json. decode(response) and return data.

Future<Map> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
return data;
}

In the Widget build, we will add the readJson() dot then the value is navigated to mapData is equal to the value. Then, the var widget is equal to the JsonWidgetData.fromDynamic(mapData, registry: registry), and then, return the widget!.build(context: context).

@override
Widget build(BuildContext context) {
readJson().then((value) => mapData = value);
var widget = JsonWidgetData.fromDynamic(mapData, registry: registry);
return widget!.build(context: context);
}

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

Final Output

Code File:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_dynamic_widget/json_dynamic_widget.dart';


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,
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const RenderingWidget());
}
}

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

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

class _RenderingWidgetState extends State<RenderingWidget> {
Map<dynamic, dynamic> mapData = {};
var registry = JsonWidgetRegistry.instance;

Future<Map> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
return data;
}

@override
Widget build(BuildContext context) {
readJson().then((value) => mapData = value);
var widget = JsonWidgetData.fromDynamic(mapData, registry: registry);
return widget!.build(context: context);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Rendering Widgets Using JSON Data in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working on Rendering Widgets Using JSON Data using the json_dynamic_widget package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Change Dynamically Theme In Flutter

0

As you probably are aware, Flutter as of late dropped its significant adaptation update, for example, Flutter 3.0. It brings a ton of changes, and I was hanging tight for such a long time, Material You, which was formally divulged at Google IO 2021. Look at this link for the individuals who don’t have the foggiest idea of what Material You are.

In this article, we will explore the Change Dynamically Theme In Flutter. We will see how to implement a demo program. How to get dynamic dark/light mode using the get package and how to make the theme persistent using the get_storage package in your flutter applications.

For GetX:

get | Flutter Package
GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, and intelligent…pub.dev

For Get Storage:

get_storage | Flutter Package
A fast, extra light, and synchronous key-value in memory, which backs up data to disk at each operation. It is written…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

It’s extraordinary assistance for overseeing themes in Flutter, however, to make it work appropriately we’ll have to ensure we’ve populated the theme and darkTheme properties on MaterialApp with the elegantly thought out and masterfully variety composed themes that our UI/UX group has made. We will change MaterialApp to GetMaterialApp utilizing getx.

ThemeMode grants us the following states:

  • Themes.light— We will create a new Themes() class and add ThemeData.light() with background color, button color, etc. Apply the theme referenced by the theme property on GetMaterialApp. Of course, this theme should have its brightness set to be a copyWith from the Flutter supplied ThemeData.light().
  • Themes.dark— Apply the theme referenced by the darkTheme property on GetMaterialApp. Again, this theme should have its brightness set to be a copyWith from the Flutter supplied ThemeData.dark().
  • ThemeService().theme — We will create a new ThemeService() class using GetStorage and apply the theme referenced by the themeMode property on GetMaterialAppthat matches the mode currently in use on the device. Now this one is interesting as it will set the theme of our app to match the modes of the device when our app starts, and it will dynamically change our app’s theme to track the mode on the device when it changes between light and dark.

Demo Module ::

This demo video shows how to change the dynamic theme in a flutter and shows how a dynamic theme will work using the get package and how to make the theme persistent using the get_storage package in your flutter applications. We will show a user press the button then the theme will be changed into the light mode to dark mode/vice versa and also the theme was persistent. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
get:
get_storage:

Step 2: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 3: Import

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the app_theme file inside, we will create a Themes class. In this class, we will add two static methods first one is light and the other is dark. Both have ThemeData.light()/dark(). copy with background color, button color, etc.

import 'package:flutter/material.dart';

class Themes {
static final light = ThemeData.light().copyWith(
backgroundColor: Colors.white,
buttonColor: Colors.cyan,
bottomAppBarColor: Colors.cyan,
buttonTheme: const ButtonThemeData(
buttonColor: Colors.cyan,
textTheme: ButtonTextTheme.primary,
),
);
static final dark = ThemeData.dark().copyWith(
backgroundColor: Colors.black,
buttonColor: Colors.deepPurple,
bottomAppBarColor: Colors.deepPurple,
buttonTheme: const ButtonThemeData(
buttonColor: Colors.deepPurple,
textTheme: ButtonTextTheme.primary,
),
);
}

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

In the main. dart file, we will return a GetMaterialApp(). Inside, we will add a theme that is equal to the Themes. light(we will already define above) and a darkTheme that is equal to the Themes. light

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

Same dart file, we will create a MyHomePage() new class. In this class, we will get your style from the theme. You can also use Theme.of(context) it instead of context.theme

return Scaffold(
backgroundColor: context.theme.backgroundColor,
.....
)

In the body, we will create an ElevatedButton. In this button, we will add a primary, padding, textStyle, and onPressed method. In this method, we will add if Get.isDarkMode then our theme Get.changeThemeMode(ThemeMode.light) else Get.changeThemeMode(ThemeMode.dark). Its child, we will add the text ‘Change Theme’. Your dynamic theme is ready to go!.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:
() {
if (Get.isDarkMode) {
Get.changeThemeMode(ThemeMode.light);
} else {
Get.changeThemeMode(ThemeMode.dark);
}
},
child: const Text('Change Theme')),

Let’s make the theme persistent:

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

get_storage is a local storage package by GetX’s author. It’s an alternative to shared_preferences with better performance. We will create a ThemeService class.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class ThemeService {
final _box = GetStorage();
final _key = 'isThemeMode';

ThemeMode get theme => _loadThemeFromBox() ? ThemeMode.dark : ThemeMode.light;

bool _loadThemeFromBox() => _box.read(_key) ?? false;
_saveThemeToBox(bool isDarkMode) => _box.write(_key, isDarkMode);

void switchTheme() {
Get.changeThemeMode(_loadThemeFromBox() ? ThemeMode.light : ThemeMode.dark);
_saveThemeToBox(!_loadThemeFromBox());
}
}

Now, we will initialize the local storage and get the theme info from the storage in main.dart file.

void main() async{
await GetStorage.init();
runApp(const MyApp());
}

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

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

Final, we will add ThemeService().switchTheme to your button’s onPressed method on a ElevatedButton in MyHomePage() class.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:ThemeService().switchTheme,
child: const Text('Change Theme')),

The user can run the application on devices then, and the theme will be persistent and work perfectly Fine.

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_dynamically_theme/app_theme.dart';
import 'package:flutter_dynamically_theme/splash_screen.dart';
import 'package:flutter_dynamically_theme/theme_service.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async{
await GetStorage.init();
runApp(const MyApp());
}

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

@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

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

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

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: context.theme.backgroundColor,
appBar: AppBar(
backgroundColor: context.theme.bottomAppBarColor,
title: const Text("Flutter Change Dynamically Theme Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: 300,
width: 350,
),
const SizedBox(height: 80,),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: context.theme.buttonColor,
padding:
const EdgeInsets.symmetric(horizontal: 30, vertical: 16),
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onPressed:ThemeService().switchTheme,
child: const Text('Change Theme')),
],
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Change Dynamically Theme in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working on Change Dynamically Theme using the get package and also make the theme persistent using the get_storage package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Implemented Overlay In Flutter

0

Whenever you will code for building anything in Flutter, it will be inside a widget. The focal intention is to build the application out of widgets. It portrays how your application view ought to look with its ongoing configuration and state. At the point when you made any adjustment in the code, the widget revamps its depiction by computing the contrast between the past and current widget to decide the negligible changes for delivering in the UI of the application.

Widgets are settled with one another to build the application. It implies the base of your application is itself a widget, and right down is a widget moreover. For instance, a widget can show something, can characterize design, can deal with collaboration, and so on.

In this post, we will explore the Implemented Overlay In Flutter. We will also implement a demo program of overlay, and to implement Overlay in Flutter we need to know about two Flutter built-in classes OverlayEntry class and the OverlayState class.

Table Of Contents::

Introduction

OverlayEntry

OverlayState

Code Implement

Code File

Conclusion



Introduction:

Overlays let independent child widgets “float” visual components on top of different widgets by embedding them into the overlay’s stack. The overlay gives every one of these widgets dealing with their support access to the overlay utilizing OverlayEntry objects.

The Overlay widget utilizes a custom stack execution, which is the same as the Stack widget. The primary use instance of Overlay is connected with the route and has the option to embed widgets on top of the pages in an application. To just show a pile of widgets, think about utilizing Stack all things considered.

Demo Module ::

The above demo video shows how to implement an overlay in a flutter and shows how the overlay will work using the OverlayEntry & OverlayState in your flutter applications. We will show a user when clicking on the button and then, show a different three container box with text and remove it according to delay of seconds. It will be shown on your device.

OverlayEntry:

A place in an Overlay that can contain a widget. Overlay entries are embedded into an Overlay utilizing the OverlayState.insert or OverlayState.insertAll functions. To find the nearest encasing overlay for a given BuildContext, utilize the Overlay. of function.

An overlay section can be in all things considered each overlay in turn. To remove an entry from its overlay, call the remove function on the overlay entry. Since an Overlay utilizes a Stack format, overlay sections can utilize Positioned and AnimatedPositioned to situate themselves inside the overlay.

> OverlayEntry Construction:

To utilize OverlayEntry, you need to call the constructor underneath:

OverlayEntry({
required this.builder,
bool opaque = false,
bool maintainState = false,
})

All fields marked with @required must not be empty in the above Constructor.

> OverlayEntry Properties:

There are some parameters of OverlayEntry are:

  • > builder: This property is utilized for this entry and will incorporate the widget built by this builder in the overlay of the entry’s situation.
  • > opaque: This property is utilized to take a bool value that chooses whether this entry impedes the whole overlay. On the off chance that an entry professes to be opaque, for proficiency, the overlay will skip building entries underneath that entry except if they have a maintainState set.
  • > maintainState: This property is utilized to take bool value and if set true, it strongly builds the blocked entries under an opaque entry.

> OverlayEntry Methods:

There are only one methods of OverlayEntry are:

  • > remove: This method is used to remove this entry from the overlay.

OverlayState:

The current state of an Overlay is used to insert OverlayEntries into the overlay.

> OverlayState Methods:

There are some method of OverlayState are:

  • > debugIsVisibleThis method is utilized to check regardless of whether the given OverlayEntry is visible and returns a bool.
  • > insertThis method is utilized to embed the given OverlayEntry into the Overlay.
  • > insertAllThis method is utilized to take a List of OverlayEntries and embeds every one of the entries into the Overlay. You can likewise determine the above-mentioned and underneath properties to state in which request entries are to be embedded.
  • > rearrangeThis method is utilized to remove every one of the entries listed in the given List of OverlayEntries, then reinsert them into the overlay in the given order.

Code Implement:

You need to implement it in your code respectively:

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

In the main. dart file. Inside, we will create an OverlayDemo() class. In this class, we will create a Column widget. In this widget, we will add crossAxisAlignment and mainAxisAlignment as the center. Also, Add an image and Material Button(). In this button, we will add color, height, width, and the onPressed() method. In this method, we will add _showOverlay(context) Function. We will deeply describe it below later. Also, we will add the Text ‘show Overlay’.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/logo.png',height: 300,width: 350,),
const SizedBox(height: 50,),
MaterialButton(
color: Colors.pink[300],
minWidth: MediaQuery.of(context).size.width * 0.4,
height: MediaQuery.of(context).size.height * 0.06,
child: const Text(
'show Overlay',
style: TextStyle(color: Colors.white,fontSize: 17),
),
onPressed: () {
//calling the _showOverlay method
// when Button is pressed
_showOverlay(context);
},
),
],
)

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

Output

Now, we will deeply describe _showOverlay(context) Function:

First, we will be Declaring and Initializing OverlayState and
 OverlayEntry objects.

OverlayState? overlayState = Overlay.of(context);
OverlayEntry overlay1;
OverlayEntry overlay2;
OverlayEntry overlay3;

Then, we will create overlay1 that is equal to the theOverlayEntry(). We can return any widget we like here to be displayed on the Overlay. We will return Positioned widget with ClipRRect and inside add a container with height, width, and color. Its child, we will add Material with color and text.

overlay1 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.3,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.orange.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('The Flutter app developers at FlutterDevs have',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

Same as above for overlay2. The change was the color of the container and text on the Material widget. All the process was the same.

overlay2 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.5,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.pink.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('decades of industry experience under a single roof,',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

Same as above for overlay3. The change was the color of the container and text on the Material widget. All the process was the same. User can add any return widget you like here to be displayed on the Overlay.

overlay3 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.7,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.blue.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('and this empowers us to serve you with excellence.',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

After the instatement of OverlayEntries I have called the insertAll technique for OverlayState and passed it to the List of OverlayEntries, this adds every one of the Entries to the Overlay.

overlayState?.insertAll([overlay1, overlay2, overlay3]);

From that point forward, I have awaited on Future. delayed to make a delay of 2 seconds and afterward called remove strategy to remove the first OverlayEntry from the Overlay and afterward correspondingly I have delayed for one second then called remove for the second OverlayEntry and afterward again postponed for 1seconds and called remove for the third and last OverlayEntry, this causes the OverlayEntries to disappear one after another.

await Future.delayed(const Duration(seconds: 2));
overlay1.remove();

await Future.delayed(const Duration(seconds: 1));
overlay2.remove();

await Future.delayed(const Duration(seconds: 1));
overlay3.remove();

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

Output

Code File:

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

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.cyan,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

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

class _OverlayDemoState extends State<OverlayDemo> {
void _showOverlay(BuildContext context) async {
OverlayState? overlayState = Overlay.of(context);
OverlayEntry overlay1;
OverlayEntry overlay2;
OverlayEntry overlay3;
overlay1 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.3,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.orange.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('The Flutter app developers at FlutterDevs have',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});
overlay2 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.5,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.pink.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('decades of industry experience under a single roof,',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});
overlay3 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.7,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.blue.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('and this empowers us to serve you with excellence.',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

overlayState?.insertAll([overlay1, overlay2, overlay3]);

await Future.delayed(const Duration(seconds: 2));

overlay1.remove();

await Future.delayed(const Duration(seconds: 1));

overlay2.remove();

await Future.delayed(const Duration(seconds: 1));

overlay3.remove();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[50],
appBar: AppBar(
title: const Text(
'Flutter Overlay Demo',
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/logo.png',
height: 300,
width: 350,
),
const SizedBox(
height: 50,
),
MaterialButton(
color: Colors.pink[300],
minWidth: MediaQuery.of(context).size.width * 0.4,
height: MediaQuery.of(context).size.height * 0.06,
child: const Text(
'show Overlay',
style: TextStyle(color: Colors.white, fontSize: 17),
),
onPressed: () {
_showOverlay(context);
},
),
],
))),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Overlay in your flutter projectsWe will show you what the Introduction is?. What are the OverlayState and OverlayEntry, make a demo program for working Overlay using the OverlayEntry & OverlayState in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Flash Error Messages In Flutter

0

Flutter is a UI tool compartment for making quick, gorgeous, natively compiled applications for mobile, web, and desktop with one programing language and single codebase. It is free and open-source. It was at first evolved by Google and is presently overseen by an ECMA standard.

Flutter applications utilize the Dart programming language for making an application. The dart programming shares a few same highlights as other programming dialects, like Kotlin and Swift, and can be trans-ordered into JavaScript code.

In this article, we will explore the Flash Error Messages In Flutter. We will see how to implement a demo program. Learn how to create a different style of the flash error message, it is called a snack bar, and how it shows error, success, or any warning message to the user in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Conclusion



Introduction:

The below demo output shows how to create flash messages in flutter and shows how flash messages will work like a snack bar used in your flutter applications. We will show a user when clicking on the button and then, show a flash message with your styles, text, and design. It will be shown on your device.

Demo Module ::

Demo Output

Code Implement:

You need to implement it in your code respectively:

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

In the main. dart file. Inside, we will create a MyHomePage() class. In this class, we will add a Column widget. In this widget, we will add crossAxisAlignment, mainAxisAlignment was the center. Inside, we will add an image and ElevatedButton().

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/logo.png',height: 300,width: 350,),
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
'This Username is not found! Please try again later')));
},
child: const Text('Show Flash Error Message')),
),
],
),

Inside ElevatedButton, we will add style and onPressed function. In this function, we will create a simple SnackBar() method. In this method, we will add content that is equal to the text ‘This Username is not found! Please try again later. Also, we will add the child method. In this method, we will add the text ‘Show Flash Error Message’.

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

Now, this time all are the same but only changes on SnackBar(). Inside the SnackBar(), we will add behavior is equal to the SnackBarBehavior.floating and content is equal to the Container widget. In this widget, we will add padding, height, and decoration box with the color blue and border-radius circular(15). In the child, we will add the text ‘This Username is not found! Please try again later.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar( SnackBar(
behavior: SnackBarBehavior.floating,
content: Container(
padding: const EdgeInsets.all(8),
height: 70,
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(15)),
),
child: const Center(
child: Text(
'This Username is not found! Please try again later'),
),
),

));
},
child: const Text('Show Flash Error Message')),

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

Last but not least, now this time we will other changes to SnackBar() on the ElevatedButton(). Inside, we will add a background color that was transparent, behavior is equal to the SnackBarBehavior.floating, elevation is 0 and content is equal to the Stack() widget. Inside the widget, we will add alignment in was center, clipBehavior was none. We will also add a Row widget. In this widget, we will add a Column. In this Column, we will add two text widgets.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.transparent,
behavior: SnackBarBehavior.floating,
elevation: 0,
content: Stack(
alignment: Alignment.center,
clipBehavior: Clip.none,
children: [
Container(
padding: const EdgeInsets.all(8),
height: 70,
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(15)),
),
child: Row(
children: [
const SizedBox(
width: 48,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Oops Error!',
style: TextStyle(
fontSize: 18, color: Colors.white),
),
Text(
'This Username is not found! Please try again later',
style: TextStyle(
fontSize: 14, color: Colors.white),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
Positioned(
bottom: 25,
left: 20,
child: ClipRRect(
child: Stack(
children: [
Icon(
Icons.circle,
color: Colors.red.shade200,
size: 17,
)
],
),
)),
Positioned(
top: -20,
left: 5,
child: Stack(
alignment: Alignment.center,
children: [
Container(
height: 30,
width: 30,
decoration: const BoxDecoration(
color: Colors.red,
borderRadius:
BorderRadius.all(Radius.circular(15)),
),
),
const Positioned(
top: 5,
child: Icon(
Icons.clear_outlined,
color: Colors.white,
size: 20,
))
],
)),
],
),
));
},
child: const Text('Show Flash Error Message')),

Then, we will add a Positioned widget. In this widget, we will add the bottom is 25, and the left is 20. In this child, we will add ClipRRect, and inside we will add a circle icon. Also, we will create one more Positioned widget. In this widget, we will add a clear icon.

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


Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Flash Error Messages in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Flash Error Messages in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Exploring Dart Constructors

0

In this blog, we will be Exploring Dart Constructors. Client befuddled by that puzzling linguistic structure in Dart constructors? Colons, named boundaries, asserts, etc. We’ll track down constructors on this blog.



What is Constructor?:

A constructor is an exceptional strategy that is utilized to introduce objects. The constructor is called when an object of a class is made.

In object-oriented programming when an object is made, it is naturally called the constructor. All classes have their default constructor which is made by the compiler when the class is called, besides one can likewise characterize its very own constructor. Yet, you should take note that if you do such, the default constructor won’t be made and will be overlooked.


When we need an example of a specific class we call a constructor, isn’t that so?

var animal = new Animal();

In Dart 2 we can leave out the new:

var animal = Animal();

A constructor is utilized to guarantee instances are made in a reasonable state. This is the definition in a class:

class Animal {
Animal();
}

Initializing:

Most times we want to design our cases. For instance, pass in the height of an animal:

var a = Animal(7);

a is now a 7-feet tall Animal.

To compose that constructor we incorporate the height field after the colon :

class Animal {
double height;
Animal(height) : this.height = height;
}

This is called an initializer. It acknowledges a comma-isolated rundown of articulations that initialize fields with contentions.

Luckily, Dart gives us an easy route. If the field name and type are equivalent to the argument in the constructor, we can do the:

class Animal {
double height;
Animal(this.height);
}

At times we should call super constructors while initializing:

class Age {
String name;
Age(this.name);
}

class Animal extends Age {
static mToFt(m) => m * 5.100;
double height;
Animal(height, name) : this.height = mToFt(height), super(name);
}

Notice that super(...)should constantly be the last bring in the initializer.

Furthermore, on the off chance that we expected to add more mind-boggling monitors (than types) against a twisted animal, we can utilize assert:

class Animal {
final double height;
Animal(height) : this.height = height, assert(height > 3.0);
}

Accessors and mutators:

Back to our earlier animal definition:

class Animal {
double height;
Animal(this.height);
}

void main() {
var a = Animal(7);
print a.height); // 7
}

How about we keep anybody from changing the height by making the field private.

In Dart, there is no private keyword. All things considered, we utilize a show: field names beginning with _ are private.

class Animal {
double _height;
Animal(this._height);
}

Amazing! Yet, presently it is impossible to get to a.height. We can make the height property read simply by adding a getter:

class Animal {
double _height;
Robot(this._height);

get height {
return this._height;
}
}

Getters are capacities that take no contentions and adjust to the uniform access principle.

We can rearrange our getter by utilizing two alternate ways: single expression syntax and implicit this:

class Animal {
double _height;
Robot(this._height);

get height => _height;
}

We can consider public fields as private fields with getters and setters as the same. That is:

class Animal {
double _height;
Animal(this._height);

get height => _height;
set height(value) => _height = value;
}

Remember initializers just assign values to fields and it is in this manner impractical to utilize a setter in an initializer:

class Animal {
double _height;
Animal(this.height); // ERROR: 'height' isn't a field in the enclosing class

get height => _height;
set height(value) => _height = value;
}

Constructor bodies:

If a setter should be called, we’ll need to do that in a constructor body:

class Animal {
double _height;

Animal(h) {
height = h;
}

get height => _height;
set height(value) => _height = value;
}

We can do a wide range of things in constructor bodies, yet we can’t return a value!

class Animal {
double height;
Animal(this.height) {
return this; // ERROR: Constructors can't return values
}
}

Final fields:

Final fields will be fields that must be relegated once.

final a = Animal(7);
a = Animal(9); /* ERROR */

Inside our class, we won’t be able to use the setter:

class Animal {
final double _height;
Animal(this._height);

get height => _height;
set height(value) => _height = value; // ERROR
}

Just like with var, we can utilized final before any type of definition:

var a;
var Animal a;


final a;
final Animal a;

The accompanying won’t work since height, being final, should be instated. What’s more, initialization occurs before the constructor body is run. How about we fix it:

class Animal {
final double height;
Animal(this.height);
}

Default values:

On the off chance that most animals are 7-feet tall, we can try not to indicate the height each time. We can suggest argument optional and give a default value:

class Animal {
final double height;
Animal([this.height = 7]);
}

So we can just call:

void main() {
var a = Animal();
print(a.height); // 7

var a2d2 = Animal(5.100);
print(a2d2.height); // 5.100
}

Immutable animals:

Our animals have more attributes than a height. Let’s add some more!

class Animal {
final double height;
final double weight;
final String name;

Animal(this.height, this.weight, this.name);
}

void main() {
final a = Animal(7, 150, "Whale");
a.name = "Fish"; // ERROR
}

As all fields are final, our animals are immutable! Once they are initialized, their attributes can’t be changed.

We can solve this with a const constructor:

class Animal{
final double height;
final double weight;
final List<String> names;

const Animal(this.height, this.weight, this.names);
}

void main() {
final a = const Robot(5, 170, ["Whale"]);
printar.names..add("Fish")); // ERROR: Unsupported operation: add
}

const must be utilized with articulations that can be processed at compile time. Take the accompanying model:

import 'dart:math';

class Animal {
final double height;
final double weight;
final List<String> names;

const Animal(this.height, this.weight, this.names);
}

void main() {
final a = const Animal(5, 170, ["Whale", Random().nextDouble().toString()]); // ERROR: Invalid constant value
}

const occurrences are canonicalized which implies that equivalent occasions highlight a similar item in memory space while running. Also, indeed, involving const constructors can further develop execution in Flutter applications.

Named Constructors:

In addition to the fact that arguments be can be named. We can give names to quite a few constructors:

class Animal {
final double height;
Animal(this.height);

Animal.fromWater(String water) : height = (water == 'whale') ? 5: 8;
Animal.copy(Animal other) : this(other.height);
}

void main() {
print(Animal.copy(Animal(7)).height); // 7
print(new Animal.fromWater('whale').height); // 5
print(new Animal.fromWater('crocodile').height); // 8
}

What occurred in duplicate? We utilized this to call the default constructor, actually “diverting” the launch.

Invoking named super constructors work as expected:

class Age{
String name;
Age();
Age.named(this.name);
}

class Animal extends Age {
final double height;
Animal(this.height);

Animal.named({ height, name }) : this.height = height, super.named(name);
}

void main() {
print(Animal.named(height: 8, name: "Whale").name); // Whale
}

Note that named constructors require an anonymous constructor to be characterized!

Private Named Constructors:

Be that as it may, imagine a scenario where we would have rather not uncovered a public constructor. Just named?. We can make a constructor private by prefixing it with an underscore:

class Robot {
Robot._();
}

Applying this information to our past model:

class Age {
String name;
Age._();
Age.named(this.name);
}

class Animal extends Age {
final double height;
Animal._(this.height, name) : super.named(name);

Animal.named({ height, name }) : this._(height, name);
}

void main() {
print(Animal.named(height: 8, name: "Whale").name); // Whale
}

The named constructor is “diverting” to the private default constructor. Purchasers of this API just see Animal.named() it as a method to get animal instances.

Factory Constructor:

We said constructors were not permitted to return. Prepare to be blown away. Factory constructors can!

class Animal {
final double height;

Animal._(this.height);

factory Animal() {
return Animal._(8);
}
}

void main() {
print(Animal().height); // 7
}

Factory constructors are syntactic sugar for the “factory pattern”, typically carried out with static capacities.

They seem like a constructor from an external perspective, yet inside they can designate occurrence creation by invoking a “normal” constructor. This makes sense why factory constructors don’t have initializers.

Since factory constructors can return different examples, we can do extremely helpful things like:

  • > caching: conditionally returning existing objects.
  • > subclasses: returning other instances such as subclasses.
class Animal {
final double height;

static final _cache = <double, Robot>{};

Animal._(this.height);

factory Animal(height) {
return _cache[height] ??= Animal._(height);
}
}

void main() {
final r1 = Animal(8);
final r2 = Animal(8);
final r3 = Animal(10);

print(r1.height); // 8
print(r2.height); // 8
print(identical(r1, r2)); // true
print(r3.height); // 10
print(identical(r2, r3)); // false
}

Singletons:

Singletons are classes that just at any point make one occurrence. We consider this a particular instance of caching!.

Let’s implement the singleton pattern in Dart:

class Animal {
static final Animal _instance = new Animal._(7);
final double height;

factory Animal() {
return _instance;
}

Animal._(this.height);
}

void main() {
var r1 = Animal();
var r2 = Animal();
print(identical(r1, r2)); // true
print(r1 == r2); // true
}

The factory constructor Animal(height)just consistently returns the unrivaled occurrence that was made while stacking the Animal class.

Conclusion:

In the article, I have explained the Dart constructors. This was a whole introduction to Dart constructors On User Interaction from my side, and it’s working using Dart.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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