Google search engine
Home Blog Page 29

Reorderable ListView In Flutter

0

Flutter is notable for its similarity among other mobile development stages that why it is one of the most promptly developing stages, and the primary purpose for it is the Flutter has thought of each feature and functionality which is required to build up a completely fledged application.

In this article, I will explore Reorderable ListView in Flutter and how to reorder a listview thing. By utilizing the ReorderableListView widget, you can rearrange the item inside a ListView in your flutter applications. You have to see that in the wake of moving and dropping the item.

Table Of Contents:

Reorderable ListView

Code Implementation

Code File

Conclusion



Reorderable ListView

The reorderable List is one whose items are draggable, and the user can rearrange/modify the object.

This class is fitting for sees with few numbers of the children’s fact that developing the List requires accomplishing work for each child that might be shown in the list view see rather than merely those children that are noticeable.

Code Implementation

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

First, we will create a list in which we have the data. So, we will create a list of string and let me give it a name called item and after giving the name item. I will create an array; basically, it is a list, not an array.

List<String> item = ["Clients","Designer","Developer","Director",
"Employee", "Manager", "Worker","Owner"];

Note that all children of the ReorderableListView widget must have a key since the key is expected to distinguish items after their position is changed in the List. This is the means by which your ReorderableListView widget resembles.

ReorderableListView(
children: <Widget>[
for(final items in widget.item)
Card(
color: Colors.blueGrey,
key: ValueKey(items),
elevation: 2,
child: ListTile(
title: Text(items),
leading: Icon(Icons.work,color: Colors.black,),
),
),
],
onReorder: reorderData,

),

In ReorderableListView, we will add a card, and in the card, we will add key and List Tile. In List Tile, we will add a title and leading icon. On Reorder parameter is compulsory. It will be called when the list child is moved to a new position.

Let we will create a rorder function and give it a name called reorderData.

void reorderData(int oldindex, int newindex){
setState(() {
if(newindex>oldindex){
newindex-=1;
}
final items =widget.item.removeAt(oldindex);
widget.item.insert(newindex, items);
});
}

This function will add two parameters, first old index and the second one is the new index. In this function, we will add final items is equal to item dot remove at the old index place. Then, when the item is excluded from that index placed, it should be inserted the point where you want to index that is it should be inserted at the new index place. So, item dot inserts (new index, items) and then run the code, and the output will be shown on your devices. We have to write the logic in the setState() method to reflect the changes.

Now we add an icon on the app bar for sorting purposes. It will rearrange your list is increasing to decreasing the alphabet.

actions: <Widget>[
IconButton(icon: Icon(Icons.sort_by_alpha),
tooltip:"Sort",
onPressed: sorting
),
],

Let we will create a sorting function.

void sorting(){
setState(() {
widget.item.sort();
});
}

In this function, we will add item dot short for rearranging the data.

We will tap on the AZ icon then all data will be rearranged due to the sort method. On this screen, you will see a list and icon on a card.

Code File

https://gist.github.com/ShaiqAhmedkhan/3ce7736b6f40a9de09c545449c5f6597#file-reorderable_view_page-dart

You will see a full code on a GitHub, and this is a small demo example of ReorderableListView in a flutter, and this below video shows how ReorderableListView will work and how to drag and drop the item.

Conclusion:

In the article, I have explained the basic demo of ReorderableListView you can modify this code according to your choice, and this was a small basic introduction of ReorderableListView from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Reorderable ListView in Flutter in your flutter projects. This is a demo example that will integrate ReorderableListView in a flutter and show dragging and dropping the items, and also used a sort method for rearranging the items in a list on the increase to decrease way, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Reorderable ListView Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Custom Dialog In Flutter

0

I have been trying different things with Flutter for some time, and I staggered a lot of times, making custom widgets from designs for applications. Even though Flutter is staggeringly simple to make UI parts, you need to experience a lot of trial procedures to get what we need.

In this blog, We will be going to explore Custom Dialog In Flutter and show a demo of how to make a custom dialog in your flutter applications.

Contents:

Custom Dialog

Code Implementation

Code File

Conclusion



Custom Dialog

A dialog resembles a popup window to give a few alternatives to users(options like acknowledging/decay). Basic Alert Dialog won’t be helpful for each necessity. On the off chance that you need to execute further developed custom Dialog, you can utilize the Dialog widget for that. Rather than the AlertDialog, in here, we return the Dialog widget. The showDialog technique will continue as before.

Code Implementation :

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

In this screen, we will create a button for opening a dialog and button named called it Custom Dialog.

Container(
child: Center(
child: RaisedButton(
onPressed: (){},
child: Text("Custom Dialog"),

),
),
),

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

It is just a class to store the few constants, as shown down here.

import 'package:flutter/material.dart';

class Constants{
Constants._();
static const double padding =20;
static const double avatarRadius =45;
}

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

In this screen, we will use CircularAvatar for the image at the top, Text for Title and Descriptions, and FlatButton for button.

Let’s declare the CustomDialogBox class.

return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(Constants.padding),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: contentBox(context),
);

We are setting all the properties of dialog and title to contentBox(), which contains all our significant widgets.

Dialog, as a matter of course, accompanies its background color and elevation. Since we won’t use it, we are setting backgroundColor to Colors.transparent and elevation to 0.

contentBox(context){
return Stack(
children: <Widget>[
Container(),// bottom part
Positioned(),// top part
],
);
}

The Stack shows the keep last element on the top. We have circular toward the end to overlap on the card. How about we dive profound into every one of the children.

Container(
padding: EdgeInsets.only(left: Constants.padding,top: Constants.avatarRadius
+ Constants.padding, right: Constants.padding,bottom: Constants.padding
),
margin: EdgeInsets.only(top: Constants.avatarRadius),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(Constants.padding),
boxShadow: [
BoxShadow(color: Colors.black,offset: Offset(0,10),
blurRadius: 10
),
]
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(widget.title,style: TextStyle(fontSize: 22,fontWeight: FontWeight.w600),),
SizedBox(height: 15,),
Text(widget.descriptions,style: TextStyle(fontSize: 14),textAlign: TextAlign.center,),
SizedBox(height: 22,),
Align(
alignment: Alignment.bottomRight,
child: FlatButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(widget.text,style: TextStyle(fontSize: 18),)),
),
],
),
),

We are utilizing a Container and BoxDecoration for making the card, and since the half of circular avatar ought to be on the card, we include padding and margin as needs are with the characteristic Constants.avatarRadiusand Constants.paddding. We will include the title, descriptions, and text of a button.

Positioned(
left: Constants.padding,
right: Constants.padding,
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: Constants.avatarRadius,
child: ClipRRect(),
),

We will use Positioned widget as a child in Stack to wrap the CircularAvatar. Also the left and right attributes are set to the same values to place in the center of the Stack. We will add background color, radius, and use ClippRRect() for the image.

ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(Constants.avatarRadius)),
child: Image.asset("assets/model.jpeg")
),

We will use ClippRRect()for the image circular border.

Now, then add CustomDialogBox in dialog.dart the lib folder.

import 'package:custom_dialog_flutter_demo/custom_dialog_box.dart';
import 'package:flutter/material.dart';

class Dialogs extends StatefulWidget {
@override
_DialogsState createState() => _DialogsState();
}

class _DialogsState extends State<Dialogs> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Custom Dialog In Flutter"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Container(
child: Center(
child: RaisedButton(
onPressed: (){
showDialog(context: context,
builder: (BuildContext context){
return CustomDialogBox(
title: "Custom Dialog Demo",
descriptions: "Hii all this is a custom dialog in flutter and you will be use in your flutter applications",
text: "Yes",
);
}
);
},
child: Text("Custom Dialog"),

),
),
),
);
}
}

In the onPressed() the method you will call showDialog and return CustomDialogBox when the button then the custom dialog will pop up.

Code File

https://gist.github.com/ShaiqAhmedkhan/78bec9a4145881662c50848f08a12ffe#file-custom_dialog_box-dart

You will see a full code on a GitHub, and this is a small demo example of Custom Dialog in a flutter; and this below video shows how Custom Dialog will work and pop up show.

Conclusion:

In the article, I have explained the basic demo of Custom Dialog you can modify this code according to your choice, and this was a small introduction of Custom Dialog from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Custom Dialog in Flutter in your flutter projects. This is a demo example that will integrate Custom Dialog in a flutter and show pop up, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Custom Dialog Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Typography In Flutter

0

In this article, we will explore the Typography In Flutter. We’ll lift the top on everything you have to think about typography. We’ll begin with the definition of typography, including a concise history of its origins. Well, at that point, address the advantages of good typography and the effect it can have on your users.

