Google search engine
Home Blog Page 49

Explore Shake Effect In Flutter

0

Animations are a fundamental piece of causing the UI of a mobile application to feel regular and smooth to the client. Smooth transitions and intelligent components make an application charming to utilize. Exacerbate the application through and through. Consequently, learning the basics of animations in any structure is a fundamental stage toward delivering a prevalent user experience.

This article will be Explore Shake Effect In Flutter. We will see how to implement a demo program. We are going to learn about how we can shake effect in your flutter applications.

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

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to implement a Shake Effect in a flutter. It shows how the Shake Effect will work in your flutter applications. It shows our widgets that shake when the user presses the button. Then, the widget will be shaken with some errors. It will be shown on your device.

Demo Module :


How to implement code in dart file :

You need to implement it in your code respectively:

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

We will initially be going to make an animation controller class. We will require AnimationContoller to accomplish our desired impact, so we will make a different abstract state class.

import 'package:flutter/material.dart';

abstract class AnimationControllerState<T extends StatefulWidget>
extends State<T> with SingleTickerProviderStateMixin {
AnimationControllerState(this.animationDuration);

final Duration animationDuration;
late final animationController =
AnimationController(vsync: this, duration: animationDuration);

@override
void dispose() {
animationController.dispose();
super.dispose();
}
}

We will add the final Duration and the final animationController is equal to the AnimationController(vsync: this, duration: animationDuration). Also add dispose() method. In this method, we will add animationController.dispose().

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

We should characterize a StatefulWidget as a subclass that takes a child widget alongside a few adaptable properties. This widget will be mindful to shake our different widgets.

class CustomShakeWidget extends StatefulWidget {
const CustomShakeWidget({
required this.child,
required this.duration,
required this.shakeCount,
required this.shakeOffset,
Key? key,
}) : super(key: key);

final Widget child;
final double shakeOffset;
final int shakeCount;
final Duration duration;

@override
// ignore: no_logic_in_create_state
State<CustomShakeWidget> createState() => CustomShakeWidgetState(duration);
}

There are some properties are:

  • > child: This property is used for the widget that we want to shake.
  • > duration: This property is used for the Shake duration. It represents a difference from one point in time to another.
  • > shakeCount: This property is used for how many times our widget should shake
  • > shakeOffset: This property is used for the shake distance of the widget.

Note: CustomShakeWidgetState is public

Let’s define the CustomShakeWidgetState class with extends custom AnimationControllerState.

class CustomShakeWidgetState extends AnimationControllerState<CustomShakeWidget> {
CustomShakeWidgetState(Duration duration) : super(duration);
..................
.............
}

In this class, we will add a status audience to reset our AnimationController. This is significant as we need to show this error at various times and on the off chance that we don’t reset our controller then we can not see this impact once more.

@override
void initState() {
super.initState();
animationController.addStatusListener(_updateStatus);
}

@override
void dispose() {
animationController.removeStatusListener(_updateStatus);
super.dispose();
}

void _updateStatus(AnimationStatus status) {
if (status == AnimationStatus.completed) {
animationController.reset();
}
}

In the build method, we will utilize the animation with AnimatedBuilder and Transform. translate. We will return an AnimatedBuilder() technique. In this technique, we will add animationController and child. In a child, we will add the widget. child. Likewise, we will add a builder method.

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: animationController,
child: widget.child,
builder: (context, child) {
final sineValue =
sin(widget.shakeCount * 2 * pi * animationController.value);
return Transform.translate(
offset: Offset(sineValue * widget.shakeOffset, 0),
child: child,
);
},
);
}

In the class, we will likewise add the shake() strategy. This strategy will be liable for the shaken impact. This strategy ought to be public. We will add inside an animationController.forward().

void shake() {
animationController.forward();
}

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

In the main. dart file, we will create a HomeScreen class. In this class, we will utilize GlobalKey to control the shaken impact (or to shake our widgets). Flutter gives GlobalKey that we can use as per our requirements regardless of the state. For this situation, we will require the state so we can start the shake during any taps. We will add two TextEditingControllers and three GlobalKeys.

late GlobalKey<FormState> _formKey;
late GlobalKey<CustomShakeWidgetState> _emailIDState;
late GlobalKey<CustomShakeWidgetState> _passwordState;
late TextEditingController _emailEditingController;
late TextEditingController _passwordEditingController;

We will create an initState() method. In this method, we will add _formKey is equal to the GlobalKey(), _emailIDState is equal to the GlobalKey(), _passwordState is equal to the GlobalKey(), _emailEditingController is equal to the TextEditingController(), and _passwordEditingController is equal to the TextEditingController().

@override
void initState() {
_formKey = GlobalKey();
_emailIDState = GlobalKey();
_passwordState = GlobalKey();
_emailEditingController = TextEditingController(text: "");
_passwordEditingController = TextEditingController(text: "");
super.initState();
}

Now, we will create a dispose() of the method. In this method, we will add all GlobalKey and TextEditingController.

@override
void dispose() {
_formKey.currentState?.dispose();
_emailIDState.currentState?.dispose();
_passwordState.currentState?.dispose();
_emailEditingController.dispose();
_passwordEditingController.dispose();
super.dispose();
}

In the body, we will create two TextformField widgets. In this widgets will wrap to CustomShakeWidget() method. In this method, we will add key, duration, shakeCount, and shakeOffset.

CustomShakeWidget(
key: _emailIDState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _emailEditingController,
decoration: const InputDecoration(
labelText: "Email id",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Email id is Invalid";
}
return null;
},
keyboardType: TextInputType.emailAddress,
),
),
),
CustomShakeWidget(
key: _passwordState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _passwordEditingController,
obscureText: true,
decoration: const InputDecoration(
labelText: "Password",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Password was Incorrect";
}
return null;
},
keyboardType: TextInputType.visiblePassword,
),
),
),

