Google search engine
Home Blog Page 28

Explore BlockSemantics In Flutter

0

Flutter permits you to set the semantics of a widget or a subtree by wrapping it as the child of the Semantics widget. A few widgets given by Flutter as of now have semantics as a matter of course. The semantics data given by the application can be extremely valuable for availability services. Accordingly, we should give suitable semantics for the UI showed on the screen. Notwithstanding, at times we need certain pieces of the UI to not have semantics.

In this article, we will Explore BlockSemantics In Flutter. We will execute a demo program of the BlockSemantics and how to use it in your flutter applications.

Table Of Contents::

BlockSemantics

Constructor

Properties

Code Implement

Code File

Conclusion



BlockSemantics:

In such cases, it’s smarter to utilize BlockSemantics, which is a more helpful approach to reject the semantics of sibling widgets. It’s shrewd enough to just do that for widgets that were painted before the BlockSemantics child, which implies that you don’t have to manually figure out which ones ought to, and which shouldn’t be disregarded.

Additionally, you might need that the semantics are just set for specific widgets on a subtree. For instance, when a popup is being shown, it implies the client can just interact with the popup. Different widgets ought not to have semantics at that point.

Demo Module :

This demo video shows how to use BlockSemantics in a flutter. It shows how BlockSemantics will work in your flutter applications. It shows there is a button for showing a popup. The popup itself is made utilizing a Card. When the popup is being shown, the client can just communicate with the popup. At that point, different widgets behind the popup ought not to have semantics, including the ‘Show popup’ button. BlockSemantics widget drops the semantics of all widgets that were painted before it in a similar semantic container. It will be shown on your device.

Constructor:

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

const BlockSemantics({
Key key,
this.blocking = true,
Widget child
})

You can utilize BlockSemantics and pass the popup widget as the child contention. The constructor has a named contention blocking which shows whether it should drop the semantics of different widgets painted before it. Thusly, you can pass a state variable to make the value true when the popup is being shown or false something else.

Properties:

There are some properties of BlockSemanticsare:

  • > blocking: This property is used to whether this widget is blocking semantics of all widgets that were painted before it in the same semantic container.
  • key: This property is used to controls how one widget replaces another widget in the tree.
  • > child: This property is utilized to characterize the widget beneath this widget in the tree. This widget can just have one child. To design various children, let this present widget’s child be a widget like Row Widget, Column Widget, or Stack Widget, which have a children’s property, and afterward give the children to that widget.

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 bool variable _showMessages is equal to false and static constant textStyle color was red.

bool _showMessage = false;
static const TextStyle textStyle = const TextStyle(color: Colors.red);

In the body, we will add SizedBox with a double width. infinity. We will add the Column widget. In this widget, we will add SizedBox with width and height. We will add the Stack widget. Inside, we will add an OutlinedButton(). We will add text and the onPressed function. In the function, we will add setState() method. Inside, we will add _showMessage is equal to true and wrap OutlinedButton() to Positioned() widget.

SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 400,
height: 150,
child: Stack(
alignment: Alignment.topCenter,
children: [
Positioned(
bottom: 0,
child: OutlinedButton(
child: Text('Show Message'),
onPressed: () => setState(() { _showMessage = true; }),
),
),
BlockSemantics(
blocking: _showMessage,
child: Visibility(
visible: _showMessage,
child: _buildMessage(),
),
)
],
),
),
],
),
),

We will add BlockSemantics() widget. Inside, we will add blocking is _showMessage bool variable and Its child property we will add Visibility(). Inside, add visible are equal _showMessage and add a _buildMessage() widget. We will discuss the below code.

We will deeply define _buildMessage() widget are:

In this widget, we will return Card(). Inside, we will add color, SizedBox, and Column. Inside a Column, we will add ListTile(). Inside we will add leading, title, and subtitle. Also, we will add TextButton(). Inside, we will add Text and the onPressed function. In the function, we will add setState() method. Inside, we will add _showMessage is equal to false and wrap TextButton() to ButtonTheme() widget.

Widget _buildMessage() {
return Card(
color: Colors.cyan[50],
child: SizedBox(
width: 200,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Image.asset("assets/logo.png",height: 22,),
title: Text('BlockSemantics Demo', style: textStyle),
subtitle: Text('by Flutter Devs', style: textStyle),
),
ButtonTheme(
child: ButtonBar(
children: <Widget>[
TextButton(
child: const Text('OK', style: textStyle),
onPressed: () => setState(() { _showMessage = false; }),
),
],
),
),
],
),
),
);
}

When the popup is being displayed and the showSemanticsDebugger is set to true, and 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/rendering.dart';
import 'package:flutter_block_semantics_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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

class BlockSemanticDemo extends StatefulWidget {

@override
State<StatefulWidget> createState() {
return _BlockSemanticDemoState ();
}
}

class _BlockSemanticDemoState extends State<BlockSemanticDemo> {

bool _showMessage = false;
static const TextStyle textStyle = const TextStyle(color: Colors.red);

Widget _buildMessage() {
return Card(
color: Colors.cyan[50],
child: SizedBox(
width: 200,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Image.asset("assets/logo.png",height: 22,),
title: Text('BlockSemantics Demo', style: textStyle),
subtitle: Text('by Flutter Devs', style: textStyle),
),
ButtonTheme(
child: ButtonBar(
children: <Widget>[
TextButton(
child: const Text('OK', style: textStyle),
onPressed: () => setState(() { _showMessage = false; }),
),
],
),
),
],
),
),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter BlockSemantics Demo'),
backgroundColor: Colors.cyan,

),
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 400,
height: 150,
child: Stack(
alignment: Alignment.topCenter,
children: [
Positioned(
bottom: 0,
child: OutlinedButton(
child: Text('Show Message'),
onPressed: () => setState(() { _showMessage = true; }),
),
),
BlockSemantics(
blocking: _showMessage,
child: Visibility(
visible: _showMessage,
child: _buildMessage(),
),
)
],
),
),
],
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the BlockSemantics Widget in a flutter; you can modify this code according to your choice. This was a small introduction to BlockSemantics 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 BlockSemantics in your flutter projects. We will show you what the BlockSemantics is?. Show a constructor and properties of the BlockSemantics. That is how to exclude the semantics of widget subtrees in Flutter. You can utilize BlockSemantics relying upon the case. 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.

Related: Dialog Using GetX in Flutter

Related: Pagination using GetX in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Explore Autocomplete Widget In Flutter

0

Flutter came out a couple of days prior and presents to us an extremely valuable widget called Autocomplete. With this new companion, we presently can rapidly carry out autocomplete text fields without utilizing any outsider party plugins. Making a pursuit field with ideas that show up as the client types something is currently perfect and simple.

In this article, we will Explore Autocomplete Widget In Flutter. We will execute a demo program of the autocomplete and tell you the best way to utilize the widget, including how to set the options, customize the TextField, and handle the choice chose events in your flutter applications.

Autocomplete class – material library – Dart API
A widget for helping the user make a selection by entering some text and choosing from among a list of options. The…api.flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

On the off chance that you have a text field in your Flutter application, for certain cases, it would be pleasant if you can give a list of choices that clients can choose from. Subsequently, the clients don’t have to type the total text and henceforth can further develop the client experience. In Flutter, that should be possible by utilizing Autocomplete widget. It’s a widget that permits the client to type on text enter and choose over a list of choices.

Demo Module :

This demo video shows how to use autocomplete in a flutter. It shows how to autocomplete will work in your flutter applications. It shows when users tap on textfield then will show down some suggestions and yow will also pick up those suggestions. It will be shown on your device.

Constructor:

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

const Autocomplete({
Key? key,
required AutocompleteOptionsBuilder<T> optionsBuilder,
AutocompleteOptionToString<T> displayStringForOption = RawAutocomplete.defaultStringForOption,
AutocompleteFieldViewBuilder fieldViewBuilder =
_defaultFieldViewBuilder,
AutocompleteOnSelected<T>? onSelected,
AutocompleteOptionsBuilder<T>? optionsViewBuilder,
})

The Autocomplete class itself has a generic kind T expands Object. That implies the choice item can be any kind of object, not a string.

Properties:

