Google search engine
Home Blog Page 19

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.


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.


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.


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.


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.


Draggable Floating Action Button In Flutter

0

Flutter permits you to add a floating action button utilizing the FloatingActionButton widget. Nonetheless, it doesn’t permit you to drag the button. Consider the possibility that you need to make it draggable. This article has a model that discloses what you need to do to make a floating action button that can be hauled anyplace around the screen as long as it’s inside the parent widget.

In this blog, we will explore the Draggable Floating Action Button In Flutter. We will see how to implement a demo program of the draggable floating action button and show how to create it in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a draggable floating action button in a flutter. It shows how the draggable floating action button will work in your flutter applications. It shows when the code successfully runs, then the user dragged a floating action button anywhere around the screen as long as it’s within the parent widget. It will be shown on your devices.

Demo Module :

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 Globalkey and name it called _parentKey

final GlobalKey _parentKey = GlobalKey();

In the body, we will add a Container widget with height and width. It’s child property, we will add the Stack widget. In this widget, we will add a key, text, and a DraggableFloatingActionButton(). Inside the button, we will add a container with height and width. Add image on its child property. Also, we will add initialOffset, parent key, and onPressed. We will deeply define the below code.

Container(
width: 300,
height: 300,
child: Stack(
key: _parentKey,
children: [
Container(color: Colors.cyan),
Center(
child: const Text(
"FlutterDev's.com",
style: const TextStyle(color: Colors.white, fontSize: 24),
),
),
DraggableFloatingActionButton(
child: Container(
width: 60,
height: 60,
decoration: ShapeDecoration(
shape: CircleBorder(),
color: Colors.white,
),
child: Image.asset("assets/logo.png"),
),
initialOffset: const Offset(120, 70),
parentKey: _parentKey,
onPressed: () {},
),
],
),
)

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

We will make a class for such a widget. The main thing we need to deal with is the capacity to make the button draggable after the pointer. One of the widgets that can be utilized is Listener, which can identify pointer move events and give the movement detail. Essentially, the button should be wrapped as the child of a Listener.

The Listener widget has onPointerMove the contention which can be utilized to pass a callback that will be considered when the pointer is moving. The callback function should have a boundary PointerMoveEvent that contains the development delta in x and y headings (delta. dx and delta. dy). The offset of the catch should be refreshed by the movement delta.

The following is the class for making draggable floating action buttons. It has a few contentions which incorporate child, initialOffset, and onPressed. The child widget is delivered utilizing Positioned the widget dependent on the current offset. It’s additionally wrapped as the child of a Listener widget. There’s additionally a strategy _updatePosition that refreshes the current offset dependent on the movement delta.