Now, we will create an ElevatedButton(). In this button, we will add style and the onPressed() function. Also, we will add a child. In a child, we will add the Text “Log In”. When the user presses the button then, our widget will shake with show some errors.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
onPressed: () {
_formKey.currentState?.validate();
if (_emailEditingController.text.isNotEmpty ||
_passwordEditingController.text.isNotEmpty) {
_emailIDState.currentState?.shake();
_passwordState.currentState?.shake();
}
},
child: const Text("Log In"),
),

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_shake_effect_demo/custom_shake_widget.dart';
import 'package:flutter_shake_effect_demo/splash_screen.dart';

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

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

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

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

@override
State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
late GlobalKey<FormState> _formKey;
late GlobalKey<CustomShakeWidgetState> _emailIDState;
late GlobalKey<CustomShakeWidgetState> _passwordState;
late TextEditingController _emailEditingController;
late TextEditingController _passwordEditingController;

@override
void initState() {
_formKey = GlobalKey();
_emailIDState = GlobalKey();
_passwordState = GlobalKey();
_emailEditingController = TextEditingController(text: "");
_passwordEditingController = TextEditingController(text: "");
super.initState();
}

@override
void dispose() {
_formKey.currentState?.dispose();
_emailIDState.currentState?.dispose();
_passwordState.currentState?.dispose();
_emailEditingController.dispose();
_passwordEditingController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Shake Effect Demo"),
automaticallyImplyLeading: false,
backgroundColor: Colors.green,
centerTitle: true,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
CustomShakeWidget(
key: _emailIDState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _emailEditingController,
decoration: const InputDecoration(
labelText: "Email id",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Email id is Invalid";
}
return null;
},
keyboardType: TextInputType.emailAddress,
),
),
),
CustomShakeWidget(
key: _passwordState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _passwordEditingController,
obscureText: true,
decoration: const InputDecoration(
labelText: "Password",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Password was Incorrect";
}
return null;
},
keyboardType: TextInputType.visiblePassword,
),
),
),
const SizedBox(
height: 40,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
onPressed: () {
_formKey.currentState?.validate();
if (_emailEditingController.text.isNotEmpty ||
_passwordEditingController.text.isNotEmpty) {
_emailIDState.currentState?.shake();
_passwordState.currentState?.shake();
}
},
child: const Text("Log In"),
),
],
),
),
),
),
);
}
}

Conclusion:

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

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

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: Explore Exception Handling In Flutter

Related: Explore Dart String Interpolation


Firestore Subcollections In Flutter

0

Firebase is an amazing platform developed by Google to connect mobile and web applications and help developers to improve, build, and grow their apps. Firebase provides us a variety of products Authentication, Realtime Database, Cloud Firestore, Cloud Storage, Cloud Functions, Firebase Hosting, ML Kit. Firebase is highly effective and easy to use.

Firebase cloud firestore is a flexible and scalable database. It offers offline availability of data across your client’s apps and keeps data in-sync across clients apps through realtime listeners.

In this blog, we shall discuss how to work with cloud firestore subcollections:


Table of contents:

::What is subcollection?

::Connecting app to your firebase project

::Creating users collection

::Creating a sub collection

::Fetching a sub collection

::Updating sub collection

::Deleting sub collection


To work with firebase cloud firestore in flutter you need to learn about basic crud operation i.e. uploading data, deleting data, editing data, fetching data.

Using Firebase Firestore in Flutter
Fetching data from cloud firestoremedium.com

What is subcollection?

Let’s understand subcollection through an example, take an example of a shopping application, in this app, there are two people 1st the user that will place the order and the 2nd wander that will accept the user’s orders. For each user, the wander needs to keep a record of every user’s order. So to keep the data in a sequential manner we can create a subcollection in the following manner.

***Subcollection example***

In the above image, you can easily analyze the user’s order in an easier and precise manner. So to create this type of collection we need to specify the documentId .

Why the documentIdis important?

Assigning a specific documentId is very important if you are building two different applications one for the user and the other for a wander. To fetch all the orders with the user’s details we need to get all the documentIdof all orders placed by different users inside our wanders application. So to get that documentId we need to fetch it from the users collection that I have created.

Let me explain to you the whole cycle of getting that documentId :

  1. At the time of user authentication auserId is generated by the firebase, we will use this userId and upload it along with user information on cloud firestore inside a users collection.
await FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user.uid)
.set({
'username': username,
'email': email,
'laundryBagNo': laundryBagNo,
'image_url': url,
'userId': userCredential.user.uid //this_one
});

2. Now in the other application we will fetch the stream of users and using the snapshot of the stream we will get all the userId i.e.

‘userId’: userCredential.user.uid //this_one

StreamBuilder(
stream:
FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, userSnapshot) {
return userSnapshot.hasData
? ListView.builder(
itemCount: userSnapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot userData =
userSnapshot.data.documents[index];
if (userData
.data()['laundryBagNo']
.toString()
.startsWith('B-') &&
boys)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else if (userData
.data()['laundryBagNo']
.toString()
.startsWith('G-') &&
girls)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else
return SizedBox();
})
: CircularProgressIndicator();
},
),

Now we can access the subcollection that we have created named order and we use this id to get all the users and orders.

***Uploading user data on cloud firestore inside users collection***
***Uploading user orders inside orders collection using userId as document id***
***User order documents inside the user_orders sub collection***

Connecting app to your firebase project:

If you are new to firebase then you can follow the steps that I have mentioned in my crud operation blog to connect your apps to Firebase, you can add more then one app to your firebase project:

Using Firebase Firestore in Flutter
Fetching data from cloud firestoremedium.com

Creating users collection:

As we have discussed above, we need a users collection that will store the userId and other users information. We will create this collection when the user signs up.

await FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user.uid)
.set({
'username': username,
'email': email,
'laundryBagNo': laundryBagNo,
'image_url': url,
'userId': userCredential.user.uid
});

Here users is a collection that contains a document whose id is userId i.e. userCredential.user.uid .

Creating a sub-collection:

orders is a collection that contains a document whose id is the userId that we can easily get through FirebaseAuth instance using currentUser.

User user = FirebaseAuth.instance.currentUser; , inside this document, we will create another collection user_orders . user_orders is our sub-collection.

await FirebaseFirestore
.instance
.collection('orders')
.doc(user.uid)
.collection(
"user_orders")
.add({
//add your data that you want to upload
});

Fetching a sub-collection:

To fetch orders subcollection we will need the documentId , so to get the documentId we need to fetch the users collection to get the userId .

StreamBuilder(
stream:
FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, userSnapshot) {
return userSnapshot.hasData
? ListView.builder(
itemCount: userSnapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot userData =
userSnapshot.data.documents[index];
if (userData
.data()['laundryBagNo']
.toString()
.startsWith('B-') &&
boys)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else if (userData
.data()['laundryBagNo']
.toString()
.startsWith('G-') &&
girls)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else
return SizedBox();
})
: CircularProgressIndicator();
},
)

UserCard is a widget that displays the user details and on taping it new screen is pushed that contains all the orders of that particular user.

Now we will use the userId to fetch the sub-collection.

class CurrentOrders extends StatelessWidget {
final String userId;

CurrentOrders({
@required this.userId,
});

@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.snapshots(),
builder: (context, orderSnapshot) {
return orderSnapshot.hasData
? ListView.builder(
itemCount: orderSnapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot orderData =
orderSnapshot.data.documents[index];
return OrderItem();
},
)
: CircularProgressIndicator();
});
}
}

Updating sub-collection:

FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.doc(orderData.id)
.update(
{'key': 'new_value'});

Deleting sub-collection:

FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.doc(orderData.id)
.delete();

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.

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


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, and Twitter for any flutter related queries.

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

Thank you for reading. 🌸

Unit Testing In Flutter With Mockito

0

It is possible to make unit tests which call to a live server or a database but, doing so would either consume too much time or give unexpected results

Instead of relying on that, the Flutter team has provided us with a fantastic package for mocking dependencies, called Mockito.

What Mockito does is that, it emulates a dummy database and gives us returns based on our results.

So imagine you have a simple function that uses the HTTP package and then fetches results from the database and based on the result aka status code returns either exception or the JSON we required


So let’s write the code for it

Future fetchFromDatabase(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/posts/1');

if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('exception occured!!!!!!');
}
}

In the above code, you can see we created a function that takes an http.Client parameter and on it performs the get operation and provides values to the response variable, and then we check if the response’s status code was 200 which means it was successful or if it was something else then it means the call was a failure and based on the that we return either the json we needed or the exception.

Clear so far? Alright, now we move on to using Mockito to test this function and check it performs accordingly.

first of all please add the dependency for Mockito, as of writing this blog the version 4.1.3 is the highest, but please check pub.dev for the latest version, also add the HTTP package too.

mockito: ^latest version

http: ^latest version

After that is done we will need to create a class that extends the Mock from mockito package and also implements the http.Client

So for that, we will import the http/http.dart as http like so

import 'dart:convert';

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;

These are all of my imports needed for this

Now on to creating the class

class MockitoExample extends Mock implements http.Client {

}

Now what this actually does is that instead of connecting to a live web service or database it actually cuts off and connects to our mock class which allows us to test by providing various results and test it under different conditions

Moving on now we will write test cases, so for a general idea about unit testing in flutter, you can refer to my previous blog post here.

Unit Testing In Flutter
Hello everyone, I am back with another interesting topic- UNIT TESTING IN FLUTTER.medium.com

So first we make a instance of our MockitoExample class and call it mockitoExample and use it in our tests.

Mockito also provides us when and thenAnswer methods which make testing a whole lot easier.

First we will test it in case of Success

test('returns a Map if there is no error', () async {
http.Client mockitoExample = MockitoExample();

when(mockitoExample.get('https://jsonplaceholder.typicode.com/posts/1'))
.thenAnswer((value) async {
http.Response('{"title": "Test"}', 200);
});

expect(await fetchFromDatabase(mockitoExample), isA<Map>());
});

In the above code snippet you can see I have written a test scenario in which the description is “return a map if there is no error”

Now inside When I have used the mockitoExample’s .get() method to get the data from the API, and in the then Answer, I am simply returning the http.Response along with the status code 200 means that it was a success.

Now in the expected part of the test, we use the function we created above-called fetchFromDatabase and provide it our mockitoExample as http.client, which will return us a success, and then we use isA() method in the matcher part of the expect function which is basically a typeMatcher provided to us in the test/flutter_test import, in which we have taken the generic type as a Map since we will be getting a map from the fetchFromDatabase function in this particular case.

Now we test in case of an Error

test('gives us an exception if we get error in our http call', () {
final mockitoExample = MockitoExample();

when(mockitoExample.get('https://jsonplaceholder.typicode.com/posts/1'))
.thenAnswer((value ) async {
return http.Response('Not Found', 404);
});

expect(fetchFromDatabase(mockitoExample), throwsException);
});

This is almost the same as before, we created an instance of MockitoExample, then we passed the same API in when and provided status code 404 in the http.Response part.

Now in the expect we called the fetchFromDatabase function and provided it our mockitoExample as a client and in the matcher part we used throwsException because we know it will give us an exception if the status code is not 200.

That’s just the basic example of writing mock tests using the Mockito package to mock dependencies.

Most of the code idea is taken from the official documentation of Mockito just a bit modified so that it’s easier to understand by everyone.

Write to me in the comments for any problem you face implementing this I will try my best to help you ASAP.

That’s it for this blog lets meet in the next one.


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, and Twitter for any flutter related queries.

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

Thank you for reading. 🌸

2026 Ultimate Guide: Best Practices for AnimatedPositioned Wid…

0

Flutter is an amazing UI tool kit used to create beautiful applications with ease. Flutter provides us a variety of widgets that can be used to create animated and customs widgets.

In this blog, we shall explore AnimatedPositioned widget and we will create a custom screen view demo using Animation and AnimatedPositioned. So let’s get started.