There are some properties of Autocompleteare:

  • > key: The widget’s key, used to control how a widget is replaced with another widget.
  • > optionsBuilder: Returns the selectable options objects given the current TextEditingValue.
  • > displayStringForOption: Returns the string to be shown for choice.
  • > fieldViewBuilder: Used to construct the field whose info is utilized to get the alternatives. If not given, will construct a standard Material-style text field by default.
  • > onSelected: A function that will be considered when a choice is chosen by the user.
  • > optionsViewBuilder: Used to assemble the selectable options widgets from a list of choices objects.

How to implement code in dart file :

You need to implement it in your code respectively:

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

To start with, we will make a class name Country to be utilized as the choice item.

class Country {

const Country({
required this.name,
required this.size,
});

final String name;
final int size;

@override
String toString() {
return '$name ($size)';
}
}

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

const List<Country> countryOptions = <Country>[
Country(name: 'Africa', size: 30370000),
Country(name: 'Asia', size: 44579000),
Country(name: 'Australia', size: 8600000),
Country(name: 'Bulgaria', size: 110879),
Country(name: 'Canada', size: 9984670),
Country(name: 'Denmark', size: 42916),
Country(name: 'Europe', size: 10180000),
Country(name: 'India', size: 3287263),
Country(name: 'North America', size: 24709000),
Country(name: 'South America', size: 17840000),
];

When calling the constructor, you need to pass Country as the generic type.

Autocomplete<Country>(
// Put the arguments here
)

There is a necessarily named contention optionsBuilder. For that contention, you need to pass a function that returns the list of options that can be chosen by the user. The following are instances of how to make the options builder and pass different contentions upheld by Flutter’s Autocomplete widget.

  • > Set Options Builder:

You can handle the list of choices accessible to browse by making your own AutocompleteOptionsBuilder and pass it as optionsBuilder. The AutocompleteOptionsBuilder is a function that acknowledges a boundary of type TextEditingValue and returns an Iterable of T. By using the passed TextEditingValue, you can filter the list of options to be shown depending on the current text.

optionsBuilder: (TextEditingValue textEditingValue) {
return countryOptions
.where((Country county) => county.name.toLowerCase()
.startsWith(textEditingValue.text.toLowerCase())
)
.toList();
},
  • > Set Displayed String Options:

Of course, Flutter will utilize the toString method for the generic kind as the shown string for every choice, as you can see from the past output. Be that as it may, it’s feasible to set the string to be shown by passing displayStringForOption contention. You need to pass a function that acknowledges a boundary of type T and returns the string that you need to show in the options.

In the code beneath, the function passed as displayStringForOption returns the name property of the Country class.

displayStringForOption: (Country option) => option.name,
  • > Set Field View Builder:

For the text field, Flutter will construct a standard Material-style text field of default. Assuming you need to utilize an altered TextView, you can pass fieldViewBuilder contention. The value for the contention is a function with four boundaries whose types all together are BuildContext, TextEditingController, FocusNode, and VoidCallback. The return kind of the function is a Widget.

The underneath model passes the fieldViewBuilder contention with the passed work returns a TextField with a custom text style.:

fieldViewBuilder: (
BuildContext context,
TextEditingController fieldTextEditingController,
FocusNode fieldFocusNode,
VoidCallback onFieldSubmitted
) {
return TextField(
controller: fieldTextEditingController,
focusNode: fieldFocusNode,
style: const TextStyle(fontWeight: FontWeight.bold),
);
},
  • > Set Options View Builder:

The function should have three boundaries whose types all together are BuildContextAutocompleteOnSelected<T>, and Iterable<T>. The subsequent boundary is the function to be considered when a thing is chosen, while the third boundary is the list of options. The return kind of the function is a Widget.

Generally, you need to utilize the passed options to assemble a list of widgets. Likewise, the Autocomplete widget should be advised when the client chooses an option. To tell the Autocomplete widget, call the AutocompleteOnSelected function and pass the selected item as the contention.

The beneath model makes a custom view for the options by making a ListView wrapped as the child of a Container. Each list item is wrapped as the child of a GestureDetector widget, settling on it conceivable to decision the AutocompleteOnSelected function when a tap gesture happens.

optionsViewBuilder: (
BuildContext context,
AutocompleteOnSelected<Country> onSelected,
Iterable<Country> options
) {
return Align(
alignment: Alignment.topLeft,
child: Material(
child: Container(
width: 300,
color: Colors.cyan,
child: ListView.builder(
padding: EdgeInsets.all(10.0),
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final Country option = options.elementAt(index);

return GestureDetector(
onTap: () {
onSelected(option);
},
child: ListTile(
title: Text(option.name, style: const TextStyle(color: Colors.white)),
),
);
},
),
),
),
);
},
  • > Set On Selected Callback:

At the point when the client chooses an item from the options, you can get the event by passing a callback function as onSelected contention. The callback function acknowledges a boundary of type T and returns void.

onSelected: (Country selection) {
print('Selected: ${selection.name}');
},

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_autocomplete_demo/country_page.dart';
import 'package:flutter_autocomplete_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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


const List<Country> countryOptions = <Country>[
Country(name: 'Africa', size: 30370000),
Country(name: 'Asia', size: 44579000),
Country(name: 'Australia', size: 8600000),
Country(name: 'Bulgaria', size: 110879),
Country(name: 'Canada', size: 9984670),
Country(name: 'Denmark', size: 42916),
Country(name: 'Europe', size: 10180000),
Country(name: 'India', size: 3287263),
Country(name: 'North America', size: 24709000),
Country(name: 'South America', size: 17840000),
];

class AutoCompleteDemo extends StatefulWidget {

@override
State<StatefulWidget> createState() => _AutoCompleteDemoState();
}

class _AutoCompleteDemoState extends State<AutoCompleteDemo> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title:Text('Flutter AutoComplete Demo'),
backgroundColor: Colors.cyan,
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Autocomplete<Country>(
optionsBuilder: (TextEditingValue textEditingValue) {
return countryOptions
.where((Country county) => county.name.toLowerCase()
.startsWith(textEditingValue.text.toLowerCase())
)
.toList();
},
displayStringForOption: (Country option) => option.name,
fieldViewBuilder: (
BuildContext context,
TextEditingController fieldTextEditingController,
FocusNode fieldFocusNode,
VoidCallback onFieldSubmitted
) {
return TextField(
controller: fieldTextEditingController,
focusNode: fieldFocusNode,
style: const TextStyle(fontWeight: FontWeight.bold),
);
},
onSelected: (Country selection) {
print('Selected: ${selection.name}');
},
optionsViewBuilder: (
BuildContext context,
AutocompleteOnSelected<Country> onSelected,
Iterable<Country> options
) {
return Align(
alignment: Alignment.topLeft,
child: Material(
child: Container(
width: 300,
color: Colors.cyan,
child: ListView.builder(
padding: EdgeInsets.all(10.0),
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final Country option = options.elementAt(index);

return GestureDetector(
onTap: () {
onSelected(option);
},
child: ListTile(
title: Text(option.name, style: const TextStyle(color: Colors.white)),
),
);
},
),
),
),
);
},
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Autocomplete Widget in a flutter; you can modify this code according to your choice. This was a small introduction to Autocomplete Widget 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 Autocomplete Widget in your flutter projects. We will show you what the Introduction is?. Show a constructor and properties of the Autocomplete Widget. The AutoComplete widget can be utilized to give a superior user experience to the users by permitting them to choose from a list of qualities. On the off chance that is essential, you can likewise generate the choices dynamically (for example from API response) rather than utilizing static choices like in this article. You can likewise consider utilizing RawAutocomplete which permits you to pass FocusNode and TextEditingController as contentions when utilizing an external field. 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.

find the source code of the Flutter Autocomplete Widget Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Explore FutureBuilder In Flutter

0

In Dart, you can make a function that returns Future if you need to perform asynchronous activities. Some of the time, you might need to build a Flutter widget that relies upon the consequence of a Future. All things considered, you can utilize FutureBuilder. FutureBuilder is a widget that utilizes the result of a Future to build itself. The following are instances of how to utilize the widget.