class DraggableFloatingActionButton extends StatefulWidget {

final Widget child;
final Offset initialOffset;
final VoidCallback onPressed;

DraggableFloatingActionButton({
required this.child,
required this.initialOffset,
required this.onPressed,
});

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

class _DraggableFloatingActionButtonState extends State<DraggableFloatingActionButton> {

bool _isDragging = false;
late Offset _offset;

@override
void initState() {
super.initState();
_offset = widget.initialOffset;
}

void _updatePosition(PointerMoveEvent pointerMoveEvent) {
double newOffsetX = _offset.dx + pointerMoveEvent.delta.dx;
double newOffsetY = _offset.dy + pointerMoveEvent.delta.dy;

setState(() {
_offset = Offset(newOffsetX, newOffsetY);
});
}

@override
Widget build(BuildContext context) {
return Positioned(
left: _offset.dx,
top: _offset.dy,
child: Listener(
onPointerMove: (PointerMoveEvent pointerMoveEvent) {
_updatePosition(pointerMoveEvent);

setState(() {
_isDragging = true;
});
},
onPointerUp: (PointerUpEvent pointerUpEvent) {
print('onPointerUp');

if (_isDragging) {
setState(() {
_isDragging = false;
});
} else {
widget.onPressed();
}
},
child: widget.child,
),
);
}
}

You need to add a key to the parent widget and pass it to the DraggableFloatingActionButton widget. From the key, you can get the RenderBox from the currentContext property, which has findRenderObject a strategy. Then, at that point, you can get the size of the parent from the size property of the RenderBox. You should be cautious because the findRenderObject technique should be called after the tree is built. Subsequently, you need to summon it utilizing addPostFrameCallback of WidgetsBinding.

The _updatePosition the technique should be changed as well. On the off chance that the new offset is lower than the minimum offset, the value must be set to the minimum offset. On the off chance that the new offset is more noteworthy than the maximum offset, the value must be set to the most maximum offset. You need to do that for both x and y axes.

class DraggableFloatingActionButton extends StatefulWidget {

final Widget child;
final Offset initialOffset;
final VoidCallback onPressed;

DraggableFloatingActionButton({
required this.child,
required this.initialOffset,
required this.onPressed,
});

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

class _DraggableFloatingActionButtonState extends State<DraggableFloatingActionButton> {

final GlobalKey _key = GlobalKey();

bool _isDragging = false;
late Offset _offset;
late Offset _minOffset;
late Offset _maxOffset;

@override
void initState() {
super.initState();
_offset = widget.initialOffset;

WidgetsBinding.instance?.addPostFrameCallback(_setBoundary);
}

void _setBoundary(_) {
final RenderBox parentRenderBox = widget.parentKey.currentContext?.findRenderObject() as RenderBox;
final RenderBox renderBox = _key.currentContext?.findRenderObject() as RenderBox;

try {
final Size parentSize = parentRenderBox.size;
final Size size = renderBox.size;

setState(() {
_minOffset = const Offset(0, 0);
_maxOffset = Offset(
parentSize.width - size.width,
parentSize.height - size.height
);
});
} catch (e) {
print('catch: $e');
}
}

void _updatePosition(PointerMoveEvent pointerMoveEvent) {
double newOffsetX = _offset.dx + pointerMoveEvent.delta.dx;
double newOffsetY = _offset.dy + pointerMoveEvent.delta.dy;

if (newOffsetX < _minOffset.dx) {
newOffsetX = _minOffset.dx;
} else if (newOffsetX > _maxOffset.dx) {
newOffsetX = _maxOffset.dx;
}

if (newOffsetY < _minOffset.dy) {
newOffsetY = _minOffset.dy;
} else if (newOffsetY > _maxOffset.dy) {
newOffsetY = _maxOffset.dy;
}

setState(() {
_offset = Offset(newOffsetX, newOffsetY);
});
}

@override
Widget build(BuildContext context) {
return Positioned(
left: _offset.dx,
top: _offset.dy,
child: Listener(
onPointerMove: (PointerMoveEvent pointerMoveEvent) {
_updatePosition(pointerMoveEvent);

setState(() {
_isDragging = true;
});
},
onPointerUp: (PointerUpEvent pointerUpEvent) {
print('onPointerUp');

if (_isDragging) {
setState(() {
_isDragging = false;
});
} else {
widget.onPressed();
}
},
child: Container(
key: _key,
child: widget.child,
),
),
);
}
}

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_draggable_floating/draggable_floating_action_button.dart';
import 'package:flutter_draggable_floating/splash_screen.dart';

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

class MyApp extends StatelessWidget {

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

class DraggableFloatingActionButtonDemo extends StatelessWidget {

final GlobalKey _parentKey = GlobalKey();

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Draggable Floating Action Button'),
backgroundColor: Colors.cyan,
),
body: Column(
children: [
Container(
height: 150,
),
Container(
width: 300,
height: 300,
child: Stack(
key: _parentKey,
children: [
Container(color: Colors.cyan),
Center(
child: const Text(
"FlutterDev's.com",
style: const TextStyle(color: Colors.white, fontSize: 24),
),
),
DraggableFloatingActionButton(
child: Container(
width: 60,
height: 60,
decoration: ShapeDecoration(
shape: CircleBorder(),
color: Colors.white,
),
child: Image.asset("assets/logo.png"),
),
initialOffset: const Offset(120, 70),
parentKey: _parentKey,
onPressed: () {},
),
],
),
)
],
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Draggable Floating Action Button in a flutter; you can modify this code according to your choice. This was a small introduction to Draggable Floating Action 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 Draggable Floating Action Button in your flutter projectsWe will show you what the Introduction is?. That is the way to make a draggable floating action button in Flutter. Fundamentally, you can utilize Listener the widget to distinguish pointer move events and update the button offset dependent on the development delta. The Listener widget likewise upholds distinguishing pointer-up events at which the button’s activity ought to be performed except if it has recently been dragged. You likewise need to get the size of the parent and the button to keep the button from being out of the parent’s box. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Explore Open URLs In Flutter

0

While surfing the net, each user will go over numerous buttons, text, and so forth, that would divert the user to an alternate website page in a similar tab or an alternate tab when clicked. Now and then, we might need to divert users to explicit links or websites by inciting a browser.

In this article, we will Explore Open URLs In Flutter. We will implement a demo program of the URL and how to open URLs in browser and app using the url_launcher package in your flutter applications.

url_launcher | Flutter Package
A Flutter plugin for launching a URL. Supports iOS, Android, web, Windows, macOS, and Linux. To use this plugin, add…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

In Flutter, everything is a widget and similarly, Flutter likewise utilizes a lot of plugins or dependencies to make the application work quicker and simpler. For this situation, the “url_launcher” plugin can be utilized to dispatch the URL in a mobile application.

Similarly, when a developer interfaces a URL to a button or text in an application, the application will open the website when clicked in the accompanying manners:

  • In browser(default)
  • In-App

With regards to opening a website in a browser then it includes two applications at work. One of the applications that the user is utilizing and the other is the browser. Yet, with regards to, in-application opening, it includes only one application. Every one of these highlights can be utilized by a developer as indicated by the need of the user.

Demo Module :

This demo video shows how to open a url’s in a flutter. It shows how the URLs will work using the url_launcher package in your flutter applications. It shows open URLs in the external browser and In-app. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

url_launcher:

Step 2: Import

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

Presently, how about we make a function that can be called at whatever point the user clicks a button that is connected to a URL, to open it in a browser.

_launchURLBrowser() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

The function is named here as “_launchURLBrowser” and the function is proclaimed as “async” so it returns a guarantee. The “url” variable is allowed with the necessary web address, as a string. It is pronounced as a “const” with the goal that the variable isn’t changed in any situation. On the off chance that there is the possibility to dispatch the URL, just the url is launch by calling the launch() work with url variable as a trait. Else, it will throw/print a text with the URLs value, as a blunder message.

Presently, how about we make a function that can be called at whatever point the user clicks a button that is connected to a URL, to open it in a app.

_launchURLApp() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url, forceSafariVC: true, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}

The function is named here as “_launchURLApp” and the function is proclaimed as “async” so it returns a guarantee. The “url” variable is doled out with the necessary web address, as a string. It is pronounced as a “const” so the variable isn’t changed at any condition. On the off chance that there is plausible to dispatch the URL, just the url is launched by calling the launch() function with url variable as a property. Else, it will throw/print a text with the url value, as an error message.

To open the URL inside the application, two conditions must be made valid.