Contents:

What is typography

Typography Scale

Fonts

Why is Typography important?

Classification

Conclusion



What is typography?

Typography is the specialty of arranging letters and text such that makes the duplicate decipherable, clear, and outwardly speaking to the peruser. Typography includes textual style, appearance, and structure, which expects to evoke certain feelings and pass on explicit messages. Typography is the thing that rejuvenates the content.https://www.youtube.com/embed/CfkHyFClLSg?feature=oembed

Typography is generally connected with both the digital world and print. With the introduction of the internet came an innovative blast of the specialty of typography. Out of nowhere, website specialists had a wealth of textual styles and type choices available to them, making typography more outwardly assorted than any other time in recent memory.

Typography Scale

Its scale utilizes the Roboto typeface for all headlines, captions, body, and subtitles, creating a durable typography experience. Chain of importance is imparted through contrasts in textual style weight like (Light, Medium, Regular), size, letter spacing, and case.

  • > Headlines

In the type scale, headlines length from a scope of 1 through 6. Headlines are the most significant content on the screen, held for short, significant content or numerals.

For headlines, you can pick an expressive text style, for example, a showcase, written by hand, or content style. These offbeat textual style plans have details and intricacies that help attract in the eye.

  • > Subtitles

Subtitles are littler than headlines. They are generally held for a medium-accentuation text that is shorter in length. Serif or sans serif typefaces function admirably for subtitles.

  • > Body

Body text comes in ranges 1–2, and it’s ordinarily utilized for long-structure writing as it functions admirably for small content sizes. For more extended areas of text, serif or sans serif typeface is suggested.

Fonts

Before you dive into details, you need to choose essentials: font(s). Through investigation, examination, research, and often for huge companies making a text style themselves, each show falls from and relies upon this decision.

We will likewise utilize Google Fonts, while frameworks can differ text styles dependent on theming, most ground themselves initially by identifying essential serif or potentially sans-serif textual style family. Every text style is expanded with a course of fallbacks, and numerous frameworks toss in a monospace textual style for code shows regardless of whether just their own.

Why is typography important?

Typography is far beyond simply choosing lovely textual styles: it’s a crucial part of the UI plan. Great typography will set up a solid visual hierarchy, give a realistic equalization to the site, and set the item’s general tone. Typography should direct and inform your clients, upgrade readability and availability, and guarantee magnificent client experience.

Let’s explore a little deeper into why typography is important.

  • > Builds brand recognition

Not exclusively will great typography upgrade the site’s character, yet your clients will subliminally begin to relate the typeface included on your site with your brand. One of a kind, predictable typography will assist you with establishing a solid client following, form trust with your clients, and help to convey your brand forward.

  • > Influences decision making

Typography profoundly affects the way that clients process and see the information passed on by the content. The eye-catching sort is substantially more convincing than feeble textual styles that don’t reinforce the message of the content.

  • > Holds the attention of the readers

Great typography could be the distinction between somebody staying on your site for one minute or 30 minutes. It’s significant that your site is outwardly stimulating and important, and typography assumes a tremendous job in this procedure.

Typography properties

Typography communicates progression and brand nearness. A typeface is an assortment of letters. While each letter is exceptional, certain shapes are shared across letters. A typeface speaks to shared examples over an assortment of letters.

Typefaces that are chosen for their style, legibility, and readability are best when following the major principles of typographic structure.

  • Baseline: It is the invisible line whereupon a line of the content rests. In Material Design, the baseline is a significant particular in measuring the vertical separation among text and a component.
  • Cap height: It alludes to the tallness of a typeface’s level capital letters (for example, M or I) estimated from the baseline. Round and pointed capital letters, for example, S and A, are optically balanced by being drawn with a slight overshoot over the cap-height to accomplish the impact of being a similar size. Each typeface has an extraordinary cap-height.
  • X-height: It alludes to the stature of the lower-case x for a typeface, and it indicates how tall or short every glyph in a typeface will be.

Typefaces with tall x-heights have better legibility at small font sizes, as the white space within each letter is more legible

  • Ascenders and descenders: Ascenders are an upward vertical stroke found in certain lower-case letters that reach out past either the cap height or baseline. Descenders are the descending vertical stroke in these letters. Sometimes, a crash between these strokes can happen when the line stature (the vertical separation between baselines) is excessively close.
  • Weight: It alludes to the general thickness of a text style’s stroke. A typeface can come in numerous weights, and four to six weights is a common number accessible for a typeface.

Common weights are:
1. Light
2. Regular
3. Medium
4. Bold

Classification

  1. Serif: It is a little shape or projection that shows up toward the beginning or end of a stroke in a letter. Typefaces with serifs are called serif typefaces.

Serif fonts are classified as one of the following:

  • Old-Style serifs: It is a Low complexity among thick and thin strokes, Diagonal worry in the strokes, and Slanted serifs on lower-case ascenders.
  • Transitional serifs: It is a high differentiation among thick and thin strokes, Medium-High x-tallness, Vertical worry in the strokes, and Bracketed serifs.
  • Didone serifs: It is an extremely high differentiation among thick and thin strokes, Vertical worry in the strokes, and “Ball” terminal strokes.
  • Slab serifs: It is a Heavy serif with vague contrasts between the stroke weight, and Minimal or no bracketing

2. Sans Serif: A typeface without serifs is known as a sans serif typeface, from the French word “sans” that signifies “without.”

Sans serifs can be classified as one of the following:

  • Grotesque: It is a Low complexity among thick and thin strokes, vertical or no discernible pressure.
  • Humanist: It is a Medium difference among thick and thin strokes, inclined pressure.
  • Geometric: It is a Low differentiation among thick and thin strokes, with vertical pressure, and circular round structures.

3. Monospace: It is a typeface to show all characters with a similar width.

1.Roboto Mono
2. Space Mono
3. VT323

Conclusion:

This article would serve as an Exploratory article for Typography In Flutter and its working using Flutter. We will describe the basic introduction of typography from my side.

Typography is regularly neglected; however, it’s an urgent part of the UI design. Mastering typography will see you well on your approach to becoming an incredible UI originator!

I hope this blog has provided you with valuable information about what is all about Typography In Flutter, and that you will give it Typography In Flutter — a Try. Begin using your apps.

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.


Dart Generators & Callable Class In Flutter

0

In this blog, we will explore Dart Generators & Callable Class In Flutter. We will perceive how to utilize Dart’s generator capacity to create an on-request sequence of qualities synchronously and asynchronously is the iterative and recursive way and Furthermore,

We will figure out how to implement a Callable class. Dart is a genuine object-oriented language. Dart’s functions are additionally objects.

Table of Content :

Dart Generators — Introduction

Synchronous Generator

Asynchronous Generator

Recursive Synchronous Generator

Recursive Asynchronous Generator

Callable Class — Introduction

Implement Callable Class

Using Callable Class

Conclusion



Dart Generators

It is Functions are utilized to create an arrangement of values on-demand lazily. Such a value arrangement can be produced either synchronously or asynchronously.https://www.youtube.com/embed/TF-TBsgIErY?feature=oembed

There are two sorts of implicit generator functions accessible to support the two situations :

  • Synchronous Generator
  • Asynchronous Generator

Synchronous Generator

It is function restores an Iterable object. Begin, the values are produced and afterward returned lazily on-demand by the function service.

Iterable: An collection of values, or “components”, that can be gotten to successively.

  • > Using sync*Function:

The function Iterable<int> countDown(int num) sync* accepts a number as num, and conveys all numbers beginning from num until 0. The synchronous generator function is set apart with sync*. The qualities are returned utilizing yield the keyword. The iterable arrangement gets the number arrangement and prints each number utilizing for a loop. This number arrangement really isn’t produced until it has been gotten to by for the loop.

import 'package:flutter/material.dart';

 void main() {
  print("Iterable [sync* + yield]");
  Iterable<int> sequence = countDown(3);

print("CountDown Start");

for (int value in sequence) {
    print(value);
  }
  print("Complete");
}

Iterable<int> countDown(int num) sync* {
  while (num > 0) {
    yield num--;
  }
}

Output :

The sync* assists with creating values in a synchronous way.

Note:- CountDown Start message is printed before for loop’s execution. The Complete message is executed at last as well.

Asynchronous Generator

It is function restores a Stream object. The arrangement of values is generated on demand as they become available.

Stream: A source of asynchronous information events.

  • > Using async*Function:

The function Stream<int> countDown(int num) async* accepts a number as num, and convey number grouping beginning from num until 0. The asynchronous generator function is set apart with async*. The qualities are returned utilizing yield a keyword. The stream succession gets the number succession. Its qualities can be gotten to when it began listening in upon.