In this blog, we will be Explore FutureBuilder In Flutter. We will also implement a demo program and we show you how to use FutureBuilder in your flutter applications.

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introducton:

In Flutter, the FutureBuilder Widget is utilized to make widgets dependent on the most recent snapshot of association with a Future. Future needs to be gotten before either through a difference in state or change in dependencies. FutureBuilder is a Widget that will assist you with executing some asynchronous function and based on that function’s outcome your UI will update.

In future builder, it calls the future capacity to wait for the outcome, and when it creates the outcome it calls the builder function where we assemble the widget.

Constructor:

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

const FutureBuilder({
Key? key,
Future<T>? future,
T? initialData,
required AsyncWidgetBuilder<T> builder,
})

The FutureBuilder class has a conventional parameter which is the information type to be returned by the Future. To utilize it, you need to call the constructor which can be seen previously. Fundamentally, what you need to do is construct a widget utilizing a capacity passed as the builder the contention, because of the snapshot of a Future, passed as the future argument.

Parameters:

There are some parameters of FutureBuilderare:

  • Key? key: The widget’s key, used to control how a widget is replaced with another widget.
  • Future<T>? future: A Future whose snapshot can be accessed by the builder function.
  • T? initialData: The data that will be used to create the snapshots until a non-null Future has completed.
  • required AsyncWidgetBuilder<T> builder: The build strategy used by this builder.

How to implement code in dart file :

You need to implement it in your code respectively:

Let’s create a Future:

To start with, we need to make a Future to be passed as the future argument. In this article, we will utilize the capacity beneath, which returns Future<String>

Future<String> getValue() async {
await Future.delayed(Duration(seconds: 3));
return 'Flutter Devs';
}

You should be cautious when passing the Future. In the event that you pass it as the code underneath.

FutureBuilder(
future: getValue(),
// other arguments
),

The getValue function will be considered each time the widget is reconstructed. If you don’t need the function to be considered each time the widget is revamped, you should not make the Future inside State.build or StatelessWidget.build technique. TheFuture should be made before, for instance during State.initStateState.didChangeDependencies, or State.daidUpdateWidget. In the model underneath, the Future is put away in a state variable.

Future<String> _value;

@override
initState() {
super.initState();
_value = getValue();
}

Then, at that point, pass the state variable as the future argument.

FutureBuilder<String>(
future: _value(),
// other arguments
),

Let’s create a AsyncWidgetBuilder

You are needed to pass an AsyncWidgetBuilder function that is utilized to assemble the widget. The function has two boundaries. The main boundary’s sort is BuildContext, while the subsequent boundary’s sort is AsyncSnapshot<T>. You can utilize the value of the subsequent boundary to decide the substance that ought to be delivered.

In the first place, you need to comprehend about AsyncSnapshot. AsyncSnapshot is portrayed as a changeless portrayal of the latest interaction with an asynchronous calculation. For this situation, it addresses the most recent communication with a Future. There are some significant properties AsyncSnapshot that can be helpful. The first is connectionState whose type is ConnectionState enum. It shows the current association state to an asynchronous calculation. In the FutureBuilder’s degree, the asynchronous calculation is the Future.

FutureBuilder<String>(
future: _value,
builder: (
BuildContext context,
AsyncSnapshot<String> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data,
style: const TextStyle(color: Colors.cyan, fontSize: 36)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),

The enum has some possible values:

  • > none: Not connected to any asynchronous computation. It can happen if the future is null.
  • > waiting: Associated with asynchronous calculation and awaiting communication. In this specific situation, it implies the Future hasn’t been finished.
  • > active: Associated with a functioning asynchronous calculation. For instance, if a Stream has returned any value yet is not finished at this point. Ought not to occur for FutureBuilder.
  • > done: Associated with an ended asynchronous calculation. In this unique circumstance, it implies the Future has finished.

Another property you need to know is hasError. It tends to be utilized to show whether the depiction contains a non-null error value. If the last consequence of the asynchronous activity was fizzled, the value will be valid. To check whether the snapshot contains non-null information, you can utilize the hasData property.

The asynchronous activity must be finished with non-null information altogether for the value to turn out to be valid. Nonetheless, if the asynchronous activity finishes without information (for example Future<void>), the value will be false. If the snapshot has data, you can acquire it by getting to the data property.

Because of the value of the properties above, you can figure out what ought to be delivered on the screen. In the code over, a CircularProgressIndicator is shown when the connectionState value is waiting. At the point when the connectionState changes to done, you can check whether the snapshot has an error or data.

Let set the Initial Data:

The constructor of FutureBuilder has a named parameter initialData. It very well may be utilized to pass the data that will be utilized to make the snapshots until a non-null Future has finished. Passing a value as the initialData makes the hasData property have true value toward the start, even before the Future finishes.

You can get to the initial data utilizing the data property. When the Future has finished with a non-invalid value, the value of data will be supplanted with another worth returned by the Future. If the Future finishes with an error, the hasData and data properties will be refreshed to false and invalid individually.

FutureBuilder<String>(
initialData: 'Demo Name'
// other arguments
),

By setting an initial data, the snapshot can have information in any event, when the connection state is as yet waiting. In this manner, we need to change the code above inside the if (snapshot.connectionState == ConnectionState.waiting) block, with the goal that the initial data can be shown when the association state is waiting.

if (snapshot.connectionState == ConnectionState.waiting) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Visibility(
visible: snapshot.hasData,
child: Text(
snapshot.data,
style: const TextStyle(color: Colors.black, fontSize: 24),
),
)
],
);
}

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_futurebuilder_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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

Future<String> getValue() async {
await Future.delayed(Duration(seconds: 3));
return 'Flutter Devs';
}

class FutureBuilderDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _FutureBuilderDemoState ();
}
}