  • > forceWebView: true — this helps the app start the app’s web view for the website to open inside the app itself.
  • > forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser.

Note: In browser opening, the forceWebView and forceSafariVC are set to “false” by default.

The above functions can be called whenever needed in code, by calling the name of the functions as such. In the body, we will create two raised buttons having the text “Press Url Browser” and “Press Url App” on it, respectively.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLBrowser,
child: Text('Press Url Browser',style: TextStyle(color: Colors.white),),
),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLApp,
padding: EdgeInsets.only(left: 30,right: 30),
child: Text('Press Url App',style: TextStyle(color: Colors.white),),
),
],
),

For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp individually so that, when the first button is pressed the URL is opened in a browser, and when the second button is pressed the URL is opened in the actual application. 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_url/splash_screen.dart';
import 'package:url_launcher/url_launcher.dart';

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

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

class OpenUrlDemo extends StatelessWidget {

_launchURLBrowser() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

_launchURLApp() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url, forceSafariVC: true, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
title: Text('Flutter Open Url Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLBrowser,
child: Text('Press Url Browser',style: TextStyle(color: Colors.white),),
),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLApp,
padding: EdgeInsets.only(left: 30,right: 30),
child: Text('Press Url App',style: TextStyle(color: Colors.white),),
),
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Open URLs’ basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Open URLs 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 Open URLs in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Open URLs and it shows open URLs in the external browser and In-app itself using the url_launcher 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.


Exploring Flutter Essentials Lists

0

Flutter is an open-source structure to make the superior grade, elite mobile applications across mobile working systems — Android and iOS. It gives a basic, amazing, productive, and straightforward SDK to compose a mobile application in Google’s own language, Dart.

In this blog, we will be Exploring Flutter Essentials Lists. We will also implement a demo program and we are going to talk about lists in your flutter applications.

Table of Contents:

Using ListView how to handle lists in Flutter