import 'package:flutter/material.dart';

void main() {
print("Stream [async* + yield]");
Stream<int> sequence = countDown(3);

print("CountDown Start");

sequence.listen((int value) {
print(value);
});
print("Complete");
}

Stream<int> countDown(int num) async* {
while (num > 0) {
yield num--;
}
}

Output:

The async* assists with creating values in an asynchronous way.

Note:- CountDown Start and Complete message is printed before the actual stream’s values are printed. The values are printed as they become available after the setup code

Recursive Synchronous Generator

Using sync* + yield*Function

At the point when generator functions are utilized recursively, yield* is utilized to stamp such recursive function calls. This model tells the best way to utilize generator functions recursively. You’ll see a similar yield with respect to the non-recursive execution. The keyword yield* is utilized for the function that is called recursively.

import 'package:flutter/material.dart';

void main() {
print("Iterable [sync* + yield*]");
Iterable<int> sequence = countDownRecursive(4);

print("CountDown Start");

for (int value in sequence) {
print(value);
}
print("Complete");
}

Iterable<int> countDownRecursive(int num) sync* {
if (num > 0) {
yield num;

yield* countDownRecursive(num -1);
}
}

Output:

You will get the following output on running up the code :

Recursive Asynchronous Generator

Using async* + yield*Function

This is a case of utilizing an asynchronous generator function recursively. It likewise has a similar output as its non-recursive partner.

import 'package:flutter/material.dart';

void main() {
print("Stream [async* + yield*]");
Stream<int> sequence = countDownRecursive(4);

print("CountDown Start");

sequence.listen((int value) {
print(value);
});
print("Complete");
}

Stream<int> countDownRecursive(int num) async* {
if (num > 0) {
yield num;

yield* countDownRecursive(num -1);
}
}

Output:

You will get the following output on running up the code :

Callable Class

In Dart, functions are objects as well. It’s an object of type Function. Like different objects, functions can be passed as contentions to different functions and can be relegated to variables also.https://www.youtube.com/embed/jluOUyDeKQ4?feature=oembed

Callable class permits its example to be known as a function. This element of Dart language is valuable in making named-functions.

Implement Callable Class

All Dart functions have call strategies. So as to make a class Callable, the call() strategy should be actualized. How about we proclaim a callable class beneath:

class Multiply {
int call(int a, int b) => a * b;
}

The above class.’ call the technique takes two arguments and returns their multiplication number.

Using Callable Class

We should look at utilizing the Multiply callable class in the code underneath. The multiply item is of Multiply type. Presently, multiply(2, 2) it can be called to figure the multiplication of given numbers

void main() {
Multiply multiply = Multiply();
var result = multiply(2, 2);
print(result mpy);
}

Output:

You will get the following output on running up the code :

I/flutter (25099): 4

Conclusion:

This article would serve as an Exploratory article for Dart Generators & Callable Class and its working using Flutter. We will describe the basic introduction and demo implementation on Dart Generators & Callable Class from my side.

I hope this blog has provided you with valuable information about what is all about Dart Generators & Callable Class, and that you will give it Dart Generators & Callable Class — a Try. Begin using your apps.

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.


Switch Theme Using Bloc With Cubit In Flutter

0

In this article, we will explore the Switch Theme Using Bloc With Cubit In Flutter. We will see how to implement a demo program. How to switch theme using bloc with cubit the flutter_bloc package in your flutter applications.

For Flutter Bloc:

flutter_bloc | Flutter package
Flutter Widgets that make it easy to implement the BLoC (Business Logic Component) design pattern. Built to be used…pub.dev

For Equatable:

equatable | Dart package
A Dart package that helps to implement value based equality without needing to explicitly override == and hashCode.pub.dev

For Shared Preferences:

shared_preferences | Flutter package
Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on…pub.dev

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


Table Of Contents::

Introduction

Implementation

Code Implement

Conclusion



Introduction:

Bloc guarantees that the application generally opens with the client’s picked theme. Rather than utilizing standard Bloc classes, we can accomplish the ideal functionality by utilizing cubits which makes the implementation a lot more straightforward.

The below demo video shows how to switch theme using bloc with cubit in a flutter and shows how a switch theme will work using the flutter_bloc package and equatable package in your flutter applications. We will show a user switch the toggle button then the theme will be changed from the light mode to dark mode/vice versa and also the theme was persistent. It will be shown on your device.

Demo Module :


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
equatable: ^2.0.5
flutter_bloc: ^8.1.6
shared_preferences: ^2.2.3

Step 2: Import

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:shared_preferences/shared_preferences.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 _share_pref.dart inside the lib folder.

Rather than getting to the SharedPreferences straightforwardly inside our ThemeRepository, I prescribe utilizing a SharedPreferencesController to make it simpler to deal with all your SharedPreferences keys.

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:shared_preferences/shared_preferences.dart';

class _SharedPreferencesKeys {
static const String isDarkTheme = 'isDarkTheme';
}

class SharedPreferencesController {
static late SharedPreferences _preferences;

static Future init() async =>
_preferences = await SharedPreferences.getInstance();

static bool get isDarkTheme =>
_preferences.getBool(_SharedPreferencesKeys.isDarkTheme) ??
SchedulerBinding.instance.platformDispatcher.platformBrightness ==
Brightness.dark;

static Future<void> setIsDarkTheme({required bool isDarkTheme}) async =>
_preferences.setBool(_SharedPreferencesKeys.isDarkTheme, isDarkTheme);
}

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

Inside the ThemeRepository class we will have two functions. One function will be responsible for getTheme and the other function will be responsible for setTheme.

In the code snippet, we created a ThemeRepository class. Inside this class, we have the getTheme and setTheme functions to utilize the functions of the SharedPreferencesController class.

import 'package:flutter_switch_theme_demo/repositories/share_pref.dart';

class ThemeRepository {
bool getTheme() => SharedPreferencesController.isDarkTheme;

Future<void> setTheme({required bool isDarkTheme}) async =>
SharedPreferencesController.setIsDarkTheme(isDarkTheme: isDarkTheme);
}

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

To guarantee that our application knows about the ongoing theme we made the ThemeState class that will be utilized in the forthcoming ThemeCubit class.

In the above code, we made a ThemeState class that expands the Equatable class. The expansion is expected to guarantee that we can contrast cases of the ThemeState class and each other to decide on changes. The ThemeState class has one attribute themeMode that will be utilized to store the ongoing theme.

part of 'theme_cubit.dart';

class ThemeState extends Equatable {
const ThemeState({this.themeMode = ThemeMode.light});

final ThemeMode themeMode;

ThemeState copyWith({ThemeMode? themeMode}) => ThemeState(
themeMode: themeMode ?? this.themeMode,
);

@override
List<Object?> get props => [themeMode];
}

Likewise, notice that the theme_state.dart file is a piece of the theme_cubit.dart file. In this manner, every one of the imports is finished inside the theme_cubit.dart file.

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

The ThemeCubit class will contain two capabilities that we will call inside our widgets to either get the current theme or switch the theme.

In the below code, we make the ThemeCubit class which broadens the Cubit class with a type of ThemeState. The ThemeCubit class has a constructor that takes the instance of the ThemeRepository class. Other than that we have a _isDarkTheme variable that is utilized to monitor the ongoing theme and we have two functions.

import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_switch_theme_demo/repositories/theme_repo.dart';

part 'theme_state.dart';

class ThemeCubit extends Cubit<ThemeState> {
ThemeCubit({
required ThemeRepository themeRepository,
}) : _themeRepository = themeRepository,
super(const ThemeState());

final ThemeRepository _themeRepository;
static late bool _isDarkTheme;

void getCurrentTheme() {
final isDarkTheme = _themeRepository.getTheme();
_isDarkTheme = isDarkTheme;
emit(state.copyWith(themeMode: isDarkTheme ? ThemeMode.dark : ThemeMode.light));
}

Future<void> switchTheme() async {
_isDarkTheme = !_isDarkTheme;
await _themeRepository.setTheme(isDarkTheme: _isDarkTheme);
emit(state.copyWith(themeMode: _isDarkTheme ? ThemeMode.dark : ThemeMode.light));
}
}

The primary function is the getCurrentTheme function that calls the getTheme function from the ThemeRepository class. Given the result of the getTheme function we set the _isDarkTheme variable and update the state with the ongoing ThemeMode utilizing the emit function.

The second function switchTheme is utilized to switch between ThemeMode.light and ThemeMode.dark. Given the value of the _isDarkTheme variable, we update the actual variable and update the state with the refreshed ThemeMode.

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

