Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Equatable In Flutter

We all know we can compare two things with “==” this operator, but do you know how to compare two instances of the same class?. Well, it is quite a lengthy process, comparing each instance by overriding “==” and hashCodes, and to simply that exact process we have Equatable.

In this article, we will explore Equatable In Flutter. We will implement the Equatable demo program and learn how to use the same in your flutter applications.

equatable | Dart Package
Not only is it verbose and tedious, but failure to do so can lead to inefficient code which does not behave as we…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::

Equatable

Code Implement

Property

Uses

Code File

Conclusion

GitHub Link



Equatable:

The Equatable is used to simplify the process of comparing instances of the same object without the need for boilerplate codes of overriding “==” and hashCodes.

Using flutter equatable we can Simplify Equality Comparisons in order to compare different instances of the same class we have to override the == operator as well as hashcode. By default, == returns true if two objects are the same instance of the class.

Code Implement:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
equatable: ^2.0.3

Step 2: Import

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

class Phone {
final String phoneName;
final String phoneImage;

const Phone({
required this.phoneName,
required this.phoneImage,
});
}

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

We create two phone objects,

final Phone samsung = const Phone(
phoneName: 'Samsung S20 FE 5G',
phoneImage: 'assets/phone1.jpeg',
);
final Phone iphone = const Phone(
phoneName: 'Iphone 11',
phoneImage: 'assets/phone2.jpeg',
);

Now if we try to compare these two objects, they will never be the same,

Output

but if we create two same objects,

final Phone iphone = const Phone(
phoneName: 'Iphone 11',
phoneImage: 'assets/phone2.jpeg',
);
final Phone iphone2 = const Phone(
phoneName: 'Iphone 11',
phoneImage: 'assets/phone2.jpeg',
);

and compare the two still, they are not the same because under the hood Dart doesn’t compare the objects by their value.

Output

here iPhone and iphone2 both objects are in different memory locations. It doesn’t matter if they have the same values. They both will be considered as different objects.

So, what can we do now?

Let’s use equatable for comparing two instances of the same object,

First, we extend the existing class with Equatable, and then override a getter method props.

import 'package:equatable/equatable.dart';

class Phone extends Equatable {
final String phoneName;
final String phoneImage;

const Phone({
required this.phoneName,
required this.phoneImage,
});

@override
List<Object?> get props => [phoneName, phoneImage];
}

Note: Equatable is designed to only work with immutable objects so all member variables must be final.

That’s it!!

Output

Now the two objects are the same based on their values, the prop property of the equatable is further explained below.

Property:

Equatable comes with props property which has its own purpose in object comparison.

Props property decides which objects we should consider for object comparison.Props is a getter method that will return List<Object>. HereObject can be of any type (like : int,double, list etc). You have to simply return a list of all the objects that are available in your class, (phoneName and phoneImage in our case).

Uses:

Equatable is useful in many cases, one of which is with flutter_bloc

In Bloc, we have to extend Equatable to States and Events classes to use this functionality. This helps us when it comes to stream as we need to decide state updation based on it.

For example,

abstract class FetchUserState extends Equatable {}

FetchUserState will not make duplicate calls and is not going to rebuild the widget if the same state occurs. Now, think if we hadn’t used Equatablehere, then how many times the widget will be rebuilt?

Code File:

import 'package:equatable_example/phone.dart';
import 'package:flutter/material.dart';

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
final Phone samsung = const Phone(
phoneName: 'Samsung S20 FE 5G',
phoneImage: 'assets/phone1.jpeg',
);
final Phone iphone = const Phone(
phoneName: 'Iphone 11',
phoneImage: 'assets/phone2.jpeg',
);
final Phone iphone2 = const Phone(
phoneName: 'Iphone 11',
phoneImage: 'assets/phone2.jpeg',
);

comparePhone(BuildContext context) {
if (iphone == iphone2) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text("YES, They are EQUAL")));
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("NO, They are not EQUAL")));
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal,
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Center(child: Text('Equatable Example')),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
phoneWidget(
phoneName: iphone.phoneName, phoneImage: iphone.phoneImage),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green),
),
onPressed: () {
comparePhone(context);
},
child: const Text("Compare"),
),
phoneWidget(
phoneImage: iphone2.phoneImage,
phoneName: iphone2.phoneName,
),
],
),
),
);
}

phoneWidget({
required phoneImage,
required phoneName,
}) {
return Column(
children: [
Image.asset(phoneImage),
const SizedBox(height: 5),
Text(
phoneName,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
),
),
],
);
}
}

Conclusion:

In the article, I have explained the essential construction of the Equatable in a flutter application; you can alter this code as indicated according to your choice. This was a little prologue to the Equatable package on User Interaction from my side, and its functioning utilizing Flutter.

I hope this blog will provide you with sufficient information on Trying up the Equatable package in your flutter projects. We showed you what the Equatable package is? its properties of the Equatable package. We made a demo program for working Equatable package. 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.


Github Link:

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


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.

Leave comment

Your email address will not be published. Required fields are marked with *.