Using ListTile is a useful widget for list items

The builder constructor

Separated constructor & Divider widget

How to implement a horizontal list



Using ListView how to handle lists in Flutter:

Making a list utilizing Flutter is truly simple as it accompanies an inherent widget called ListView, which handles everything for you. How about we perceive how to make a fundamental utilization of this widget.

To deliver a list, add a ListView widget. It has numerous properties, and one of these is called children, which accepts an array of widgets as value. Along these lines, a straightforward list would resemble this:

ListView (
children: <Widget>[
// ...widgets to show in the list...
],
)

> Space rules :

There are two rules you need to think about going to see how ListView chooses how much space to take on your screen.

  • The list will fill up all the width available;
  • The height of each item should be defined, implicitly, or explicitly.

There’s very little to say about the first point: except if you have a widget with a characterized width to contain your list, it will top off all the accessible space evenly. The second rule implies that when you characterize a thing of the list, the ListView ought to have the option to tell how high everything will be.

Using ListTile is a useful widget for list items:

Another valuable widget to think about is the ListTile widget. This is generally used to deliver each list item as it is adaptable enough for that utilization. It has a title, a subtitle, a leading widget, and a trailing widget, as you can find in the photos beneath.

ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey.shade300,
child: Text('Y'),
),
title: Text('THIS IS A TITLE'),
subtitle: Text('This is a subtitle and it has a different style'),
trailing: Icon(Icons.delete),
)

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

This widget is incredible assuming you need your list of components to follow the material plan details. It has two properties to enable interaction: the onTap and the onLongPress callbacks.

The builder constructor:

We’ve perceived how to implement out a list in Flutter. The technique displayed before is acceptable if you have a list with few things, however, it experiences execution issues on the off chance that you need to deal with a more extended list: this happens because it attempts to deliver everything of the list, even though they are not noticeable on the screen! You comprehend that for an extremely extensive list, it very well may be an issue.

The solution:

To tackle the referenced issue, ListView accompanies an exceptional constructor called builder, and it is savvy enough to deliver just the widgets right now apparent on the screen. A list utilizing the builder constructor resembles this:

The primary thing to see is that you will not utilize the “children” property any longer by utilizing the developer constructor. All things considered, you need to characterize the itemCount and the itemBuilder property; how about we see what they are.

itemCount and itemBuilder:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => Text(items[index]),
);
}
}

Separated constructor & Divider widget:

We’ve effectively seen two constructors of the ListView widget. It has a third one called separated. This one is based upon the past one and adds another element: you can put some divider between your list items. There are numerous methods of partitioning your substance. For instance, a straight line might be utilized, or 3 horizontal dots, as Medium itself does. Flutter has the Divider widget that defines a horizontal line.

We should perceive what we need to utilize this constructor:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.separated(
padding: EdgeInsets.all(10),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
leading: Icon(Icons.arrow_forward),
);
},
separatorBuilder: (context, index) {
return Divider(
thickness: 2,
);
},
);
}
}

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

separatorBuilder parameter:

The separatorBuilder works precisely as the itemBuilder. Rather than dealing with the list components, it deals with every separator: you need to pass in a capacity that takes a BuilderContext and an integer index, and it should return a widget.

It doesn’t occur much regularly to the function’s contributions to be of any need. That is because typically, the separator ought to consistently be something very similar, regardless of which things of the list you’re dividing. All things considered, if the one above isn’t the situation, you can utilize the unique context and the index to characterize which widget to return as we do with the itemBuilder parameter.

How to implement a horizontal list:

Now and again you need to swipe through your items horizontally. In Flutter, it’s clear to accomplish that!. You should simply characterize the property scrollDirection, which ought to be appointed a value from the Axis enum, and one of its values is horizontal, the one we were searching for. We should perceive how everything meets up:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Container(
width: 200,
child: Card(
elevation: 2,
child: ListTile(title: Text(items[index])),
),
),
);
}
}

You may have seen that everything has a predetermined width. That is because level records act as the specific inverse of vertical ones. The rules applied to a vertical list we’ve seen before don’t work here any longer. In this way, we should perceive what changed.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Flutter Essentials Lists in your flutter projects. That’s all. There is plenty more Flutter has to offer regarding lists, but I wanted to lay down the most useful concepts. So please try it.

❤ ❤ Thanks for reading this article ❤❤


From Our Parent Company Aeologic

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

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

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

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

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