In the main.dat file, In the beneath code, we changed the main function to nonconcurrent. Inside the main function, we start by calling the WidgetsFlutterBinding.ensureInitialized capability to guarantee that the bindings are initialized. Solely after the bindings are introduced we can get to the SharedPreferences occurrence which is finished by calling the init capability of the SharedPreferencesController class.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_switch_theme_demo/cubits/theme_cubit.dart';
import 'package:flutter_switch_theme_demo/repositories/share_pref.dart';
import 'package:flutter_switch_theme_demo/repositories/theme_repo.dart';
import 'package:flutter_switch_theme_demo/splash_screen.dart';

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferencesController.init();
runApp(const MyApp());
}

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

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Splash());
}
}

class HomePage extends StatefulWidget {
const HomePage({
required ThemeRepository themeRepository,
super.key,
}) : _themeRepository = themeRepository;

final ThemeRepository _themeRepository;

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return MultiRepositoryProvider(
providers: [
RepositoryProvider<ThemeRepository>(
create: (context) => widget._themeRepository,
),
],
child: MultiBlocProvider(
providers: [
BlocProvider(
create: (BuildContext context) =>
ThemeCubit(themeRepository: widget._themeRepository)
..getCurrentTheme())
],
child: BlocBuilder<ThemeCubit, ThemeState>(
builder: (BuildContext context, ThemeState state) => MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(useMaterial3: true),
darkTheme: ThemeData.dark(useMaterial3: true),
themeMode: state.themeMode,
home: Scaffold(
appBar: AppBar(
title: const Text("Flutter Theme Switch Demo"),
backgroundColor: Colors.cyan,
actions: [
Switch(
value: state.themeMode == ThemeMode.dark,
onChanged: (_) async =>
context.read<ThemeCubit>().switchTheme(),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset(
"assets/logo.png",
height: MediaQuery.of(context).size.height * 0.14,
))
],
),
),
),
),
),
);
}
}

In a similar file, we will make a HomePage class. The HomePage widget requires a case of the ThemeRepository class. This case can be passed inside its constructor. Later on, the instance of the ThemeRepository class is utilized in the MultiRepositoryProvider and MultiBlocProvider class. Both provider classes are important to guarantee that we can around the globally access occurrences of ThemeRepository and ThemeCubit all through our application.

Additionally, to get the underlying subject we call the getCurrentTheme function quickly utilizing the cascade notation on the ThemeCubit case. To guarantee that our MaterialApp widget knows about the ongoing theme we enveloped the widget with a BlocBuilder widget. The BlocBuilder widget is of type ThemeCubit and ThemeState thusly we approach the ThemeState inside our MaterialApp widget.

Inside our MaterialApp widget, we characterize both the light theme utilizing the theme property and the dark theme utilizing the darkTheme attribute. We likewise set the themeMode trait to state.themeMode to guarantee that it is generally equivalent to the themeMode of the ThemeState example produced by the ThemeCubit.

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


Conclusion:

In the article, I have explained the Switch Theme Using Bloc With Cubit in a flutter; you can modify this code according to your choice. This was a small introduction to Switch Theme Using Bloc With Cubit 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 Switch Theme Using Bloc With Cubit in your Flutter projects. We will show you what the Introduction is?. Make a demo program for working on Switch Theme Using Bloc with Cubit the flutter_bloc package and the equatable 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 Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

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


FlyWeight Design Pattern In Flutter

0

The Flyweight design is tied in with utilizing memory proficiently. If your Dart or Flutter application manages moderately overwhelming items, and it needs to launch a large number of them, using this pattern can help spare memory and increment execution by staying away from information duplication. Articles that have the same information can share that information as opposed to replicating it wherever it’s required.

In this article, we will explore the Flyweight Design Pattern in a flutter. We will implement a demo flyweight design pattern in your flutter applications.

Table of Contents:

Design Pattern

Structural Design Patterns

Flyweight Design Pattern

Applicable

Code Implementation

Code File

Conclusion



Design Pattern

Design Pattern could be characterized as a typical repeatable answer for repeating issues in programming design. Design patterns can not be identified with a completed design that will be legitimately utilized in code; however, it could be comprehended as a portrayal or layout for how to tackle any normal issue that may happen as a rule.

So If we experience this Definition we will find that

  • It is an answer to repeating issues of programming development.
  • It’s anything but an example code that will be legitimately utilized in the task.
  • It is only a layout that assists with taking care of any difficulty that happens in programming development.

Structural Design Patterns

Structural patterns assist us with molding the connections between the objects and classes we make. These patterns are centered around how classes acquire from one another, how items can be made out of different objects, and how objects and classes interrelate. In these articles, you’ll figure out how to manufacture enormous, complete frameworks from easier, singular modules and parts. The pattern helps us in making adaptable, inexactly coupled, interconnecting code modules to finish complex undertakings in a reasonable manner.

  • Flyweight:- It contains an inherent state while the extrinsic state is passed to the Flyweight’s strategies. The object should be shareable.
  • FlyweightFactory:- It creates and oversees flyweight objects. At the point when a customer calls the factory, it checks whether the particular flyweight object exists. In the event that indeed, it is basically come back to the customer, in any case, another example of the flyweight object is made and afterward returned.
  • Context:- It contains the extrinsic state, special over every single unique item.
  • Client:- It computes or stores the outward condition of Flyweight (s) and keeps up a reference to it/them.

Flyweight Design Pattern

Flyweight has a place with the classification of structural design patterns. Utilize sharing to help huge quantities of fine-grained protests productively.

To spare space, you can isolate the natural state into a flyweight object, making just one duplicate of every one of a kind sort and reserving it for reuse. The extrinsic state goes in its own object, alongside a reference to the natural express the item needs. Rather than putting away similar information in various objects, you can store inherent information in only a couple of flyweight protests that are connected to suitable setting objects, where extrinsic information is kept.

Applicable

The Flyweight design pattern ought to be utilized just when your program must help a colossal number of items which scarcely fit into accessible RAM. The example’s adequacy relies upon how and where it’s utilized. It would be the most valuable when:

  • An application utilizes countless objects.
  • The object channel all accessible RAM on an objective device.
  • The items contain copy states which can be separated and shared between various objects.
  • Numerous gatherings of objects could be supplanted by a couple of shared items once the extrinsic state is expelled;
  • The application doesn’t rely upon object personality. Since flyweight objects are shared, adroitly particular items could be considered as a similar object.

Code Implementation

Shape Type

It is a enumerator class defining possible shape types was Circle and Square.

Circle and Square are concrete situated shape classes that actualize the abstract class PositionedShape. Both of these shapes have their own intrinsic state: circle characterizes shading and diameter across properties while square contains shading, width properties, and getter tallness, which restores a similar incentive as width.

enum ShapeType {
Circle,
Square,
}

Circle Shape

It is a particular usage of the PositionedShape interface speaking to the shape of a circle.

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/positioned_shape.dart';

class CircleShape implements PositionedShape {
final Color color;
final double diameter;

circleShape({
@required this.color,
@required this.diameter,
}) : assert(color != null),
assert(diameter != null);

@override
Widget render(double x, double y) {
return Positioned(
left: x,
bottom: y,
child: Container(
height: diameter,
width: diameter,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
),
),
);
}
}

Square Shape

It is a particular usage of the PositionedShape interface speaking to the shape of a square

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/positioned_shape.dart';

class SquareShape implements PositionedShape {
final Color color;
final double width;

SquareShape({
@required this.color,
@required this.width,
}) : assert(color != null),
assert(width != null);

double get height => width;

@override
Widget render(double x, double y) {
return Positioned(
left: x,
bottom: y,
child: Container(
height: height,
width: width,
color: color,
),
);
}
}

Positioned Shape

It defines the render() method to be implemented by shape classes.

import 'package:flutter/widgets.dart';

abstract class PositionedShape {
Widget render(double x, double y);
}

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

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_flyweight_design_demo/constants.dart';
import 'package:flutter_flyweight_design_demo/repo/modal/design_pattern_category_modal.dart';
import 'package:flutter_flyweight_design_demo/screens/category/category_card.dart';
import 'package:flutter_flyweight_design_demo/utils/custom/custom_back_button.dart';
import 'package:flutter_flyweight_design_demo/utils/fade_transition.dart';