class _FutureBuilderDemoState extends State<FutureBuilderDemo> {

Future<String> _value;

@override
initState() {
super.initState();
_value = getValue();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
title: const Text('Flutter FutureBuilder Demo'),
),
body: SizedBox(
width: double.infinity,
child: Center(
child: FutureBuilder<String>(
future: _value,
initialData: 'Demo Name',
builder: (
BuildContext context,
AsyncSnapshot<String> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Visibility(
visible: snapshot.hasData,
child: Text(
snapshot.data,
style: const TextStyle(color: Colors.black, fontSize: 24),
),
)
],
);
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data,
style: const TextStyle(color: Colors.cyan, fontSize: 36)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the FutureBuilder in a flutter; you can modify this code according to your choice. This was a small introduction to FutureBuilder 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 FutureBuilder in your flutter projects. We will show you what the Introduction is?. Show a constructor and parameters of Streambuilder. That is the way to utilize FutureBuilder in Flutter. You need to make a Future and pass it as the future argument. The snapshots of the Future will be passed to the builder function, in which you can decide the format to be shown depending on the current snapshot. 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.

Related: Explore Exception Handling In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Flutter 2.5 — What’s New In Flutter

0

Google, the search giant recently rolled out the new stable version of its Extensive Popular Cross-Platform UI Framework Flutter. Flutter 2.5 is out with 4600 closed issues and 3932 merged PRs.

Flutter 2.5 & Dart 2.14 have been released at the same time with evidently Substantial Performance Improvements from their contemporary releases. Flutter is release proceeds with a few significant performance and tooling improvements to find performance issues in your own application.

Simultaneously, there are a few new provisions, including full-screen support for Android, more Material You support, updated text editing to help switchable keyboard shortcuts, a new, more definite look at your widgets in the Widget Inspector, new help for adding dependencies in your Visual Studio Code projects, new help for getting inclusion data from your test runs in IntelliJ/Android Studio and a totally different application layout to fill in as a superior establishment for your genuine Flutter applications.


Some of the Key Announcements In Release are ::>

Performance Improvements:

This release accompanies a few performance enhancements. iOS has less jank, burns-through less CPU and power, wiping out jank from this source in our testing, and is more performant now. Additionally, iOS 8 help is deprecated

Frame lag due to processing asynchronous event results before and after

One more reason for jank is the point at which the garbage collector (GC)pauses the UI thread to recover memory. In this release, memory for unused pictures is recovered excitedly, reducing GCs extensively.

GCs before and after adding the fix to eagerly reclaim unused large image memory

One more performance improvement in Flutter 2.5 is the latency when sending messages among Dart and Objective-C/Swift (iOS) or Dart and Java/Kotlin (Android). Eliminating pointless duplicates from messaging codecs diminished latencies by up to half contingent upon message size and device.

iOS message latencies before and after

Dart 2.14:

This release of Flutter comes with Dart 2.14

  • > Apple Silicon support
  • > Dart formatter and cascades
  • > Pub support for ignoring files using.pubignore
  • > Pub is much smarter and faster
  • Flutter Lints is out of the box now.
  • > added a new triple shift operator (>>>)

Breaking changes

  • > Removed support for ECMAScript5
  • > Deprecated dartfmt and dart2native commands, and discontinued stagehand
  • > Deprecated the Dart VM’s Native Extensions

If you want to explore more about Flutter, please visit Announcing Dart 2.14 to get more information.

Announcing Dart 2.14
Apple Silicon support, and improved productivity with default lints, better tools, and new language featuresmedium.com

Framework:

The Flutter 2.5 release includes several fixes and improvements to the framework.

  • > Android full-screen support

Android, has fixed a bunch of related issues around full-screen modes. New features: lean back, sticky, sticky immersive, and edge to edge. This change additionally added an approach to listen to fullscreen changes in different modes.

Normal mode (left), Edge to Edge mode (center), Edge to Edge with a custom SystemUIOverlayStyle (right)
  • > Floating action button sizes updated

As part of Material You, users can configure a larger FloatingActionButton if they choose. With this change a FAB can be configured in 4 sizes: small, regular, large, and extended.

New Material You FAB sizes
  • > MaterialState.scrolledUnder state added to SliverAppBar

Demo::

SliverAppBar(
backwardsCompatibility: false,
elevation: 0,
backgroundColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
return states.contains(MaterialState.scrolledUnder) ? Colors.indigo : Colors.blue;
}),
expandedHeight: 160,
pinned: true,
flexibleSpace: const FlexibleSpaceBar(
title: Text('SliverAppBar'),
),
),
MaterialState.scrolledUnder action
  • > ListView now sends notifications of scrollable areas even if the user isn’t scrolling
scrollbar appearing or disappearing as appropriate based on the underlying size of the ListView
  • > Material banner supports now to the ScaffoldMessenger

In Flutter 2.5, you would now be able to add a banner to the highest point of your scaffold that stays set up until the user dismisses it.

ElevatedButton(
child: const Text('Show MaterialBanner'),
onPressed: () => ScaffoldMessenger.of(context).showMaterialBanner(
MaterialBanner(
content: const Text('Hello, I am a Material Banner'),
leading: const Icon(Icons.info),
backgroundColor: Colors.yellow,
actions: [
TextButton(
child: const Text('Dismiss'),
onPressed: () => ScaffoldMessenger.of(context)
.hideCurrentMaterialBanner(),
),
],
),
),
)

Camera: show some features are –

  • 3795 [camera] android-rework part 1: Base classes to support Android Camera features
  • 3796 [camera] android-rework part 2: Android autofocus feature
  • 3797 [camera] android-rework part 3: Android exposure-related features
  • 3798 [camera] android-rework part 4: Android flash and zoom features
  • 3799 [camera] android-rework part 5: Android FPS range, resolution, and sensor orientation features

Image Picker:

  • 3898 [image_picker] Image picker fix camera device
  • 3956 [image_picker] Change storage location for camera captures to internal cache on Android, to comply with new Google Play storage requirements
  • 4001 [image_picker] Removed redundant request for camera permission
  • 4019 [image_picker] Fix rotation when the camera is a source
  • > battery package moved to battery_plus

Besides, since these plugins are at this point not effectively kept up with, they are as of now not set apart as Flutter Favorite plugins. If you haven’t effectively done as such, we prescribe moving to the in addition to renditions of the accompanying plugins:

Flutter DevTools:

This release of Flutter comes with several improvements to Flutter DevTools. First and foremost is the added support in DevTools to take advantage of engine updates.

  • > Flutter DevTools utilizes these events to assist you with diagnosing shader compilation jank in your application
  • > New CPU Profiler highlight that empowers you to hide profiler data from any of these sources.
  • > Now we can easily distinguish codes with colored bars so that you can easily see what parts of the CPU Frame Chart come from what parts of the system.
  • > This release of DevTools accompanies an update to the Widget Inspector that permits you to hover over a widget to assess the object, view properties, widget state, etc.

When you select a widget, it consequently populates in the new Widget Inspector Console, where you can investigate the widget’s properties.

  • > To make DevTools a more useful destination for comprehension and debugging your Flutter applications.

IntelliJ/Android Studio:

The IntelliJ/Android Studio plugin for Flutter has also undergone several improvements with this release.

  • > Starting with the ability to run integration tests support
  • > The most recent release likewise incorporates the new ability to preview icons utilized from packages from the pub. dev
  • > To empower icon previews you need to tell the plugin which packages you are utilizing. There is another text field on the plugin settings/preferences page

Visual Studio Code:

  • > We can add dependencies without leave the VS Code now
  • > You may also be interested in the “Fix All” command. This can also be set to run on-save by adding source.fixAll to the editor.codeActionsOnSave VS Code setting.
  • > VS Code has new test runner integration it’s as yet under see. You need to empower the dart.previewVsCodeTestRunner in settings.
  • > The Visual Studio Code test runner also adds new gutter icons showing the last state of a test that can be clicked to run the test.

Tools:

  • > Flutter has a new template skeleton

Uses ChangeNotifier to coordinate multiple widgets

Generates localizations by default using arb files

Includes an example image and establishes 1x, 2x, and 3x folders for image assets

Uses a “feature-first” folder organization

Supports shared preferences

Supports light and dark theming

Supports navigation between multiple pages

  • > Pigeon is v1.0 now

A Pigeon is a codegen apparatus for creating typesafe interop code among Flutter and its host stage. It permits you to characterize a depiction of your plugin’s API and produce skeleton code for Dart, Java, and Objective-C

Conclusion:

In Flutter 2.5— Apparently Described as the biggest release with the 2nd highest stats Flutter history. The update release has created an igniting spark among the mobile developer’s Community by focussing well on varied Important Aspects.

Though Each New Release Certainly Brings with In Increased usage and momentum It can be easily seen that the 4600 issues closed and 3932 PRs merged from 252 contributors with 216 reviewers. If we look back over the last year, we see a huge 21,072 PRs created by 1337 contributors, of which 15,172 of them were merged.

What makes it more special for us is that Our Country, India now being the #1 region for Flutter developers, having doubled in the last six months

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


References For the Blog :

For detailed information, you definitely check this official article out

What’s new in Flutter 2.5
Performance improvements, DevTools updates, new Material You support, a new app template, and more!medium.com


From Our Parent Company Aeologic

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

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

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

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

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Cupertino Sliding Segmented Control In Flutter

0

A segmented control is a direct arrangement of at least two fragments that function as a totally unrelated button. Inside the control, all sections are equivalent in width. Like buttons, segments can contain text or pictures. Segmented controls are frequently used to show various perspectives.

In this blog, we will explore the Cupertino Sliding Segmented Control In Flutter. We will see how to implement a Cupertino sliding segmented control demo program and show how to create it in your flutter applications.

CupertinoSlidingSegmentedControl class – cupertino library – Dart API
An iOS 13 style segmented control. Displays the widgets provided in the Map of children in a horizontal list. It allows…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

Showcases the widgets gave in the Map of children in a horizontal list. It permits the client to choose between various totally unrelated alternatives, by tapping or hauling inside the segmented control.

A segmented control can include any Widget as one of the qualities in its Map of children. The sort T is the kind of the Map keys used to recognize every widget and figure out which widget is chosen.

Demo Module :

The above demo video shows how to create a Cupertino sliding segmented control in a flutter. It shows how the Cupertino sliding segmented control will work in your flutter applications. It shows when the code successfully runs, then the user sliding button, then the content was highlighted, and also the user was tapping content highlighted then button also move. It will be shown on your devices.

Constructor:

There are constructor of CupertinoSlidingSegmentedControl are:

CupertinoSlidingSegmentedControl({
Key? key,
required this.children,
required this.onValueChanged,
this.groupValue,
this.thumbColor = _kThumbColor,
this.padding = _kHorizontalItemPadding,
this.backgroundColor = CupertinoColors.tertiarySystemFill,
})

The constructor expects you to compulsory required children and onValueChanged.

Properties:

There are some properties of CupertinoSlidingSegmentedControl are:

  • > onValueChanged: This property is used to the callback that is called when a new option is tapped.
  • > groupValue: This property is used to the identifier of the widget that is currently selected.
  • > thumbColor: This property is used to the color used to paint the interior of the thumb that appears behind the currently selected item.
  • > backgroundColor: This property is used to the color used to paint the rounded rect behind the children and the separators.
  • > children: This property is used to identify keys and corresponding widget values in the segmented control.

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 an integer variable groupvalue is equal to zero.

int? groupValue = 0;

In the body, we will add a Container widget. Inside, we will add alignment was center, add padding and its child property, add a CupertinoSlidingSegmentedControl() method. In this method, we will add a background color, thumbcolor, padding, group value, and its children, we will add the buildSegment() widget. We will deeply define below the code. Also, we will add the onValueChanged property. In this property, we will add setState() function. In this function, we will add groupValue is equal to the value.

Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
child: CupertinoSlidingSegmentedControl<int>(
backgroundColor: CupertinoColors.white,
thumbColor: CupertinoColors.activeGreen,
padding: EdgeInsets.all(8),
groupValue: groupValue,
children: {
0: buildSegment("Flutter"),
1: buildSegment("React"),
2: buildSegment("Native"),
},
onValueChanged: (value){
setState(() {
groupValue = value;
});
},
),
),

We will define the buildSegment() widget

In this buildSegment widget, we will return a Container. Inside, we will add text with color, and fontSize.

Widget buildSegment(String text){
return Container(
child: Text(text,style: TextStyle(fontSize: 22,
color: Colors.black),),
);
}

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/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_sliding_segmented_demo/splash_screen.dart';

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

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

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {
int? groupValue = 0;

@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Cupertino Sliding Segmented Control Demo",
style: TextStyle(fontSize: 19),),
),
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
child: CupertinoSlidingSegmentedControl<int>(
backgroundColor: CupertinoColors.white,
thumbColor: CupertinoColors.activeGreen,
padding: EdgeInsets.all(8),
groupValue: groupValue,
children: {
0: buildSegment("Flutter"),
1: buildSegment("React"),
2: buildSegment("Native"),
},
onValueChanged: (value){
setState(() {
groupValue = value;
});
},
),
),
);

Widget buildSegment(String text){
return Container(
child: Text(text,style: TextStyle(fontSize: 22,
color: Colors.black),),
);
}

}

Conclusion:

In the article, I have explained the basic structure of the Cupertino Sliding Segmented Control in a flutter; you can modify this code according to your choice. This was a small introduction to Cupertino Sliding Segmented Control 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 Cupertino Sliding Segmented Control in your flutter projects. We will show you what the Introduction is?. Show constructor and properties of the Cupertino Sliding Segmented Control. Make a demo program for working Cupertino Sliding Segmented Control and It shows when the code successfully runs, then the user sliding button, then the content was highlighted, and also the user was tapping content highlighted then button also move. 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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Cupertino Alert Dialog In Flutter

0

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 a Cupertino Alert dialog box for straightforward pop-up messages in which are shown.

In this blog, we will explore the Cupertino Alert Dialog In Flutter. We will see how to implement a Cupertino alert dialog demo program and show how to create it in your flutter applications.

Table Of Contents::

Cupertino Alert Dialog

Properties

Code Implement

Code File

Conclusion



Cupertino Alert Dialog:

The CupertinoAlertDialog class is utilized to make a Cupertino alert dialog. Action button that appears as though a standard iOS dialog button, can be made utilizing CupertinoDialogAction. This dialog can be shown utilizing showDialog() a capacity. In any case, there is another capacity showCupertinoDialog() that shows a dialog with an iOS-style passage and exit animations.

Demo Module :

This demo video shows how to create a Cupertino alert dialog in a flutter. It shows how the Cupertino alert dialog will work in your flutter applications. It shows how the Cupertino alert dialog will work when the user taps the button, then the pop-up dialog shows. It will be shown on your device.

Properties:

There are some properties of Cupertino alert dialog are:

  • > title: This property was optional. The title of the dialog is displayed in a large font at the top of the dialog.
  • > content: This property was optional. The content of the dialog is displayed in the center of the dialog in a lighter font.
  • > actions: This property was also optional.The set of actions that are displayed at the bottom of the dialog.
  • > scrollController: This property is used as a scroll controller that can be used to control the scrolling of the content in the dialog.
  • > actionScrollController: This property is used as a scroll controller that can be used to control the scrolling of the actions in the dialog.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the body, we will add the Column widget. Inside the widget, we will add mainAxisAlignment and crossAxisAlignment will be center. Also, we will add an image from the assets folder. We will add RaisedButton() with color and onPressed Function. In this function, we will add _showDialog(context). We will deeply define the below code. It’s child property, we will add the text ‘Show AlertDialog’.

Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset("assets/logo.png",scale: 12,),
SizedBox(height: 50,),
RaisedButton(
color: Colors.green[100],
onPressed: () {
_showDialog(context);
},
child: Text('Show AlertDialog'),
),
],
),

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

Home Page Screen

We will deeply define _showDialog(context):

We will create a _showDialog() method. In this method, we will add showDialog(). Inside the dialog, we will add context and CupertinoAlertDialog() function. In this function, we will add a title that means the user wants to add any title, content means the user displays any data at the center of the dialog. Also, we will add actions: <Widget>. Inside, we will add three CupertinoDialogAction() with different text.

_showDialog(BuildContext context){
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Column(
children: <Widget>[
Text("CupertinoAlertDialog"),
Icon(
Icons.favorite,
color: Colors.red,
),
],
),
content: new Text( "An iOS-style alert dialog."+
"An alert dialog informs the user about situations that require acknowledgement."
" An alert dialog has an optional title, optional content, and an optional list of actions."),
actions: <Widget>[
CupertinoDialogAction(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},),
CupertinoDialogAction(
child: Text("CANCEL"),
onPressed: () {
Navigator.of(context).pop();
},),
CupertinoDialogAction(
child: Text("MAY BE"),
onPressed: () {
Navigator.of(context).pop();
},),
],
));
}

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/cupertino.dart';

class HomePage extends StatelessWidget {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Flutter Cupertino Alert Dialog Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset("assets/logo.png",scale: 12,),
SizedBox(height: 50,),
RaisedButton(
color: Colors.green[100],
onPressed: () {
_showDialog(context);
},
child: Text('Show AlertDialog'),
),
],
),
),
);
}

_showDialog(BuildContext context){
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Column(
children: <Widget>[
Text("CupertinoAlertDialog"),
Icon(
Icons.favorite,
color: Colors.red,
),
],
),
content: new Text( "An iOS-style alert dialog."+
"An alert dialog informs the user about situations that require acknowledgement."
" An alert dialog has an optional title, optional content, and an optional list of actions."),
actions: <Widget>[
CupertinoDialogAction(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},),
CupertinoDialogAction(
child: Text("CANCEL"),
onPressed: () {
Navigator.of(context).pop();
},),
CupertinoDialogAction(
child: Text("MAY BE"),
onPressed: () {
Navigator.of(context).pop();
},),
],
));
}
}

Conclusion:

In the article, I have explained the basic structure of the Cupertino Alert Dialog in a flutter; you can modify this code according to your choice. This was a small introduction to Cupertino Alert 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 Cupertino Alert Dialog in your flutter projects. We will show you what the Cupertino Alert Dialog is?. Show some properties of the Cupertino Alert Dialog. That is an illustration of how to make Cupertino Alert Dialog. Make a demo program for working Cupertino Alert Dialog and it shows pop-up dialog 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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Flow Widget In Flutter

0

At whatever point you will code for building anything in Flutter, it will be inside a widget. The focal design is to fabricate the application out of widgets. It depicts how your application view should look with their present design and state. At the point when you made any modification in the code, the widget remakes its depiction by figuring the distinction between the past and current widgets to decide the negligible changes for delivering in the UI of the application.