Module Demo :

Note: You can read the full blog here.


Table of Content

:: AnimatedPositioned Widget

:: MainSreen Class

:: Intializing Objects and variables

:: Stack

:: Other Widgets

:: Building dashboard

:: main.dart


AnimatedPositioned Widget

This widget is used to animate the position of a widget implicitly. It fits into a stack list of children just like a regular Positioned widget. It animates the given child position according to the curve, position, and duration specified by the user.

The properties of AnimatedPositioned are: left, right,top, bottom, duration, child,width, onEnd, height , curve and key.

Read more about Animation:

Introduction to Animation in Flutter
Let’s learn how to animate flutter widgets…medium.com

Creating a Custom Sreen View

Creating a MainSreen stateful class with SingleTickerProviderStateMixin

SingleTickerProviderStateMixin used when you have only one Animation Controller in your widget and its job is to provide with ticker value to the Stateful Widget.

class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> with SingleTickerProviderStateMixin{
@override
Widget build(BuildContext context) {
return Container();
}
}

Initializing Objects and variables

Here we have created 4 bool variables to control the animated position of the widget and _controller the object is used to control the animation of the widget and duration controls the animation duration of the widget.

class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> with SingleTickerProviderStateMixin{

bool isLeftCollapsed = true;
bool isRightCollapsed = true;
bool isTopCollapsed = true;
bool isBottomCollapsed = true;
double screenWidth, screenHeight;
final Duration duration = const Duration(milliseconds: 300);
AnimationController _controller;

@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: duration);
}

@override
void dispose() {
_controller.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold();
}
}

Stack

AnimatedPostioned widget can only be only inside the stack children widgets, so we need to use Stack widget to wrap all our widgets inside it.

Scaffold(
body: Stack(
children: <Widget>[
upperBar(),
sideBar(),
bottomBar(),
AnimatedPositioned(
left: isLeftCollapsed ? 0 : 0.5 * screenWidth,
right: isRightCollapsed ? 0 : -0.2 * screenWidth,
top: isTopCollapsed ? 0 : 0.1 * screenHeight,
bottom: isBottomCollapsed ? 0 : 0.1 * screenHeight,
duration: duration,
child: dashboard(context)),
],
),
);

Other Widgets

These widgets are used as a part of the demo UI. bottomBar() , upperBar(),sideBar()widget is used at the bottom of our screen, top of our screen, and left side of the screen respectively.

Widget bottomBar() {
return Positioned(
bottom: 10,
left: 30,
child: Row(
children: [
Text(
"Reset Password",
style: TextStyle(color: Colors.grey, fontSize: 25),
),
SizedBox(
width: 60,
),
Container(
width: 100,
height: 40,
child: Center(
child: Text(
"Log Out",
style:
TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color: Colors.blue),
)
],
));
}

Widget sideBar() {
return Positioned(
left: 30,
top: 250,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Home",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 25),
),
SizedBox(
height: 10,
),
Text(
"My Account",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 25),
),
SizedBox(
height: 10,
),
Text(
"My Orders",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 25),
),
SizedBox(
height: 10,
),
Text(
"Settings",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 25),
),
],
));
}