class CategoryPage extends StatefulWidget {
final DesignPatternCategory category;

const CategoryPage({
@required this.category,
Key key,
}) : assert(category != null),
super(key: key);

@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage>
with SingleTickerProviderStateMixin {
final double _listAnimationIntervalStart = 0.65;
final double _preferredAppBarHeight = 56.0;

AnimationController _fadeSlideAnimationController;
ScrollController _scrollController;
double _appBarElevation = 0.0;
double _appBarTitleOpacity = 0.0;
@override
void initState() {
super.initState();
_fadeSlideAnimationController = AnimationController(
duration: Duration(milliseconds: 1500),
vsync: this,
)..forward();

_scrollController = ScrollController()
..addListener(() {
setState(() {
_appBarElevation =
_scrollController.offset > _scrollController.initialScrollOffset
? 4.0
: 0.0;
_appBarTitleOpacity = _scrollController.offset >
_scrollController.initialScrollOffset +
_preferredAppBarHeight / 2
? 1.0
: 0.0;
});
});
}

@override
void dispose() {
_fadeSlideAnimationController.dispose();
_scrollController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Hero(
tag: "${widget.category.id}",
child: Container(
color: Color(widget.category.color),
),
),
SafeArea(
child: Column(
children: <Widget>[
FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.5),
end: Offset(0.0, 0.0),
),
begin: 0.0,
end: _listAnimationIntervalStart,
child: PreferredSize(
preferredSize: Size.fromHeight(_preferredAppBarHeight),
child: AppBar(
title: AnimatedOpacity(
opacity: _appBarTitleOpacity,
duration: const Duration(milliseconds: 250),
child: Text(widget.category.title),
),
backgroundColor: Color(widget.category.color),
elevation: _appBarElevation,
leading: CustomBackButton(
color: Colors.white,
),
),
),
),
Expanded(
child: ScrollConfiguration(
behavior: ScrollBehavior(),
child: SingleChildScrollView(
controller: _scrollController,
padding: const EdgeInsets.fromLTRB(
paddingL,
paddingZero,
paddingL,
paddingL,
),
child: Column(
children: <Widget>[
FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.5),
end: Offset(0.0, 0.0),
),
begin: 0.0,
end: _listAnimationIntervalStart,
child: Row(
children: <Widget>[
Text(
widget.category.title,
style: Theme.of(context)
.textTheme
.headline6
.copyWith(
fontSize: 32.0,
color: Colors.white,
),
),
],
),
),
const SizedBox(height: spaceL),
for (var i = 0;
i < widget.category.patterns.length;
i++)
FadeTransitionScreen.staggered(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.1),
end: Offset(0.0, 0.0),
),
singleItemDurationInterval: 0.05,
index: i,
begin: _listAnimationIntervalStart,
end: 1.0,
child: Container(
margin: const EdgeInsets.only(top: marginL),
child: CategoryCard(
designPattern: widget.category.patterns[i],
),
),
),
],
),
),
),
),
],
),
),
],
),
);
}
}

In this screen, a title and card have shown with description. The description comes to the JSON file.

Shape Data

A data class which defines the create shape() method to create a shape by providing its type.

import 'package:flutter/material.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/positioned_shape.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/shape_type.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/shapes/circle_shape.dart';
import 'package:flutter_flyweight_design_demo/flyweight_patterns/shapes/square_shape.dart';
class ShapeData {
PositionedShape createShape(ShapeType shapeType) {
switch (shapeType) {
case ShapeType.Circle:
return CircleShape(
color: Colors.red.withOpacity(0.2),
diameter: 10.0,
);
case ShapeType.Square:
return SquareShape(
color: Colors.blue.withOpacity(0.2),
width: 10.0,
);
default:
throw new Exception("Shape type '$shapeType' is not supported.");
}
}
}

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

Scaffold(
bottomNavigationBar: FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 1.0),
end: Offset(0.0, 0.0),
),
begin: _contentAnimationIntervalStart,
end: 1.0,
child: BottomNavigationBar(
currentIndex: _tabController.index,
backgroundColor: Colors.pink[200],
elevation: _bottomNavigationBarElevation,
selectedIconTheme: IconThemeData(size: 20.0),
selectedItemColor: Colors.black,
unselectedIconTheme: IconThemeData(size: 20.0),
unselectedItemColor: Colors.black45,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
title: Text('Data'),
icon: Icon(FontAwesomeIcons.file,color: Colors.greenAccent,),
),
BottomNavigationBarItem(
title: Text('Demo'),
icon: Icon(FontAwesomeIcons.solidLightbulb,color: Colors.greenAccent,),
),
],
onTap: onBottomNavigationBarItemTap,
),
),
body: Stack(
children: <Widget>[
Hero(
tag: "${widget.designPattern.id}",
child: Container(
color: Colors.pink[200],
),
),
SafeArea(
child: Column(
children: <Widget>[
FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.5),
end: Offset(0.0, 0.0),
),
begin: 0.0,
end: _contentAnimationIntervalStart,
child: PreferredSize(
preferredSize: Size.fromHeight(_preferredAppBarHeight),
child: AppBar(
title: AnimatedOpacity(
opacity: _appBarTitleOpacity,
duration: const Duration(milliseconds: 250),
child: Text(
widget.designPattern.title,
style: TextStyle(
color: Colors.black,
),
),
),
backgroundColor: Colors.pink[200],
elevation: _appBarElevation,
leading: CustomBackButton(
color: Colors.black,
),
),
),
),
Expanded(
child: TabBarView(
controller: _tabController,
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
ScrollConfiguration(
behavior: ScrollBehavior(),
child: SingleChildScrollView(
controller: _scrollController,
padding: const EdgeInsets.fromLTRB(
paddingL,
paddingZero,
paddingL,
paddingL,
),
child: Column(
children: <Widget>[
FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.25),
end: Offset(0.0, 0.0),
),
begin: 0.0,
end: _contentAnimationIntervalStart,
child: DesignPatternHeader(
designPattern: widget.designPattern,
),
),
const SizedBox(height: spaceL),
FadeTransitionScreen(
controller: _fadeSlideAnimationController,
slideAnimationTween: Tween<Offset>(
begin: Offset(0.0, 0.01),
end: Offset(0.0, 0.0),
),
begin: _contentAnimationIntervalStart,
end: 1.0,
child: FutureBuilder(
future:
repository.get(widget.designPattern.id),
initialData: "",
builder: (_, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return MarkdownBody(
data: snapshot.data,
);
}
                                return CircularProgressIndicator(
backgroundColor: lightBackgroundColor,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.black.withOpacity(0.65),
),
);
},
),
),
],
),
),
),
widget.example,
],
),
),
],
),
),
],
),
);

In this screen, we will add a tab bar with heading and icons, and add dummy data on this page.

Flyweight Page

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

Stack(
children: <Widget>[
for (var shape in _shapesList)
PositionedShapePage(
shape: shape,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SwitchListTile.adaptive(
title: Text(
'Flyweight Data',
style: TextStyle(color: Colors.black,fontSize: 25,
fontWeight: FontWeight.bold,
),
),
activeColor: Colors.black,
value: _useFlyweightFactory,
onChanged: _toggleUseFlyweightFactory,
),
],
),
Center(
child: Text(
'Shape count: $_shapeInstancesCount',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
],
);

In this screen, we will add a toggle button and shown shape count on this screen. On this screen, you will see the background circle and square shape with small different colors.

Code File

https://gist.github.com/ShaiqAhmedkhan/6687d8d03c2964bb96c5e79a1f93e89a#file-design_pattern_details-dart

You will see a full code on a GitHub, and this is a small demo implement on a flyweight design pattern, and the below video shows how Flyweight will work.

Conclusion

In the article, I have explained the basic structure of Flyweight, you can modify this code according to your choice, and this was a small introduction of the Flyweight Design Pattern in Flutter from my side .

I hope this blog will provide you with sufficient information in Trying up Flyweight in your flutter projects. This is a demo program that will implement Flyweight design patterns in a flutter, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Flyweight Design Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Google Sign In With Flutter

0

Firebase authentication, for the most part, helps bolster diverse user authentication certifications. It is, for the most part, a mobile backend as a service that presents you with amazing highlights for the advancement of flutter applications. It further aids in giving SDKs and instant UI libraries. This assists with validating your clients for utilizing the application. There are additionally extraordinary authentication highlights supported. This incorporates passwords, telephone numbers, virtual character suppliers through Google, Facebook, Twitter, and substantially more.

In this article, I will be exploring Google Sign In With Flutter and show demo implement Google sign-in using Firebase authentication in your flutter application.

Table of Content :

Flutter 1.7

Google Sign In

Firebase Project Setup

Authentication

Implementation — Setup Configuration

Code Implement

Code File

Conclusion



Flutter 1.7

After the launch of Flutter 1.7, one of the principal things that should have been fixed was AndroidX incompatibilities. Since this has been dealt with the progressions executed in the last half, through Flutter, you will have the option to build up another venture. This should be possible with the assistance of the AndroidX banner to guarantee that the defined activities focus on the new help library.

The library permits developers to update Android applications without stressing over in reverse similarity. Besides, it has thought of help for building portable applications, satisfying about 64 bits of Android applications. This will be conceivable in solitary accommodation. The other improved highlights remembered for Flutter 1.7 are RangeSlide Widget, OpenType Rich Typography Features, Gamer Controller Support, thus substantially more.

Google Sign In

There are a couple of new advances you need to do so as to utilize Google sign in your application. Without finishing every one of these means, in the event that you attempt to utilize Google sign in, your application will simply crash. How about we perceive how to set up Google sign-in utilizing Firebase.

  • Before consolidating the coding structure, there is a requirement for the usage of plugins and resources. Mostly, two plugins are required for the task. This incorporates firebase_auth and google_sign_in.
  • Regarding resources, there is just one picture required that will help in planning the Google Sign in the application.

Firebase Project Setup

Open the Firebase console and click the “Add project” option.

Now choose a Cloud Firestore location

Now read and acknowledge the Terms and Conditions

When done, look down and click “Create Project.”

The platform might take some time to go through your application. Once completed, then click the continue option to open the overview page of the project you made.

Andriod Configuration :

Register your android app, which is generally your application Id in your app-level build. Gradle.

Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory.

  • Add your project-level build.gradle file.
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.3'
}
  • Add your project app-level build. Gradle file
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-analytics:17.2.2'}
apply plugin: 'com.google.gms.google-services'
  • Click on Continue to console and wait for few seconds, and your application will be successfully added with Firebase.