In this blog, we will explore the Flow Widget In Flutter. We will see how to implement a demo program to make a layout containing a floating menu that can expand/collapse using the Flow widget and how to use it in your flutter applications.

Table Of Contents::

Flow Widget

Constructor

Parameters

Code Implement

Code File

Conclusion



Flow Widget:

Flow is a widget that sizes and positions its children proficiently as indicated by the rationale of a FlowDelegate. This widget is helpful when the children should be repositioned utilizing change matrices. For instance, if you need to make an animation that changes the situation of the children.

Demo Module :

The above demo video shows how to create a floating menu in a flutter. It shows how the floating menu that can expand/collapse using the Flow widget will work in your flutter applications. It shows when the code successfully runs, the user presses the menu button, then all icons will be expanded and the user press again, then all icons will collapse. It will be shown on your devices.

Constructor:

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

Flow({
Key key,
@required this.delegate,
List<Widget> children = const <Widget>[],
})

To make an example of Flow, the only required contention is delegate. You need to pass a FlowDelegate which is capable to control the presence of the flow design.

Parameters:

There are some parameters of Floware:

  • Key key: This parameter is used to control how a widget is replaced with another widget.
  • FlowDelegate delegate : This parameter is used by the delegate that controls the transformation matrices of the children.
  • List<Widget> children: This parameter is used to the widgets below this widget in the tree.

How to implement code in dart file :

You need to implement it in your code respectively:

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

To make an instance of FlowDelegate, you need to make a custom class that expands FlowDelegate. The custom class needs to call the super constructor which is a const constructor. It has one boundary whose type is Listenable. It’s entirely expected to pass an example of Animation as the Listenable. Bypassing an Animation will pay attention to the animation and repaint at whatever point the animation ticks.

class FlowDemoDelegate extends FlowDelegate {

FlowDemoDelegate({this.myAnimation}) : super(repaint: myAnimation);

final Animation<double> myAnimation;
}

Other than calling the constructor, there are a few techniques you can supersede, two of them should be overridden since they don’t have a default execution. paintChild should be called for painting every child dependent on the given change grid. The principal boundary i is the record of the child to be painted. You can paint the children at any request, however, every child must be painted once. A child’s situation relies upon the consequence of the holder’s arrange framework connected with the given change lattice. The upper left corner is set to be the beginning of the parent’s arrange framework. The value of x is expanding rightward, while the worth of y is expanding lower.

The size and childCount properties just as the getChildSize strategy may be valuable inside the FlowDelegate’s paintChildren technique. For instance, if you need to perform a loop dependent on the number of children or interpret the situation of a child dependent on its size.

import 'package:flutter/material.dart';

class FlowDemoDelegate extends FlowDelegate {

FlowDemoDelegate({this.myAnimation}) : super(repaint: myAnimation);

final Animation<double> myAnimation;

@override
bool shouldRepaint(FlowDemoDelegate oldDelegate) {
return myAnimation != oldDelegate.myAnimation;
}

@override
void paintChildren(FlowPaintingContext context) {
for (int i = context.childCount - 1; i >= 0; i--) {
double dx = (context.getChildSize(i).height + 10) * i;
context.paintChild(
i,
transform: Matrix4.translationValues(0, dx * myAnimation.value + 10, 0),
);
}
}

@override
Size getSize(BoxConstraints constraints) {
return Size(70.0, double.infinity);
}

@override
BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) {
return i == 0 ? constraints : BoxConstraints.tight(const Size(50.0, 50.0));
}
}

The other technique that you need to supersede is shouldRepaint. The bool return value of the strategy is utilized to decide if the children should be repainted. The technique has a boundary that will be passed with the old instance of the delegate. Along these lines, you can look at the fields of the past occurrence with the current fields to decide if repainting ought to be performed.

Having made the custom FlowDelegate class, presently we can call the constructor of Flow. For the delegate argument, pass an occurrence of FlowDemoDelegate. Since the constructor of FlowDemaoDelegate requires an occasion of Animation, we need to make an Animation.

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

In the first, add with SingleTickerProviderStateMixin in the revelation of the state class. Thusly, it becomes conceivable to get the TickerProvider which is required when calling the constructor of AnimationController.

class _FlowDemoState extends State<FlowDemo>
with SingleTickerProviderStateMixin {

AnimationController _myAnimation;
...
}

Now, we will add List of IconData

final List<IconData> _icons = <IconData>[
Icons.menu,
Icons.email,
Icons.settings,
Icons.notifications,
Icons.person,
Icons.wifi,
];

We will create initState() method. In this method, we will add _myAnimation is equal to the AnimationController().

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

_myAnimation = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
);
}

We will deeply define _buildItem widget are:

In this widget, we will return Padding(). Inside, add a RawMaterialButton() with fillColor, shape, BoxConstraints is tight and onPressed() function. In this function, we will add _myAnimation.status is qual to AnimationStatus.completed then show _myAnimation.reverse() else show a _myAnimation.forward(). Its child property, we will show a icon.

Widget _buildItem(IconData icon) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RawMaterialButton(
fillColor: Colors.cyan,
shape: CircleBorder(),
constraints: BoxConstraints.tight(Size.square(50.0)),
onPressed: () {
_myAnimation.status == AnimationStatus.completed
? _myAnimation.reverse()
: _myAnimation.forward();
},
child: Icon(
icon,
color: Colors.white,
size: 30.0,
),
),
);
}

In the body, we will add to changing the size of the Flow widget, you may likewise have to change how the widget ought to be spread out comparative with different widgets. Generally, you can wrap it as the child of another widget. For instance, you can use the Align widget to set the alignment or use the Stack widget to make the button floating above different widgets.

Stack(
children: [
Container(color: Colors.grey[200]),
Flow(
delegate: FlowDemoDelegate(myAnimation: _myAnimation),
children: _icons
.map<Widget>((IconData icon) => _buildItem(icon))
.toList(),
),
],
),

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/widgets.dart';
import 'package:flutter_flow_demo/flow_demo_delegate.dart';
import 'package:flutter_flow_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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

class FlowDemo extends StatefulWidget {

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

class _FlowDemoState extends State<FlowDemo>
with SingleTickerProviderStateMixin {

AnimationController _myAnimation;

final List<IconData> _icons = <IconData>[
Icons.menu,
Icons.email,
Icons.settings,
Icons.notifications,
Icons.person,
Icons.wifi,
];

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

_myAnimation = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
);
}

Widget _buildItem(IconData icon) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RawMaterialButton(
fillColor: Colors.cyan,
shape: CircleBorder(),
constraints: BoxConstraints.tight(Size.square(50.0)),
onPressed: () {
_myAnimation.status == AnimationStatus.completed
? _myAnimation.reverse()
: _myAnimation.forward();
},
child: Icon(
icon,
color: Colors.white,
size: 30.0,
),
),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Flow Widget Demo'),
backgroundColor: Colors.cyan,
),
body: Stack(
children: [
Container(color: Colors.grey[200]),
Flow(
delegate: FlowDemoDelegate(myAnimation: _myAnimation),
children: _icons
.map<Widget>((IconData icon) => _buildItem(icon))
.toList(),
),
],
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Flow Widget in a flutter; you can modify this code according to your choice. This was a small introduction to Flow Widget 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 Flow Widget in your flutter projects. We will show you what the Flow Widget is?. Show a constructor and parameters of the Flow Widget. The Flow widget is appropriate when you need to make an animation that repositions the children. It can make the cycle more proficient because it just requirements to repaint at whatever point the animation ticks. Hence, the build and design periods of the pipeline can be kept away from. To utilize the Flow widget, you need to comprehend FlowDelegate since the rationale of how to paint the children generally should be characterized inside a class that extends FlowDelegate. 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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Explore Size & Position Widget In Flutter

0

Once in a while, you might have to know the size and position of a widget rendered on the screen automatically. For instance, if you need to control child widget dependent on the parent’s size and location. In Flutter, that data can be gotten from the RenderBox of the individual widget.

In this blog, we will be Explore Size & Position Widget In Flutter. We will see how to implement a demo program of the size & position widget and how to get the size and position of a widget in your flutter applications.

Table Of Contents::

Flutter

Code Implement

Code File

Conclusion



Flutter:

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time ”

It is free and open-source. It was at first evolved from 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-arranged into JavaScript code.

If you want to explore more about Flutter, please visit Flutter’s official website to get more information.

Flutter Is Proudly Entrusted By These Organizations For their Products : — Flutter Showcase


Demo Module :

This demo video shows how to get the size and position of a widget in a flutter. It shows how the size and position widget will work in your flutter applications. It shows when the user taps on the button, then the size of the animated container will be changed. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

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

The strategy expects you to return a RenderObject and you can make your own RenderObject by making a class that expands RenderProxyBox. You need to supersede the performLayout strategy for the RenderProxyBox to get the RenderBox which can be utilized to get the size of the child.

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

typedef void OnWidgetSizeChange(Size size);

class SizeRenderObject extends RenderProxyBox {

final OnWidgetSizeChange onSizeChange;
Size? currentSize;

SizeRenderObject(this.onSizeChange);

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

try {
Size? newSize = child?.size;

if (newSize != null && currentSize != newSize) {
currentSize = newSize;
WidgetsBinding.instance?.addPostFrameCallback((_) {
onSizeChange(newSize);
});
}
} catch (e) {
print(e);
}
}
}