Widget upperBar() {
return Positioned(
top: 40,
left: 30,
child: Row(
children: [
CircleAvatar(
child: Icon(Icons.person_outline),
),
SizedBox(
width: 10,
),
Text(
"User name",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
SizedBox(
width: 80,
),
Container(
width: 100,
height: 40,
child: Center(
child: Text(
"View Profile",
style:
TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color: Colors.blue),
)
],
));
}

Building dashboard

dashboard() widgets is used at the top of our Stack this widget is going to be animated. In this widget I have created an icon Button the AppBar that will animate the position of dashborad() the widget from the top, bottomand left side of the screen, this can also be used as a custom draweras it looks like a side drawer. Also, we have Animated the top and bottom of the dashboard() .

Logic used

When the user will tap the menu icon the animation will start and isTopCollapsed, isBottomCollapsed, isLeftCollapsed variables will set to there not values i.e. if they are true then they will set to false and vise versa.

When all three variables are false the AnimatedPostioned widget that we have used inside our Stack will animate the position of dashborad() widgets.

AnimatedPositioned(
left: isLeftCollapsed ? 0 : 0.5 * screenWidth,
right: isRightCollapsed ? 0 : -0.2 * screenWidth,
top: isTopCollapsed ? 0 : 0.1 * screenHeight,
bottom: isBottomCollapsed ? 0 : 0.1 * screenHeight,
duration: duration,
child: dashboard(context)),

Widget dashboard(context) {
return SafeArea(
child: Material(
type: MaterialType.card,
animationDuration: duration,
elevation: 8,
child: Scaffold(
appBar: AppBar(
elevation: 0,
title: Text('MarketWatch'),
actions: [
IconButton(
icon: isTopCollapsed
? Icon(
Icons.keyboard_arrow_down_outlined,
size: 40,
color: Colors.white,
)
: Icon(
Icons.keyboard_arrow_up_outlined,
size: 40,
color: Colors.white,
),
onPressed: () {
setState(() {
isTopCollapsed
? _controller.forward()
: _controller.reverse();
isTopCollapsed = !isTopCollapsed;
});
},
)
],
leading: IconButton(
icon: isLeftCollapsed ? Icon(Icons.menu) : Icon(Icons.clear),
onPressed: () {
setState(() {
if (isLeftCollapsed) {
_controller.forward();
} else {
_controller.reverse();
}
isTopCollapsed = !isTopCollapsed;
isLeftCollapsed = !isLeftCollapsed;
isBottomCollapsed = !isBottomCollapsed;
});
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
isBottomCollapsed
? _controller.forward()
: _controller.reverse();
isBottomCollapsed = !isBottomCollapsed;
});
},
child: isBottomCollapsed
? Icon(
Icons.keyboard_arrow_up_outlined,
size: 40,
)
: Icon(
Icons.keyboard_arrow_down_outlined,
size: 40,
),
),
),
),
);
}

main.dart file

https://gist.github.com/anmolseth06/bd391505d4c257a2f74a199ac2f47231#file-main-dart


Thanks for reading this article ❤

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

Clap 👏 If this article helps you.

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

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.

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

DraggableScrollableSheet in Flutter

0

Introduction :

DraggableScrollableSheet widget is a draggable and scrollable widget that responds to drag gestures by resizing the scrollable until a limit is reached and then scrolling. It looks like a sheet that is built in a bottom but actually, it can be dragged and scrolled up to a certain limit. This widget can be dragged along the vertical axis providing a scrolling effect.

Demo Module :


Table of contents:

:: DraggableScrollableSheet class

:: Implementing Sample UI

:: Understanding its properties through stylish UI


DraggableScrollableSheet class :

DraggableScrollableSheet class is basically a widget that looks like a sheet that drags down from the bottom and expands in a vertical direction. This widget expands up to a certain fraction of a screen in an app as per limited height as provided and then enable scrolling effect inside it expanded height. It can be said that it is a bottom appbar that expands its size and contains a list of data inside it which scrolls.

Sample :

This is how this sample UI looks like as shown below…..

Now let’s create one stylish UI and try to explore more of its properties :

Let’s Start:

How to implement-:

Here above the code, you can see that we have used the widget called DraggableScrollableSheet and applied some of its properties to implement UI as shown above.

As you can see above that container is used inside DraggableScrollableSheet which drags by resizing itself until a limit is reached and thus creating ListView.builder inside it which contains a scrollable list inside the container.

Properties used :

initialChildSize: It is an initial size of a DraggableScrollableSheet which will display on our app as soon as we open it. The value provided to it is in fraction. Its default value is 0.5

We have used initialChildSize value as 0.3 thus it will occupy 30% of the space of our screen as soon as we open our app initially.

maxChildSize: It is the maximum size up to we can drag our container(sheet) or we can say that it is the maximum fractional value up to which we can resize our container(sheet) while displaying a widget. Its default value is 1

We have used maxChildSize value as 0.9 thus it will drag or resize until it will occupy 90% space of our screen in our app while dragging.

minChildSize: It is the minimum size up to which we can drop down our container(sheet) while dragging or we can say that it is the minimum fractional value up to which we can minimize the height of the container(sheet) while displaying our widget. Its default value is 0.25

We have used minChildSize value as 0.13 thus it will minimize its size until it occupies 13% space of our screen in our app.

builder:(){}- The builder that creates a child to display in this widget, which will use the provided ScrollController to enable dragging and scrolling of the contents.

If the widget created by the ScrollWidgetBuilder does not use the provided ScrollController, the sheet will remain at the initialChildSize and scrolling takes place inside that initial size only instead of resizing our sheet.

expand: It accepts a boolean value and decides whether the widget should expand available space in its parent or not. Its default value is true.


As you can see above the code that inside ListView.builder we have created a scrolling list of a ListTile that has an image inside a CircleAvatar as leading, title, as well as the icon in trailing of 20 counted items.

For more info visit down the link:

DraggableScrollableSheet class
A container for a Scrollable that responds to drag gestures by resizing the scrollable until a limit is reached, and…api. flutter.dev


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think is required…✔

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.

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

Enhanced Enums with Members In Dart

0

Like many programming languages, Dart permits you to make enums for characterizing limited sets of values. Here and there, you might need to add fields or works to your enum. For instance, there is an enum comprising conceivable situations with every status having a unique code. That was unimaginable until Dart 2.17, which presented improved enums with members.

This article will explore the Enhanced Enums with Members In Dart. We will perceive how to execute a demo program and we are going to learn about how we can use it in your applications.

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::

Creating Enhanced Enum with Members

Finding Enum by Field Value

Code FIle

Conclusion



Creating Enhanced Enum with Members:

The following is a fundamental enum with practically no members.

 enum Status {
pending,
success,
failed,
;
}

We will add a field code to the enum. To do as such, first, we need to add the field to the enum (very much like adding a field to a class in Dart). We likewise need to make a constructor with the field as the boundary and each characterized enum esteem value be characterized by calling the constructor.

  enum Status {
pending(1),
success(2),
failed(3),
;

final int code;

const Status(this.code);
}

In the model above, the code field is final, and that implies it must be instated. It doesn’t permit null values also. If you have any desire to permit null values, simply make the field nullable by adding ?after the sort (for example int?).

You can have more than one field on your enum. Furthermore, you can likewise make your capabilities, similar to the model beneath.

enum Status {
pending(1, false),
success(2, true),
failed(3, true),
;

final int code;
final bool isFinal;

const Status(this.code, this.isFinal);

String getUpperCaseName() {
return name.toUpperCase();
}
}

Finding Enum by Field Value:

Now and again, we need to get the enum value based on its field value. For instance, we need to get the Status enum above by utilizing the given code value.

For that reason, simply make a function that acknowledges the field value as the boundary. Inside the capability, repeat over the possible values which can be acquired from the values field.

 enum Status {
//...
static Status? getByCode(int code) {
for (Status status in Status.values) {
if (status.code == code) {
return status;
}
}

return null;
}
//...
}

Be that as it may, the above code isn’t productive since it will repeat over the values each time the capability is called. The arrangement is by caching the values to a Map.

enum Status {
//...
static final Map<int, Status> byCode = {};

static Status? getByCode(int code) {
if (byCode.isEmpty) {
for (Status status in Status.values) {
byCode[status.code] = status;
}
}

return byCode[code];
}
//...
}

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

import 'package:enums_demo/enums_demo.dart';

void main() {
print(Status.success.getUpperCaseName());
print(Status.success.toString());
print(Status.getByCode(1));
}

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

SUCCESS
success(2)
pending(1)

Process finished with exit code 0

Code File:

enums_demo.dart

enum Status {
pending(1, false),
success(2, true),
failed(3, true),
;

final int code;
final bool isFinal;

static final Map<int, Status> byCode = {};

const Status(this.code, this.isFinal);

static Status? getByCode(int code) {
if (byCode.isEmpty) {
for (Status status in Status.values) {
byCode[status.code] = status;
}
}

return byCode[code];
}

String getUpperCaseName() {
return name.toUpperCase();
}

@override
String toString() {
return "$name($code)";
}
}

main.dart

import 'package:enums_demo/enums_demo.dart';

void main() {
print(Status.success.getUpperCaseName());
print(Status.success.toString());
print(Status.getByCode(1));
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Enhanced Enums with Members of your projects. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Publishing Flutter App To PlayStore

0

Why OPT Flutter to develop your app?

  • :: Flutter is a free and open-source tool to develop mobile, desktop, web apps with a single code base.
  • :: Setting up the Flutter environment on our machine is much easier and straight forward.
  • :: Technical architecture of flutter apps is a much easier, clean, and precise code structure.
  • :: It runs the application at 60–120 frames per second.
  • :: Google, as always, tends to provide clear and in-depth documentation for their products. They did it for Flutter documentation isn’t an exception.

Almost 100,000 + applications have been successfully published in the app store. There are lots of big companies that are using flutter to develop applications. So as a flutter developer you should know how to upload your flutter app to app stores. In this blog, we shall learn how to make our flutter ready for production and publish it on app stores.

Publishing app to app stores is really easy and fun to do. The whole process is divided into four essential steps that are as follows::

Testing::

  1. Testing your app on various devices of different sizes, on older devices, new devices, small screen, big screen of course on android devices, and ios devices if you are planning to publish your app to both platforms.
  2. Use const and new keyword on static widgets to improve app performance.
  3. Try to split your code into smaller widgets file so that you can easily modify if there is any new change.

Prepare 3rd party API::

Add all your API keys so that your users do not face any problem while performing any Rest API request from your app. Please try to maintain them properly and timely.

Add app icon, splash screen, app name::

Setting up the app icon::

To set up an app icon you need an icon image:

  1. Make an assets folder inside your project and store the app icon inside it.
  2. Go to your pubspec.yaml file and add this code
flutter_icons:
android: true
ios: true
image_path: "assets/app_icon.png" //use_your_image_name

3. Run the following command:

flutter packages pub run flutter_launcher_icons:main

Now the app icon is added to your app.

Adding Splash Screen::

Timer widget is a widget that can de used to add a delay between two tasks. We can also use it to add a splash screen for a few seconds.

import 'dart:async';
import 'package:flutter/material.dart';
import 'homePage.dart';

class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
startTime() async {
var _duration = Duration(seconds: 4);
return Timer(_duration, navigationPage);
}

void navigationPage() {
Navigator.of(context).pushReplacementNamed(HomePage.routeName);
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height,
child: Image.asset(
'assets/splashScreen.jpeg',
fit: BoxFit.cover,
)),
Container(
height: MediaQuery.of(context).size.height,
color: Colors.blue.withOpacity(0.2),
),
Positioned(
top: MediaQuery.of(context).size.height * 0.9,
left: MediaQuery.of(context).size.width * 0.15,
child: Row(
children: <Widget>[
Image.asset(
'assets/bottomSplashImage.png',
width: 50,
height: 50,
),
Column(
children: <Widget>[
Text(
"ENERGY & PRESISTENCE",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20),
),
Text(
"CONQUER ALL THINGS",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15,
wordSpacing: 2,
letterSpacing: 4),
)
],
)
],
))
],
),
);
}
}