Explore Customizable Time Planner In Flutter

Flutter has been a great encounter from the earliest starting point. Building ravishing UI had never been speedier. It’s not difficult to become hopelessly enamored with Flutter, whether or not you’re an amateur or a cultivated developer. All software developers understand that dates are the trickiest thing. Likewise, schedules are no special case.

In mobile apps, there are many cases where a user needs to enter a date like date of birth, book a ticket, schedule a meeting, etc.

In this blog, we will Explore Customizable Time Planner In Flutter. We will also implement a demo program and create a customizable time planner using the time_planner package in your flutter applications.

time_planner | Flutter Package
A beautiful, easy to use and customizable time planner for flutter mobile 📱, desktop 🖥 and web 🌐 This is a widget…pub.dev

Table Of Contents::

Introduction

Attributes

Implementation

Code Implement

Code File

Conclusion



Introduction:

A delightful, simple to utilize, and customizable time planner for flutter mobile, desktop, and web. This is a widget to show assignments to clients on a schedule. Each row shows an hour and every column shows a day, yet you can change the title of the section and show whatever else you need.

Demo Module :

This demo video shows how to create a customizable time planner in a flutter. It shows how the customizable time planner will work using the time_planner package in your flutter applications. It shows when the user taps on any row and column then a random time planner will be created. animated. It will be shown on your device.

Attributes:

There are some attributes of the Time Planner are:

  • > startHour: These attributes are used to time start from this, it will start from 1.
  • > endHour: These attributes are used to time end at this hour, the max value is 24.
  • > headers: These attributes are used to create days from here, each day is a TimePlannerTitle. You should create at least one day.
  • > tasks: These attributes are used to List widgets on the time planner.
  • > style: These attributes are used to Style of time planner.
  • > currentTimeAnimation: These attributes are used to widget loaded scroll to the current time with animation. Default is true.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

time_planner: 

Step 2: Import

import 'package:time_planner/time_planner.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we create a list of TimePlannerTask called variable tasks.

List<TimePlannerTask> tasks = [];

We will create a _addObject() method. Inside, we will add a List of colors and add setState() function.

void _addObject(BuildContext context) {
List<Color?> colors = [
Colors.purple,
Colors.blue,
Colors.green,
Colors.orange,
Colors.cyan
];

setState(() {
tasks.add(
TimePlannerTask(
color: colors[Random().nextInt(colors.length)],
dateTime: TimePlannerDateTime(
day: Random().nextInt(10),
hour: Random().nextInt(14) + 6,
minutes: Random().nextInt(60)),
minutesDuration: Random().nextInt(90) + 30,
daysDuration: Random().nextInt(4) + 1,
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You click on time planner object')));
},
child: Text(
'this is a demo',
style: TextStyle(color: Colors.grey[350], fontSize: 12),
),
),
);
});

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Random task added to time planner!')));
}

In the function, we will add tasks.add()method. Inside, we will add TimePlannerTask() widget. In this widget, we will add color, date time, minutesDuration and daysDuration. We will also show snackBar messages when users tap on the time planner.

In the body, we will add TimePlanner() widget. Inside, we will add startHour, endHour, and headers. In headers, we will add some TimePlannerTitle(). Also, we will add tasks and styles.

TimePlanner(
startHour: 2,
endHour: 24,
headers: [
TimePlannerTitle(
date: "7/20/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/21/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/22/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/23/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/24/2021",
title: "saturday",
),
TimePlannerTitle(
date: "7/25/2021",
title: "sunday",
),
TimePlannerTitle(
date: "7/26/2021",
title: "monday",
),
TimePlannerTitle(
date: "7/27/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/28/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/29/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/30/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/31/2021",
title: "Saturday",
),
],
tasks: tasks,
style: TimePlannerStyle(
showScrollBar: true
),
),

Now, we will create a FloatingActionButton(). Inside, we will add onPressed, tooltip, and child.

floatingActionButton: FloatingActionButton(
onPressed: () => _addObject(context),
tooltip: 'Add random task',
child: Icon(Icons.add),
),

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

Final Output

Code File:

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_customizable_time_plan/splash_screen.dart';
import 'package:time_planner/time_planner.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 {
MyHomePage({Key? key, required this.title}) : super(key: key);

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
List<TimePlannerTask> tasks = [];