Now you have added Firebase to the Flutter app successfully.

IOS Configuration :

Register IOS app to Firebase, and iOS bundle Id must be the same in the Xcode project and on firebase console.

Download configuration files for your app and adds it to your project folder.

Add firebase dependencies to your project.

  • Make the changes needed in the AppDelegate as suggested by the setup wizard then choose next.
  • Presently check the root folder to run the application. After some time, you may see the setup wizard showing that the application has been remembered for Firebase. Then choose “Continue to the Console” to finish the setup.
  • Presently check the root organizer to run the application. After some time, you may see the arrangement wizard indicating that the application has been remembered for Firebase. At that point, pick “Proceed to the Console” to finish the arrangement.

Authentication

  • Click on the Authentication
  • Click set up the sign-in method.
  • Presently edit google sign-in, and you need to enter the project name and support email. Empower this by tapping the switch on the upper right corner. At that point, click Save.
  • Go to project settings and then open the general tab.
  • Scroll down the screen and click Add app. Then we will be added the SHA key.

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

firebase_auth: ^latest version
google_sign_in: ^latest versioin

Step 2: Add Assets

Add assets to pubspec — yaml file.

We will add images in the assets folder

assets:
- assets/

Step 3: Import

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

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

Step 5: We will now create an instance of FirebaseAuth and GoogleSignIn.

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();

Step 6: Enable AndriodX

Add this to your gradle.properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file:

You need to implement it in your code respectively:

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

SingleChildScrollView(
child:Column(
children: <Widget>[
Container(
height: deviceSize.height/2.4,
width: deviceSize.width/3,
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage('assets/weddinglogo.png'),
),),),

Container(
child: Form(
key: _userLoginFormKey,
child: Padding(
padding: const EdgeInsets.only(top:5.0,bottom:15,left: 10,right: 10),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: Text("Login",style:TextStyle(fontWeight: FontWeight.w800,fontSize: 25),),
),
Padding(
padding: const EdgeInsets.only(top:15.0,right: 14,left: 14,bottom: 8),
child: TextFormField(
controller: model.userIdController,
style: TextStyle(color: Colors.black,fontWeight:FontWeight.bold,fontSize: 15),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius
.all(
Radius.circular(15)),
),
hintText: "Email",
hintStyle: TextStyle(fontSize: 15) ,
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
),
cursorColor:Colors.black,
keyboardType: TextInputType.emailAddress,
inputFormatters: [
BlacklistingTextInputFormatter
.singleLineFormatter,
],),),
Padding(
padding: const EdgeInsets.only(top:5.0,right: 14,left: 14,bottom: 8),
child: TextFormField(
controller: model.passwordController,
obscureText: !model.passwordVisible,
style: TextStyle(color: Colors.black,fontWeight:FontWeight.bold,fontSize: 15),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius
.all(
Radius.circular(15)),
),
hintText: "Password",
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintStyle: TextStyle(fontSize: 15) ,
suffixIcon: IconButton(
icon: Icon(model
.passwordVisible
? Icons.visibility
: Icons.visibility_off,color: Color(0xFFE6E6E6),),
onPressed: () {
model.passwordVisible =
!model
.passwordVisible;
}),),
cursorColor:Colors.black,
inputFormatters: [
BlacklistingTextInputFormatter
.singleLineFormatter,
],),),
SizedBox(height: 16,),
InkWell(
child: Container(
width: deviceSize
.width/2,
height: deviceSize.height/18,
margin: EdgeInsets.only(top: 25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:Colors.black
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 30.0,
width: 30.0,
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage('assets/google.jpg'),
fit: BoxFit.cover),
shape: BoxShape.circle,
),
),
Text('Sign in with Google',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.white
),
),
],
)
)
),
onTap: ()
async{
hp signInWithGoogle(model)
.then((FirebaseUser user){
model.clearAllModels();
Navigator.of(context).pushNamedAndRemoveUntil
(RouteName.Home, (Route<dynamic> route) => false
);}
).catchError((e) => print(e));
},
),
SizedBox(height: 16,),
],),
),),
),),
],),
),

In this login screen, we will add a logo, two text fields, and sign with the Google button. Login Screen should be a Stateful Widget since we will roll out certain improvements to the UI later, which will require the widgets to be redrawn.

Now we have to design the Sign in with Google button inside the function signInWithGoogle.

Future<FirebaseUser> signInWithGoogle(SignInViewModel model) async {
  model.state =ViewState.Busy;

 GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();

 GoogleSignInAuthentication googleSignInAuthentication =

await googleSignInAccount.authentication;

  AuthCredential credential = GoogleAuthProvider.getCredential(

 accessToken: googleSignInAuthentication.accessToken,

 idToken: googleSignInAuthentication.idToken,

  );

 AuthResult authResult = await _auth.signInWithCredential(credential);

 _user = authResult.user;

 assert(!_user.isAnonymous);

  assert(await _user.getIdToken() != null);

 FirebaseUser currentUser = await _auth.currentUser();

assert(_user.uid == currentUser.uid);

model.state =ViewState.Idle;Google sign-in with Flutter using Firebase authentication

print("User Name: ${_user.displayName}");
  print("User Email ${_user.email}");




In the signInWithGoogle strategies, we need to utilize the Google sign-in information to authenticate a FirebaseUser and afterward return that user.

If Google sign-in is successful, we will be taken to the HomeScreen which we will be implementing next.

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

body: Container(
child: Padding(
padding: const EdgeInsets.all(48.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Center(
child: Text(
'Welcome User',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
),
SizedBox(height: 40),

Image.asset("assets/girl.jpg",scale: 5,),
SizedBox(height: 40),
RaisedButton(
onPressed: () {
signOutGoogle();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {return LoginScreen();}), ModalRoute.withName('/'));
},
color: Colors.black,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Sign Out',
style: TextStyle(fontSize: 25, color: Colors.white),
),
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40)),
)
],
),
),
),

In this screen, we will add a title, image, and sign out button.HomeScreen Should be a Stateful / Stateless Widget.

Now we have to design the Sign Out button inside the function signoutGoogle.

void signOutGoogle() async{
await _googleSignIn.signOut();
print("User Sign Out");
}

In the signOutGoogle methods, we have to just sign out of the current Google account.

Code File

https://gist.github.com/ShaiqAhmedkhan/ffa2e941bd94916abdcbf1b967c8739f#file-login_screen-dart

You will see a full code on GitHub, and this is a small demo program to integrate with Google Sign-In using Firebase authentication, and the below video shows how Google Sign-In will work.

Conclusion

In the article, I have explained the basic architecture of Google Sign In, you can modify this code according to your choice, and this was a small introduction of Google Sign-In using Firebase authentication from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Google Sign-In in your flutter projects. This is a demo program that will integrate Google Sign-In using firebase authentication in a flutter, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Google Sign In Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


NavigationRail Widget In Flutter

0

As a Flutter application developer, you need to stay up to date with new UI designs out there. I always tend to use new widgets, animations, and Ui designs for making my apps more beautiful. One such attractive tool was added to the inventory with v1.17 Stable release of Flutter, and it is a NavigationRail Widget.