Timer class – dart:async library – Dart API
API docs for the Timer class from the dart: async library, for the Dart programming language.api.flutter.dev

Adding App Name::

Go to android\app\main\AndroidManifest.xml and change the android label, it will change the application name that will be displayed on your phone as the app name.

<application
android:name="io.flutter.app.FlutterApplication"
android:icon="@mipmap/ic_launcher"
android:label="laundary_application">

Publish app to app store::

Create a Keystore::

Run the following command to a Keystore

for windows

keytool -genkey -v -keystore c:\Users\USER_NAME\key.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias key

for mac/linux

keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

If already have one Keystore you can also use that.

This command will make a key.jks file inside the home directory.

Create a reference of Keystore inside your app::

Create a file inside <app dir>/android/key.properties that contains a reference to your Keystore:

storePassword=testpassword
keyPassword=testpassword
keyAlias=testkey
storeFile=D:/keystore.jks //your_home_directory

Signing in Gradle::

Add the bold content inside your app/build.gradle :

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
compileSdkVersion 28

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}

lintOptions {
disable 'InvalidPackage'
}

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.gymguide.gymguide"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}


}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

Build an apk::

Run flutter build apk on your project terminal and it will build a release apk that we can use to upload on the play store.

Publish app to Google Play Store::

  • Go to Google Play Console.
  • To publish your app on the play store you need to pay $25 to google as a one-time payment.
***Console after paying $25***
  • Click on Create app and fill in the app details.
  • Go through all the steps mentioned in the dashboard section and your app will be live on the play store after google review the app, this step might take hours.

Launch | Google Play | Android Developers
Publish with confidence on Google Play.developer.android.com

Build and release an Android app
During a typical development cycle, you test an app using flutter run at the command line, or by using the Run and…flutter.dev

Build and release an iOS app
This guide provides a step-by-step walkthrough of releasing a Flutter app to the App Store and TestFlight. Before…flutter.dev


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.

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

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.

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

CheckBox ListTile In Flutter

0

In this blog, Here we will implement how to create a checked listview in flutter application. In this app, we will present the normal list item how to display CheckBox List using Flutter CheckboxListTile widget. It will not contain any kind of package in it. We will implement a demo of the CheckboxListTile in your flutter applications.


Table of Contents :

Flutter

CheckBox ListTile

Code Implementation

Code File

Conclusion


Flutter :

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