There is a callback function passed to the RenderProxyBox. Inside the performLayout widget, you need to get the child’s size and call the callback if the current size is not quite the same as the past size.

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

It very well may be finished by wrapping the widget as the child of another widget that expands SingleChildRenderObjectWidget. Extending out the class expects you to supersede the createRenderObject strategy.

import 'package:flutter/material.dart';
import 'package:flutter_size_position/size_render_object.dart';

class SizeOffsetWrapper extends SingleChildRenderObjectWidget {

final OnWidgetSizeChange onSizeChange;

const SizeOffsetWrapper({
Key? key,
required this.onSizeChange,
required Widget child,
}) : super(key: key, child: child);

@override
RenderObject createRenderObject(BuildContext context) {
return SizeRenderObject(onSizeChange);
}
}

Then, at that point, pass the widget to be estimated as the child of the SizeOffsetWrapper alongside a callback function that will be summoned when the size changes.

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

We will create a double _size variable is equal to 250.

double _size = 250;

In the body, we will add the Stack widget. In this widget, we will add SizeOffsetWrapper(). In this method, we will add onSizeChange and add AnimatedContainer() with duration, width, height, and color.

Stack(
children: [
Center(
child: SizeOffsetWrapper(
onSizeChange: (Size size) {
print('Size: ${size.width}, ${size.height}');
},
child: AnimatedContainer(
duration: const Duration(seconds: 3),
width: _size,
height: _size,
color: Colors.cyan,
),
),
),
],
),

In Stack, we will also add a Container with decoration and text. It also wraps on its InkWell() method. In this method, we will add the setState() method. The whole widget will be a wrap on Positioned() widget. When the user presses the button, the container size was changed.

Positioned(
bottom: 100,
left: 70,
right: 70,
child: InkWell(
onTap: (){
setState(() {
_size = _size == 250 ? 50 : 250;
});
},
child: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.black
),
child: Text('Change size',style: TextStyle(color: Colors.white,
fontSize: 16),
),
),
),
),

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/rendering.dart';
import 'package:flutter_size_position/size_offset_wrapper.dart';
import 'package:flutter_size_position/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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


class WidgetSizeAndPositionDemo extends StatefulWidget {

@override
State<StatefulWidget> createState() {
return _WidgetSizeAndPositionDemoState();
}
}
class _WidgetSizeAndPositionDemoState extends State<WidgetSizeAndPositionDemo> {

double _size = 250;

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Widget Size & Position Demo'),
backgroundColor: Colors.cyan,
),
body: Stack(
children: [
Center(
child: SizeOffsetWrapper(
onSizeChange: (Size size) {
print('Size: ${size.width}, ${size.height}');
},
child: AnimatedContainer(
duration: const Duration(seconds: 3),
width: _size,
height: _size,
color: Colors.cyan,
),
),
),
Positioned(
bottom: 100,
left: 70,
right: 70,
child: InkWell(
onTap: (){
setState(() {
_size = _size == 250 ? 50 : 250;
});
},
child: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.black
),
child: Text('Change size',style: TextStyle(color: Colors.white,
fontSize: 16),
),
),
),
),
],
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Size & Position Widget in a flutter; you can modify this code according to your choice. This was a small introduction to Size & Position Widget 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 Size & Position Widget in your flutter projectsThat’s how to get the size and position of a widget rendered on the screen. Make a demo program for working Size & Position Widget and shows when the user taps on the button, then the size of the animated container will be changed. 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.


Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Exploring Custom Radio Button In Flutter

0

A radio button is otherwise called the choices button which holds the Boolean value. It permits the client to pick just a single choice from a predefined set of choices. This component makes it not quite the same as a checkbox where we can choose more than one alternative and the unselected state to be reestablished. We can organize the radio button in a gathering of at least two and show it on the screen as circular holes with the white area (for unselected) or a dot (for chose).

We can likewise give a label to each relating radio button portraying the decision that the radio button addresses. A radio button can be chosen by tapping the mouse on the circular hole or utilizing a console alternate way.

In this blog, we will be Exploring Custom Radio Button In Flutter. We will see how to implement a custom radio button demo program and how to create in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

Flutter permits us to make radio buttons by utilizing the Radio widget. A radio button made with that widget comprises of a void external circle and a strong internal circle, with the last just displayed in the, chose state. Now and again, you might need to make a radio gathering whose alternatives utilize a custom design, not the traditional radio catch. This article gives an illustration of how to make a radio gathering with custom catches.

Demo Module :

This demo video shows how to create a custom radio button in a flutter. It shows how the custom radio button will work in your flutter applications. It shows how the radio group will work with custom buttons when the user taps the button. animated. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

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

Since the radio button contains a label, we can’t utilize the Radio button. All things considered, we will make a custom class that can be utilized the make the choices called MyRadioOption. Motivated by Flutter’s Radio widget, the class has valuegroupValue, and onChanged properties. The value the property addresses the value of the alternative, it ought to be extraordinary among all choices in a similar group.

The groupValue property is the currently selected value. If an option value matches the groupvalue, the option is in the selected state. The onChanged property stores the callback function that will be called when the user selects an option. When a user selects an option, it’s the responsibility of the callback function to update the groupValue. In addition, we also add label and text properties because we need to display a label on the button and a text on the right side of the button.

The groupValue property is the presently chosen value. If a choice value matches the groupvalue, the alternative is in the selected state. The onChanged property stores the callback function that will be considered when the client chooses a choice. At the point Final Outputwhen a client chooses an alternative, it’s the obligation of the callback function to update the groupValue. Moreover, we likewise add label and text properties since we need to show a name on the button and content on the right side of the button.

The following are the properties and the constructor of the class. We utilize a conventional kind T on the grounds that the value can be any sort.

class MyRadioOption<T> extends StatelessWidget {

final T value;
final T? groupValue;
final String label;
final String text;
final ValueChanged<T?> onChanged;

const MyRadioOption({
required this.value,
required this.groupValue,
required this.label,
required this.text,
required this.onChanged,
});

@override
Widget build(BuildContext context) {
// TODO implement
}
}

Then, we will make the layout. The button is a circle with a name inside. For making the circle, make a Container that utilizes a ShapeDecoration with a CircleBorder as the shape. The name can be made utilizing a Text a widget that is put as the child of the Container. Then, at that point, we can make a Row that comprises the button and a Text widget.

import 'package:flutter/material.dart';