In this article, we will discuss the Navigation Rail Widget In Flutter. We will show a small demo program to integrate navigation rail into your flutter applications.

Table of Contents:

NavigationRail Widget — Introduction

Screen Layout

NavigationRailDestination

NavigationRail Properties

Vertical Text

Code File

Conclusion



NavigationRail Widget

The NavigationRail is practically comparable in working with BottomNavigationBar. The two of them can likewise be utilized pair to make a consistent encounter across devices. In Flutter’s official described documentation, it’s a material widget and can be put at left or right on the screen, and you can explore between a different modest number of screens or fragments anything you desire to call them.

You can use both NavigationRail and BottomNavigationBar for creating seamlessly interesting UI design.

Screen Layout

The place of NavigationRail isn’t pre-characterized dispensed to itself in a Scaffold. Disparate the AppBar or the BottomNavigationBar, A navigation rail is typically utilized as the first or last component of a Row widget, which characterizes the Scaffold body.

The main content and the rail are commonly isolated by a vertical divider. It is wrapped by an Expanded widget to occupy the rest of the space on the screen. The elevation property of the NavigatonRail can likewise be utilized for the equivalent.

It is a simple class; it used to creates tappable navigations in NavigationRail. It holds the data to represent that navigation or destination view/fragment. It’s not a Widget class, and further, it contains three more properties are:

  • Icon: Icon widget is commonly positioned, and furthermore can take any widget. It must always be non-null.
  • Selected Icon: It’s an optional and not compulsory field. We will show you a dashboard as a selected Icon and date_range as an icon. So, a kind of filled icon can be placed here.
  • Label: It must be non-null. A required field, which is to be doled out with a Text Widget that goes about as title for explicit destination and situated underneath the icon. The label can be appeared or hidden utilizing the label type property of the NavigationRail.
NavigationRailDestination(
icon: Icon(Icons.date_range),
selectedIcon: Icon(Icons.dashboard),
label: Text('Trending'),
),

NavigationRail Properties

Some navigation rail properties ar as follows:

  • OnDestinationSelected: This property called when one of the destinations is chosen. The stateful widget that makes the navigation rail needs to monitor the record of the chose NavigationRailDestination and call ‘setState’ to reconstruct the navigation rail with the new selectedIndex.
  • Destinations: This property takes a rundown of NavigationRailDestination objects. The rundown ought to contain at least two things and like BottomNavigationBar for things property.
  • GroupAlignment: This property used to set the vertical alignment of the rail destinations. We will take a value between -1.0 and 1.0. The implicit default value is -1.0, which sets the alignment to Top. The value of 0.0 aligns it to the CenterThe value of 1.0 aligns the rail items to the Bottom. Arbitrary values between the range can also be assigned.
  • SelectedIconTheme UnselectedIconTheme: This property utilized, you can characterize the coloropacity, and size of the Icons of the NavigationRailDestination objects, when they are chosen and when they are most certainly not.
  • SelectedLabelTextStyle & UnselectedLabelTextStyle: You can use these properties can customize the look and style of the text labels for selected/unselected states or underneath NavigationRailDestintaion . You need to assign TextStyle objects to these properties.
  • Label Type: This property takes an enum class NavigationRailLabelType value, which gives you three options.
NavigationRailLabelType.selected
NavigationRailLabelType.none
NavigationRailLabelType.all

Selected will show all icons and only label when a destination is selected. All will show labels and icons the whole time, whether selected or not, and none will hide all the labels in every scenario, only icons will be shown.

  • MinWidth: This property characterizes the width of NavigationRail. As a matter, of course, its default values are 72; however, you can change the incentive for making a reduced Rail also.
  • SelectedIndex: This property characterizes the file that will define the at present chosen NavigationRailDestination.
  • Leading & Trailing: These properties work in the same way as they do in other widgets like ListTile, AppBar, etc. These take in any Widget objects. Hence in the design below, it was easy to nest multiple widgets inside a Column or ListView if necessary and pass it as leading or trailing.

Vertical Text

We will utilize a widget RotatedBox for adjusting my Text widget vertical direction, which can be utilized, even in the Compact method of the NavigationRail.

NavigationRailDestination(
icon: SizedBox.shrink(),
label: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: RotatedBox(
quarterTurns: -1,
child: Text("Welcome"),
),
),
);

Code File

https://gist.github.com/ShaiqAhmedkhan/8d86b429d5d0a21f664749dbcfe41e3f#file-home_screen-dart

You will see a full code on a GitHub, and this is a small demo program to integrate with NavigationRail, and the below video shows how NavigationRail will work.

Conclusion:

Navigation Rail Widget is a significantly trending design procedure. You can make unique Ui with new content for users, in this widget, not using the app bar and bottom navigation bar in a scaffold. You can use RotatedBox for aligning labels and icons in the horizontal or vertical direction.

In the article, I have explained all properties of Navigation Rail Widget you can modify this code according to your choice, and this was a small introduction of Navigation Rail from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Navigation Rail Widget in your flutter projects. This is a demo program that will integrate Navigation Rail in a flutter, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Navigation Rail Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Liquid Swipe Animation In Flutter

0

It’s very much-structured animations cause a UI to feel progressively natural, add to the smooth look and feel of a cleaning application, and improve the user experience. Flutter’s movement bolster makes it simple to actualize an assortment of animation types. Numerous widgets, particularly Material widgets, accompany the standard movement impacts characterized in their plan spec, but on the other hand, it’s conceivable to redo these impacts.

In today’s article, I am going to explore Liquid Swipe Animation in Flutter. We will show a demo program to integrate a liquid Swipe animation into your flutter application. Liquid Swipe animation is impressive, and it was Created for the Andriod Platform, iOS Platform, and React Native Platform.

Table of Contents:

Liquid Swipe Animation — Introduction

Implementation — Setup Configuration

Code Implementation

Code File

Conclusion



Liquid Swipe Animation

Liquid Swipe animation is a movement on the screen that has a water-like feel. These animations, as often as possible, have a moderate, flowy development that may wave or repeating designs. (Furthermore, that is what makes it work; liquid swipe animation needs to feel realistic.) Liquid swipe animation may create results as a floating state or swiping action.

This method has genuinely begun to detonate in prevalence, for the most part since ioS, Andriod, and Web devices can render the strategy productively. For this animation, we are will Need liquid_swipe Package. Liquid Swipe is the Unveils a New Page like Liquid Animation

liquid_swipe | Flutter Package
This repository contains the Liquid Swipe source code. Liquid Swipe is the revealing clipper to bring off amazing…pub. dev

Implementation :

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

liquid_swipe: ^latest version

Step 2: Add Assets

Add assets to pubspec — yaml file.

We will add images in the assets folder

assets:
- assets/

Step 3: Import

import 'package:liquid_swipe/Helpers/Helpers.dart';
import 'package:liquid_swipe/liquid_swipe.dart';

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

Step 5: Enable AndriodX

Add this to your gradle.properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file:

You need to implement it in your code respectively:

Liquid Swipe Setup

In the LiquidSwipe() method we need to add pages, enbaleloop, fullTransitionValue, enableSlideIcon, waveType, positionSlideIcon.

body:LiquidSwipe(
pages: page,
enableLoop: true,
fullTransitionValue: 300,
enableSlideIcon: true,
waveType: WaveType.liquidReveal,
positionSlideIcon: 0.5,
),

After that, Create three Container for 3 Pages where we will Create Container widget For Each Separate pages.

final pages = [
Container(...),
Container(...),
Container(...),
];

First Screen

In this screen, we will add a gradient color and show two fields of E-mail and Password.

Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.1, 0.4, 0.8, 1],
colors: [
Color(0xFF4563DB),
Color(0xFF5B16D0),
Color(0xFF5036D5),
Color(0xFF3594DD),
],
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
radius: 70,
backgroundImage: AssetImage("assets/fruit.jpg"),
),
SizedBox(height: 15,),
Text("Flutter Liquid Swipe Demo",style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 20,color: Colors.white),),
SizedBox(height: 15,),
Card(
margin: EdgeInsets.symmetric(vertical: 10,horizontal: 25),

shape: RoundedRectangleBorder(
borderRadius: BorderRadius
.circular(20.0)),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Icon(Icons.email,color: Colors.black,),
SizedBox(width: 10,),
Text("user@gmail.com",style: TextStyle(
color: Colors.black,fontSize: 17,fontWeight: FontWeight.bold),),
],
),
),
),
Card(
margin: EdgeInsets.symmetric(vertical: 10,horizontal: 25),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius
.circular(20.0)),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(15),
child: Row(
children: <Widget>[
Icon(Icons.lock,color: Colors.black,),
SizedBox(width: 10,),
Text("*******",style: TextStyle(
color: Colors.black,fontSize: 17,fontWeight: FontWeight.bold),),
],
),
),
)

],
),
),