CheckBox ListTile :

We are going to tell you how to use the checkbox list tile widget. If you must have an input where the user can select several options. The common solutions are to use the checkbox.you can add text or icons to the checkbox for that in the flutter .checkbox usage with icons or images and text may be the solution, but flutter provides an option that makes it much easier. A checkbox ListTile is a widget that combines a checkbox and a List Tile. The List Tile allows us to create a checkbox with the title subtitle without creating separate widgets in all the list item.

Demo Module :

Code Implementation :

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

CheckboxListTile(
activeColor: Colors.pink[300],
dense: true,
//font change
title: new Text(
checkBoxListTileModel[index].title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
letterSpacing: 0.5),
),
value: checkBoxListTileModel[index].isCheck,
secondary: Container(
height: 50,
width: 50,
child: Image.asset(
checkBoxListTileModel[index].img,
fit: BoxFit.cover,
),
),
onChanged: (bool val) {
itemChange(val, index);
})

As we are now going to use the checkbox ListTile widget in this screen. the checkbox list tile has a lot of parameters. But two parameters are very important. you have value (bool) and OnChanged (void function(bool)). In this, we can use the title. And under the title, we can use a subtitle to add more widgets. Just as we use it for details. A checkBox can use the secondary widget in ListTile. This checkbox will be on the opposite side. it is used for Icons or images.

Code File :

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_listtile_demo/model/listtilemodel.dart';

class CheckBoxListTileDemo extends StatefulWidget {
@override
CheckBoxListTileDemoState createState() => new CheckBoxListTileDemoState();
}

class CheckBoxListTileDemoState extends State<CheckBoxListTileDemo> {
List<CheckBoxListTileModel> checkBoxListTileModel =
CheckBoxListTileModel.getUsers();

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.white,
centerTitle: true,
title: new Text(
'CheckBox ListTile Demo',
style: TextStyle(color: Colors.black),
),
),
body: new ListView.builder(
itemCount: checkBoxListTileModel.length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Container(
padding: new EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
new CheckboxListTile(
activeColor: Colors.pink[300],
dense: true,
//font change
title: new Text(
checkBoxListTileModel[index].title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
letterSpacing: 0.5),
),
value: checkBoxListTileModel[index].isCheck,
secondary: Container(
height: 50,
width: 50,
child: Image.asset(
checkBoxListTileModel[index].img,
fit: BoxFit.cover,
),
),
onChanged: (bool val) {
itemChange(val, index);
})
],
),
),
);
}),
);
}

void itemChange(bool val, int index) {
setState(() {
checkBoxListTileModel[index].isCheck = val;
});
}
}

class CheckBoxListTileModel {
int userId;
String img;
String title;
bool isCheck;

CheckBoxListTileModel({this.userId, this.img, this.title, this.isCheck});

static List<CheckBoxListTileModel> getUsers() {
return <CheckBoxListTileModel>[
CheckBoxListTileModel(
userId: 1,
img: 'assets/images/android_img.png',
title: "Android",
isCheck: true),
CheckBoxListTileModel(
userId: 2,
img: 'assets/images/flutter.jpeg',
title: "Flutter",
isCheck: false),
CheckBoxListTileModel(
userId: 3,
img: 'assets/images/ios_img.webp',
title: "IOS",
isCheck: false),
CheckBoxListTileModel(
userId: 4,
img: 'assets/images/php_img.png',
title: "PHP",
isCheck: false),
CheckBoxListTileModel(
userId: 5,
img: 'assets/images/node_img.png',
title: "Node",
isCheck: false),
];
}
}

Conclusion :

In this article, I have explained a CheckBox ListTile demo, you can modify and experiment according to your own, this little introduction was from the CheckBox ListTile our side.

I hope this blog helps will provide you with sufficient information in Trying up the CheckBox ListTile in your flutter project. 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 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.

Related: Dialog Using GetX in Flutter

Related: Switch Theme Using Bloc With Cubit In Flutter

Related: Bottom Navigation Bar using Provider | Flutter

Implementing Pull-To-Refresh In Flutter

0

In this blog, we shall discuss about Pull-To-Refresh feature. Most of the apps that are made today come with API integration, sometimes when there is a change in data of the API the change might not change in realtime in the app so we need to load the data again in our app. Flutter provides us RefreshIndicator widget that can be used to implement the same feature.

RefreshIndicator is a widget that provides us onRefresh a property that we can use for reloading the API data. When the refresh operation is finished it returns a future.


Table of content

Fetching JSON data

Decode data

Fruit Class

Creating MyApp class

Displaying API data

Using RefreshIndicator

Refresh function

main.dart file


Fetching JSON data

  • Here we have created a function fetchFruit() that will fetch the JSON data from the given URL.
Future fetchFruit() async {
final response = await http.get('url');
if (response.statusCode == 200) {
//decode_JSON_data
} else {
throw Exception('Unable to fetch data from the REST API');
}
}

Decode data

  • We can use the decode method to decode the responseBody and then we can map the parsed to list.
List<Fruit> decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
}

Fruit Class

class Fruit {
final int id;
final String title;
final String imageUrl;
final int quantity;

Fruit(
this.id,
this.title,
this.imageUrl,
this.quantity,
);
factory Fruit.fromMap(Map<String, dynamic> json) {
return Fruit(json['id'], json['title'], json['imageUrl'], json['quantity']);
}
factory Fruit.fromJson(Map<String, dynamic> json) {
return Fruit(json['id'], json['title'], json['imageUrl'], json['quantity']);
}
}

Creating MyApp class

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:rest_api_flutter/fruitItem.dart';
import 'dart:async';
import 'fruit.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp(products: fetchFruit()));
class MyApp extends StatelessWidget {
final Future<List<Fruit>> products;

MyApp({this.products});

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

Displaying API data