void _addObject(BuildContext context) {
List<Color?> colors = [
Colors.purple,
Colors.blue,
Colors.green,
Colors.orange,
Colors.cyan
];

setState(() {
tasks.add(
TimePlannerTask(
color: colors[Random().nextInt(colors.length)],
dateTime: TimePlannerDateTime(
day: Random().nextInt(10),
hour: Random().nextInt(14) + 6,
minutes: Random().nextInt(60)),
minutesDuration: Random().nextInt(90) + 30,
daysDuration: Random().nextInt(4) + 1,
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You click on time planner object')));
},
child: Text(
'this is a demo',
style: TextStyle(color: Colors.grey[350], fontSize: 12),
),
),
);
});

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Random task added to time planner!')));
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(widget.title),
centerTitle: true,
),
body: Center(
child: TimePlanner(
startHour: 2,
endHour: 24,
headers: [
TimePlannerTitle(
date: "7/20/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/21/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/22/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/23/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/24/2021",
title: "saturday",
),
TimePlannerTitle(
date: "7/25/2021",
title: "sunday",
),
TimePlannerTitle(
date: "7/26/2021",
title: "monday",
),
TimePlannerTitle(
date: "7/27/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/28/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/29/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/30/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/31/2021",
title: "Saturday",
),
],
tasks: tasks,
style: TimePlannerStyle(
showScrollBar: true
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _addObject(context),
tooltip: 'Add random task',
child: Icon(Icons.add),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Customizable Time Planner in a flutter; you can modify this code according to your choice. This was a small introduction to Customizable Time Planner 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 Customizable Time Planner in your flutter projects. We will show you what the Introduction is?, some attributes using in Time Planner, and make a demo program for working Customizable Time Planner 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.


RepaintBoundary In Flutter

0

Flutter paints widgets to the screen. If the substance of a widget ought to be updated, it’s anything but a repaint. Notwithstanding, Flutter may likewise repaint different widgets whose content remaining parts unaltered. It can influence the application execution and at times it’s very huge. If you are searching for an approach to forestall unnecessary repaints, you can think about utilizing RepaintBoundary.

In this blog, we will explore RepaintBoundary In Flutter. We will see how to implement a demo program of the repaint boundary and how to use it in your flutter applications.

Table Of Contents::

RepaintBoundary

Why Need to Use RepaintBoundary

Code Implement

Code File

Conclusion



RepaintBoundary:

RepaintBoundary class Null safety. To start with, you need to realize what is RepaintBoundary in Flutter. It’s anything but’s a widget that makes a different presentation list for its child. As indicated by Wikipedia, a showcase list is a progression of illustrations commands that characterize an output picture. This widget makes a different presentation list for its child, Flutter proposes you use RepaintBoundary if a subtree repaints at unexpected times in comparison to its encompassing parts to further develop performance.

Why Need to Use RepaintBoundary:

Flutter widgets are related to RenderObjects. A RenderObject has a technique called paint which is utilized to perform painting. Be that as it may, the paint the method can be conjured regardless of whether the related widget occasions don’t change. That is because Flutter may perform repaint to other RenderObjects in a similar Layer if one of them is set apart as filthy. At the point when a RenderObject should be repainted utilizing RenderObject.markNeedsPaint, it advises its closest predecessor to repaint. The progenitor does likewise to its predecessor, perhaps until the root RenderObject. At the point when a RenderObject’s paint strategy is set off, the entirety of its relative RenderObjects in a similar layer will be repainted.

At times, when a RenderObject should be repainted, the other RenderObjects in a similar layer shouldn’t be repainted because their delivered substance stays unaltered. As such, it would be better if we would just repaint certain RenderObjects. Utilizing RepaintBoundary can be helpful to restrict the engendering of markNeedsPaint up the render tree and paintChild down the render tree.

RepaintBoundary can decouple the predecessor render objects from the relative render objects. In this way, it’s feasible to repaint just the subtree whose content changes. The utilization of RepaintBoundary may altogether further develop the application execution, particularly if the subtree that shouldn’t be repainted requires broad work for repainting.

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.

We will make a straightforward demo application where the background is painted utilizing CustomPainter and there are 10,000 ovals drawn. There is likewise a cursor that moves following the last position of the client touches the screen. The following is the code without RepaintBoundary.

In the body, we will create a Stack widget. Inside, we will add a StackFit.expand, and add two widgets was _buildBackground(), and _buildCursor(),. We will define the below code.

Stack(
fit: StackFit.expand,
children: <Widget>[
_buildBackground(),
_buildCursor(),
],
),

We will describe _buildBackground() widget:

In the _buildBackground() widget. We will return CustomPaint() widget. Inside, we will add BackgroundColor class on a painter. We will define below. Also, we will add is complex as true means whether to hint that this layer’s painting should be cached and willChange was false means whether the raster cache should be told that this painting is likely to change in the next frame.

Widget _buildBackground() {
return CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
);
}

We will describe BackgroundColor class:

We will create a BackgroundColor was extend CustomPainter.

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

class BackgroundColor extends CustomPainter {

static const List<Color> colors = [
Colors.orange,
Colors.purple,
Colors.blue,
Colors.green,
Colors.purple,
Colors.red,
];

Size _size;
BackgroundColor(this._size);

@override
void paint(Canvas canvas, Size size) {
final Random rand = Random(12345);

for (int i = 0; i < 10000; i++) {
canvas.drawOval(
Rect.fromCenter(
center: Offset(
rand.nextDouble() * _size.width - 100,
rand.nextDouble() * _size.height,
),
width: rand.nextDouble() * rand.nextInt(150) + 200,
height: rand.nextDouble() * rand.nextInt(150) + 200,
),
Paint()
..color = colors[rand.nextInt(colors.length)].withOpacity(0.3)
);
}
}

@override
bool shouldRepaint(BackgroundColor other) => false;
}

We will describe _buildCursor() widget:

In this widget, we will return the Listener widget. We will add _updateOffset () widget at onPointerDown/Move and add CustomPaint widget. Inside, we will add a key and CursorPointer class. We will define below. Also, we will add ConstrainedBox().

Widget _buildCursor() {
return Listener(
onPointerDown: _updateOffset,
onPointerMove: _updateOffset,
child: CustomPaint(
key: _paintKey,
painter: CursorPointer(_offset),
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
),
),
);
}

We will describe CursorPointer class:

We will create a CursorPointer was extend CustomPainter.

import 'package:flutter/material.dart';

class CursorPointer extends CustomPainter {

final Offset _offset;

CursorPointer(this._offset);

@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(
_offset,
10.0,
new Paint()..color = Colors.green,
);
}

@override
bool shouldRepaint(CursorPointer old) => old._offset != _offset;
}