Second Screen

On this screen, we will show some foods item in detail.

Container(
color: Colors.cyanAccent[100],
child: Column(
children: <Widget>[
Container(
width:420,
child: Image.asset("assets/food.jpeg",fit: BoxFit.cover,)),
Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
Text("Foods Item",style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 20,color: Colors.blueGrey[800]),),
],
),
),
SizedBox(height: 20,),
ListTile(
leading:Container(
width: 90,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage("assets/pizza.jpeg"),
fit: BoxFit.cover,
),
),
),
title:Text("Pizza",style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 16,color: Colors.black),),
subtitle: Text("Pizza is the world’s greatest food. Nothing says “I love you,” “I’m sorry,” or “Let’s be friends,” better than pizza.",style: TextStyle(
fontSize: 16,color: Colors.grey),),
),
SizedBox(height: 20,),
ListTile(
leading:Container(
width: 90,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage("assets/pasta.jpg"),
fit: BoxFit.cover,
),
),
),
title:Text("Pasta",style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 16,color: Colors.black),),
subtitle: Text("A super quick, healthy and delicious pasta that can de whipped up under\n15 minutes.",style: TextStyle(
fontSize: 16,color: Colors.grey),),
),
SizedBox(height: 20,),
ListTile(
leading:Container(
width: 90,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage("assets/chili.jpeg"),
fit: BoxFit.cover,
),
),
),
title:Text("Chilli Potato",style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 16,color: Colors.black),),
subtitle: Text("Chilli potato is a Indo chinese starter made with fried potatoes tossed in spicy, slightly sweet & sour chilli sauce. ",style: TextStyle(
fontSize: 16,color: Colors.grey),),
),

],
),
),

Third Screen

In this screen, we will show an order success and deliver an order status.

Container(
color: Color(0xFFE7D6F8),
child: Column(
children: <Widget>[
SizedBox(height: 10,),

Image.asset("assets/delivery_man.png"),
SizedBox(height: 30,),
Text('Order Success',
style: TextStyle(
fontSize: 22.0,
color: Colors.black,fontWeight: FontWeight.bold),overflow: TextOverflow
.ellipsis,),
SizedBox(height: 10,),

Text("Now, you're connect directly\nwith your order, lets check the detail\nJust wait your service here",
style: TextStyle(
fontSize: 16.0,
color: Colors.white),overflow: TextOverflow
.ellipsis,textAlign: TextAlign.center,),
],
),
),

Code File

https://gist.github.com/ShaiqAhmedkhan/1e73d999083a9ed0a7805d854a4bc3e3#file-my_home_page-dart

You will see a full code on GitHub, this is a small demo program to integrate with Liquid Swipe Animation, and the below video shows how Liquid Swipe Animation will work.

Conclusion:

Liquid Swipe animation is a significantly trending design procedure. Movement can help keep clients inspired by your UI design longer and furnish one more motivation to collaborate with content. This Ui plan method should look basic and reasonable. Excessively fast movements.

In the article, I have explained the basic architecture of Liquid Swipe Animation you can modify this code according to your choice, and this was a small introduction of Liquid Swipe Animation from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Liquid Swipe Animation in your flutter projects. This is a demo program that will integrate Liquid Swipe Animation in a flutter, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Liquid Swipe Animation Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Explore RangeSlider In Flutter

0

Flutter lets you make lovely, natively assembled applications. The explanation Flutter can do this is Flutter adores Material. As UI configuration keeps on advancing, Material keeps on refreshing its segments, movement, and plan framework. The range slider, an exceptionally adaptable portion for choosing a range of value, has been released in Flutter 1.7.

Flutter recently updated the RangeSlider widgets to the latest Material guidelines. This article explores the changes to the RangerSlider widgets and uses in your flutter application.

Table of Contents:

Range Slider— Introduction

Components

Code Implementation

Use Custom Shapes

Code File

Conclusion



Range Slider

Range sliders have two determination focuses that consider an adaptable change of minimum and maximum value points. This adaptability makes it a valuable segment, for example, when a client likes to control a particular range, for example, showing value focuses or a time.

Components

Range Slider consist of five parts show in above image:

  1. The thumb is the shape that slides on a level plane when the client drags it.
  2. The track is the line that the slider thumb slides along. It has a functioning active and an inactive inert side.
  3. The overlay is the corona impact that shows up while the thumb is squeezed while dragging.
  4. The tick marks are consistently separated imprints that are drawn when utilizing discrete divisions.
  5. The value indicator shows up when the client is dragging the thumb to demonstrate the value being chosen.

Code Implementation

The genuine range slider values are put away as the state in the parent widget. The value is refreshed by calling setState() inside the RangeSlider’s onChange() callback. In other words, so as to have an interactive range slider, the RangeSlider the widget itself must be made inside a StatefulWidget.

RangeValues values = RangeValues(1, 100);

RangeSlider(
activeColor: Colors.red[700],
inactiveColor: Colors.red[300],
min: 1,
max: 100,
values: values,
onChanged: (values){
setState(() {
values =values;
});
}
),

At the point when the thumbs are further separated, contacting the internal track doesn’t choose a thumb

We will add Range labels and divisions

RangeLabels labels =RangeLabels('1', "100");

RangeSlider(
divisions: 5,
activeColor: Colors.red[700],
inactiveColor: Colors.red[300],
min: 1,
max: 100,
values: values,
labels: labels,
onChanged: (value){
print("START: ${value.start}, End: ${value.end}");

setState(() {
values =value;
labels =RangeLabels("${value.start.toInt().toString()}\$", "${value.start.toInt().toString()}\$");
});
}
),

Tick mark

The tick mark size and positioning changed. The tick marks are presently part of the track segment as opposed to expanding the finish of the track. There is additionally padding on the tick mark, so it shows up inside the track component.

Use Custom Shapes

SliderTheme(
data: SliderThemeData(
rangeThumbShape: CustomRangeShape(),
trackHeight: 2
),
),

We will use Slider Theme then add SliderThemeData. In these theme data, we will add range thumb shape, track height, etc. we will add the CustomRangeShape of class into Slider Theme Data

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ranger_slider/main.dart';

class CustomRangeShape extends RangeSliderThumbShape {
static const double _thumbSize = 10.0;

@override
Size getPreferredSize(bool isEnabled, bool isDiscrete){
return Size.fromRadius(_thumbSize);
}

@override
void paint(
PaintingContext context,
Offset center, {
@required Animation<double> activationAnimation,
@required Animation<double> enableAnimation,
bool isDiscrete = false,
bool isEnabled = false,
bool isOnTop,
@required SliderThemeData sliderTheme,
TextDirection textDirection,
Thumb thumb,
}) {
final Canvas canvas = context.canvas;

Path thumbPath;
switch (textDirection) {
case TextDirection.rtl:
switch (thumb) {
case Thumb.start:
thumbPath = _rightShape(_thumbSize, center);
break;
case Thumb.end:
thumbPath = _leftShape(_thumbSize, center);
break;
}
break;
case TextDirection.ltr:
switch (thumb) {
case Thumb.start:
thumbPath = _leftShape(_thumbSize, center);
break;
case Thumb.end:
thumbPath = _rightShape(_thumbSize, center);
break;
}
break;
}
canvas.drawPath(thumbPath, Paint()..color = sliderTheme.thumbColor);
}
}

Path _rightShape(double size, Offset thumbCenter, {bool invert = false}) {
final Path thumbPath = Path();
final double halfSize = size / 1.5;
final double sign = invert ? -1.0 : 1.0;
thumbPath.moveTo(thumbCenter.dx + halfSize * sign, thumbCenter.dy);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy - size);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy + size);
thumbPath.close();
return thumbPath;
}

Path _leftShape(double size, Offset thumbCenter) => _rightShape(size, thumbCenter, invert: true);

The points of interest here are the two overridden methods. The getPreferredSize and paint methods.

The paint method is utilized legitimately for custom drawing. Since we are expanding the RangeSliderThumbShape class, the paint method gets all the important information required for the structure of the thumb, overlay, or whatever other parts that extend out the RangeSliderThumbShape class to manufacture.

Code File

https://gist.github.com/ShaiqAhmedkhan/b28cd4312ab8897588559d50bd13032f#file-main-dart

Conclusion :

This article would serve as an Exploratory article for RangeSlider in Flutter and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up RangeSlider in Flutter in your Flutter projectsYou will use a range slider in your project and update your latest Flutter version. The behavior and visual appearance can be changed in the theme at the global level, or on an instance-by-instance basis. 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.