class MyRadioOption<T> extends StatelessWidget {

final T value;
final T? groupValue;
final String label;
final String text;
final ValueChanged<T?> onChanged;

const MyRadioOption({
required this.value,
required this.groupValue,
required this.label,
required this.text,
required this.onChanged,
});

Widget _buildLabel() {
final bool isSelected = value == groupValue;

return Container(
width: 30,
height: 30,
decoration: ShapeDecoration(
shape: CircleBorder(
side: BorderSide(
color: Colors.black,
),
),
color: isSelected ? Colors.cyan : Colors.white,
),
child: Center(
child: Text(
value.toString(),
style: TextStyle(
color: isSelected ? Colors.white : Colors.cyan,
fontSize: 20,
),
),
),
);
}

Widget _buildText() {
return Text(
text,
style: const TextStyle(color: Colors.black, fontSize: 24),
);
}

@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(8),
child: InkWell(
onTap: () => onChanged(value),
splashColor: Colors.cyan.withOpacity(0.5),
child: Padding(
padding: EdgeInsets.all(5),
child: Row(
children: [
_buildLabel(),
const SizedBox(width: 10),
_buildText(),
],
),
),
),
);
}
}

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

The following is a class where we make a radio group utilizing the MyRadioOption as the choice. There is a state variable _groupValue and a ValueChanged function which is the callback to be considered when the client chooses an alternative.

String? _groupValue;

ValueChanged<String?> _valueChangedHandler() {
return (value) => setState(() => _groupValue = value!);
}

In the body, how to call the constructor of MyRadioOption.

MyRadioOption<String>(
value: '1',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '1',
text: 'Phone Gap',
),
MyRadioOption<String>(
value: '2',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '2',
text: 'Appcelerator',
),

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_custom_radio_button/radio_option.dart';

class CustomRadioDemo extends StatefulWidget {

@override
State createState() => new _CustomRadioDemoState();
}

class _CustomRadioDemoState extends State<CustomRadioDemo> {

String? _groupValue;

ValueChanged<String?> _valueChangedHandler() {
return (value) => setState(() => _groupValue = value!);
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Custom Radio Button Demo'),
backgroundColor: Colors.cyan,
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Text("Best Cross-Platform Mobile App Development Tools for 2021",
style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
),
SizedBox(height: 10,),
MyRadioOption<String>(
value: '1',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '1',
text: 'Phone Gap',
),
MyRadioOption<String>(
value: '2',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '2',
text: 'Appcelerator',
),
MyRadioOption<String>(
value: '3',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '3',
text: 'React Native',
),
MyRadioOption<String>(
value: '4',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '4',
text: 'Native Script',
),
MyRadioOption<String>(
value: '5',
groupValue: _groupValue,
onChanged: _valueChangedHandler(),
label: '5',
text: 'Flutter',
),
],
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Custom Radio Button in a flutter; you can modify this code according to your choice. This was a small introduction to Custom Radio Button 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 Custom Radio Button in your flutter projects. We will show you what the Introduction is?. That is an illustration of how to make custom radio buttons. Fundamentally, every alternative should have value and group value. The group value should be something very similar among all alternatives in a similar group. The group value is updated when a client chooses an alternative, 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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Exploring BlurHash Image Placeholder In Flutter

0

Stacking a picture from the network might require a couple of moments to finish, contingent upon the association speed. While the picture is being fetched, it’s entirely expected to show a placeholder. There are a few strategies for showing a placeholder. For instance, you can show a colored box. In any case, it would be more pleasant if the placeholder can be like the real picture. For that reason, you can utilize BlurHash.

In this blog, we will be Exploring BlurHash Image Placeholder In Flutter. We will see how to implement a demo program of the blur hash and how to use BlurHash as an image placeholder using the flutter_blurhash package in your flutter applications.

flutter_blurhash | Flutter Package
Compact representation of a placeholder for an image. You can use https://blurha.sh/ for testing or use any official…pub.dev

Table Of Contents::

Introduction

Constructor

Parameters

Implementation

Code Implement

Code File

Conclusion



Introduction:

BlurHash is a conservative portrayal of a placeholder for a picture. It works by producing a hash string from a picture. The produced hash string will be utilized to deliver the placeholder. This article tells the best way to disentangle the BlurHash string to be delivered as a picture placeholder in a Flutter application.

Demo Module :

This demo video shows how to use a blurhash in a flutter. It shows how the blurhash will work using the flutter_blurhash package in your flutter applications. It shows a compact representation of a placeholder for an image. It will be shown on your device.

Constructor:

There are constructor of BlurHash are:

const BlurHash({
required this.hash,
Key? key,
this.color = Colors.blueGrey,
this.imageFit = BoxFit.fill,
this.decodingWidth = _DEFAULT_SIZE,
this.decodingHeight = _DEFAULT_SIZE,
this.image,
this.onDecoded,
this.onReady,
this.onStarted,
this.duration = const Duration(milliseconds: 1000),
this.curve = Curves.easeOut,
})

The constructor expects you to pass a boundary hash which is the hash string figured utilizing the BlurHash algorithm. On the off chance that you don’t as of now have the hash string, you can utilize their authority site blurha. sh to create the hash string from the picture that you need to utilize.

Parameters:

There are some parameters of BlurHash are:

  • > hash: This parameter is required. The hash to decode.
  • > onDecoded: This parameter is used to callback when the hash is decoded.
  • > image: This parameter is used to remote resources to download.
  • > imageFit: This parameter is used how to fit decoded & downloaded images.
  • > color: This parameter is used to displayed background color before decoding.
  • > duration: This parameter is used for animation duration. Defaults to const Duration(milliseconds: 1000).
  • > curve: This parameter is used to animation curve. Defaults to Curves.easeOut.
  • > onStarted: This parameter is used to callback to be called when the download starts.
  • > onReady: This parameter is used to callback when the image is downloaded.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

flutter_blurhash:

Step 2: Import

import 'package:flutter_blurhash/flutter_blurhash.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.

The following is a model which just passes the hash argument. Since the Image argument isn’t passed, it will show the placeholder until the end of time.

BlurHash(
hash: 'LHA-Vc_4s9ad4oMwt8t7RhXTNGRj',
),

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

BlurHash with the hash argument

In the body, we will add BlurHash() method. In this method, we will add imagefit implies you can set how to fit the image to the accessible space by passing an BoxFit enum as the imageFit the argument to the constructor. If you don’t pass the argument, the worth defaults to BoxFit.fill. The use of imageFit contention is like the fit property of FittedBox. Presently, we will add duration implies after the picture has been effectively downloaded, the picture will be enlivened for a given term before totally shown. The duration can be set by passing Duration esteem as the duration contention. The default value if you don’t pass the argument is 1 second.

BlurHash(
imageFit: BoxFit.fitWidth,
duration: const Duration(seconds: 4),
curve: Curves.bounceInOut,
hash: 'LHA-Vc_4s9ad4oMwt8t7RhXTNGRj',
image: 'https://images.unsplash.com/photo-1486072889922-9aea1fc0a34d?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bW91dGFpbnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60',
),

Now, we will set the curve means the animation curve can be set by passing curve argument. The default value is Curves.easeOut. Finally, we will add image means where the image argument is passed with a remote URL of an image as the value. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Presently, we will set the curve implies the animation curve can be set by passing curve argument. The default esteem is Curves.easeOut. At long last, we will add an image implies where the image argument is passed with a distant URL of a picture as the value. 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_blur_hash_demo/splash_screen.dart';
import 'package:flutter_blurhash/flutter_blurhash.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class BlurHashDemo extends StatelessWidget {
@override
Widget build(BuildContext context) =>
Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
automaticallyImplyLeading: false,
title: Text("Flutter BlurHash Demo")
),
body: Center(
child: BlurHash(
imageFit: BoxFit.fitWidth,
duration: const Duration(seconds: 4),
curve: Curves.bounceInOut,
hash: 'LHA-Vc_4s9ad4oMwt8t7RhXTNGRj',
image: 'https://images.unsplash.com/photo-1486072889922-9aea1fc0a34d?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bW91dGFpbnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60',
),
),
);
}

Conclusion:

In the article, I have explained the basic structure of the BlurHash Image Placeholder in a flutter; you can modify this code according to your choice. This was a small introduction to BlurHash Image Placeholder 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 BlurHash Image Placeholder in your flutter projects. We will show you what the Introduction is?, the constructor, some parameters using in BlurHash, and make a demo program for working BlurHash. That’s how to decode a BlurHash-encoded value to be displayed as an image placeholder. It can be done easily using the flutter_blurhash 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.

Related: Octo Image In Flutter

Related: Image Compress & Crop In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.