When we run the application, we ought to get the screen’s output like the underneath screen video. If you try to move the pointer on the screen, the application will be so laggy because it repaints the background, requiring expensive computation.

Without Using RepaintBoundary

Presently, we will add RepaintBoundary. The answer to the above problem is wrapping the CustomPaint widget as the child of a RepaintBoundary.

Widget _buildBackground() {
return RepaintBoundary(
child: CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
),
);
}

When we run the application, we ought to get the screen’s output like the underneath screen video. With that simple change, now the background doesn’t need to be repainted when Flutter repaints the cursor. The application should not be laggy anymore.

Using RepaintBoundary

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_repaint_boundary_demo/background_color.dart';
import 'package:flutter_repaint_boundary_demo/cursor_pointer.dart';

class HomePage extends StatefulWidget {

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

class _HomePageState extends State<HomePage> {

final GlobalKey _paintKey = new GlobalKey();
Offset _offset = Offset.zero;

Widget _buildBackground() {
return RepaintBoundary(
child: CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
),
);
}

Widget _buildCursor() {
return Listener(
onPointerDown: _updateOffset,
onPointerMove: _updateOffset,
child: CustomPaint(
key: _paintKey,
painter: CursorPointer(_offset),
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
),
),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
title: const Text('Flutter RepaintBoundary Demo'),
),
body: Stack(
fit: StackFit.expand,
children: <Widget>[
_buildBackground(),
_buildCursor(),
],
),
);
}

_updateOffset(PointerEvent event) {
RenderBox? referenceBox = _paintKey.currentContext?.findRenderObject() as RenderBox;
Offset offset = referenceBox.globalToLocal(event.position);
setState(() {
_offset = offset;
});
}
}

Conclusion:

In the article, I have explained the basic structure of the RepaintBoundary in a flutter; you can modify this code according to your choice. This was a small introduction to RepaintBoundary 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 RepaintBoundary in your flutter projectsWe will make a demo program for working Custom Chat Bubble and you should use RepaintBoundary a subtree repaint at different times than its surrounding parts. To make sure that a RepaintBounary is useful 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.