  • To display the futuredata we need to use FutureBuilder that takes a future and a builder to display the data. Here the products future contains the API data so we need to use the FutureBuilder to display the data. ListView.builder widget can be used to create the list of API data.
FutureBuilder<List<Fruit>>(
future: products,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return FruitItem(item: snapshot.data[index]);
},
)
: Center(child: CircularProgressIndicator());
},
),

Using RefreshIndicator

  • To refresh the future data we need to use the RefreshIndicator widget that provides us onRefresh property that takes the future and it reloads the whole future whenever it is called.
RefreshIndicator(
onRefresh: () => _refreshProducts(context),
child: FutureBuilder<List<Fruit>>(
future: products,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return FruitItem(item: snapshot.data[index]);
},
)
: Center(child: CircularProgressIndicator());
},
),
),

Refresh function

This is used inside the RefreshIndicator to reload the API data.

Future<void> _refreshProducts(BuildContext context) async {
return fetchFruit();
}

Have a look at the main dart file :

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:rest_api_flutter/fruitItem.dart';
import 'dart:async';
import 'fruit.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp(products: fetchFruit()));

class MyApp extends StatelessWidget {
final Future<List<Fruit>> products;

MyApp({this.products});

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

class MyHomePage extends StatelessWidget {
final Future<List<Fruit>> products;

MyHomePage({this.products});

Future<void> _refreshProducts(BuildContext context) async {
return fetchFruit();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Rest API Demo"),
backgroundColor: Colors.cyan,
centerTitle: true,
),
body: Center(
child: RefreshIndicator(
onRefresh: () => _refreshProducts(context),
child: FutureBuilder<List<Fruit>>(
future: products,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return FruitItem(item: snapshot.data[index]);
},
)
: Center(child: CircularProgressIndicator());
},
),
),
));
}
}

Future fetchFruit() async {
final response = await http.get('url');
if (response.statusCode == 200) {
return decodeFruit(response.body);
} else {
throw Exception('Unable to fetch data from the REST API');
}
}

List<Fruit> decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
}

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.

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

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.

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

Pinch Zoom Effect In Flutter

In this article, we will explore the Pinch Zoom Effect in a flutter Using the pinch-zoom-image package. With the help of the package, we can easily achieve flutter pinch_zoom_image.In which we can rotate and zoom the image. and it achieves its position easily.


Table Of Contents :

Flutter

Pinch Zoom Image

Code Implementation

Code File

Conclusion


Flutter :

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

Pinch Zoom Image :

A Pinch Zoom Image is a widget based on flutter’s new interactive viewer that zooms to a picture pinch and returns to its initial shape position upon release. This package is only on the most recent interactive image viewer. that it has been introduced since Flutter’s new version 1.20. We use this flutter package to zoom pictures.

Demo Module :

Implementation :

Step 1: Add dependencies.

Add dependencies to pubspec — yaml file.

dependencies:
pinch_zoom_image_updated: ^latest version

Step 2: import the package :

import 'package:pinch_zoom_image_updated/pinch_zoom_image_updated.dart';

Step 3: Run flutter package get

Code Implement :

Create a new dart file is called custom_progress_indicator.dart inside the lib folder

PinchZoomImage(
image: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(
items.img,
),
),
zoomedBackgroundColor: Color.fromRGBO(240, 240, 240, 1.0),
hideStatusBarWhileZooming: true,
onZoomStart: () {
print('Zoom started');
},
onZoomEnd: () {
print('Zoom finished');
},
),

In this screen, we have used the Pinch Zoom Image widget. In this, we have a list of an image which displays the image. Pinch zoom image will have an image type widget in which we will initialize the image. And the option of zoomedBackgroundColor .In which the color shows in the background after the rotating image.

ListView.builder(
itemCount: pinchZoomModelList.length,
scrollDirection: Axis.vertical,
//shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return _buildPinchModelList(pinchZoomModelList[index], index);
}),

We have taken a screen ListView.Builder widget from this screen, which shows the data in the form of a list.

class PinchZoomModelList{
String _img;
PinchZoomModelList(this._img,);

String get img=>_img;
}

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_pinch_zoom_effect_demo/Constants/Constants.dart';
import 'package:flutter_pinch_zoom_effect_demo/model/pinch_zoom_list_model.dart';
import 'package:pinch_zoom_image_updated/pinch_zoom_image_updated.dart';

class PinchZoomEffectDemo extends StatefulWidget {
@override
_PinchZoomEffectDemoState createState() => _PinchZoomEffectDemoState();
}

class _PinchZoomEffectDemoState extends State<PinchZoomEffectDemo> {
double _height;
double _width;
List<PinchZoomModelList> pinchZoomModelList;

PageController pageController;

@override
void initState() {
pinchZoomModelList = Constants.getPinchZoomModelList();
super.initState();
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;

return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[50],
title: Text(
'Pinch Zoom Effect',
style: TextStyle(color: Colors.black, fontSize: 18),
),
centerTitle: true,
elevation: 1.0,
),
body: Container(
margin: EdgeInsets.only(left: 0, right: 10),
child: ListView.builder(
itemCount: pinchZoomModelList.length,
scrollDirection: Axis.vertical,
//shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return _buildPinchModelList(pinchZoomModelList[index], index);
}),
),
);
}

Widget _buildPinchModelList(PinchZoomModelList items, int index) {
return Container(
padding: EdgeInsets.only(top: 15.0, left: 15, right: 15),
child: PinchZoomImage(
image: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(
items.img,
),
),
zoomedBackgroundColor: Color.fromRGBO(240, 240, 240, 1.0),
hideStatusBarWhileZooming: true,
onZoomStart: () {
print('Zoom started');
},
onZoomEnd: () {
print('Zoom finished');
},
),
);
}
}

Conclusion :

In this article, I have explained a Pinch Zoom Effect demo, you can modify and experiment according to your own, this little introduction was from the pinch-zoom image effect from our side.

I hope this blog helps will provide you with sufficient information in Trying up the Pinch Zoom Effect in your flutter project. In this demo explain the Pinch Zoom Effect through the pinch_zoom_image_updated package 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.


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