How To Use Equatable In Flutter

We are all aware that the “==” comparison operator may be used to compare two items, but can you compare two instances of the same class? As a result, we have Equatable to streamline the laborious process of comparing each instance by overriding “==” and hashCodes.

It’s likely that you’ve had to override the == operator and hashCode in your Dart code in order to compare various instances of the same class.

In this tutorial, we’ll look at Equatable In Flutter. We will utilize the Equatable example program and learn how to use it in our flutter applications.

Equatable:

The Equatable is used to make comparisons between instances of the same object easier without the use of boilerplate hashCodes and overriding “==” codes.

We can Simplify Equality Comparisons by using flutter equatable. The == operator and hashcode must both be overridden in order to compare various instances of the same class. If two objects are instances of the same class, == by default returns true.

Code Execution:

1. Add dependencies

Add dependencies to the pubspec yaml file.

dependencies:
 equatable: ^2.0.3

 2.Import

import 'package:equatable/equatable.dart';

3. Run flutter packages get in the root directory of your app.

Adding code to a Dart file:

You must incorporate it into your code accordingly:

Inside the lib folder, create a new dart file called food.dart.

class Food{
  final String foodName;
  final String foodImage;

  const Food({
    required this.foodName,
    required this.foodImage,
  });
}

Additionally, in the lib folder, make a new dart file called main.dart.

We add two food objects,

final Food mango = const Food(
  foodName: 'Mango',
  foodImage: 'assets/mango.jpg',
);
final Food mango2= const Food(
  foodName: 'Mango',
  foodImage: 'assets/mango.jpg',
);

Attempting to compare these two same things,

Even if you compare the two, they are not the same because Dart does not compare objects based on their value. food and food2 are at different memory regions in this case. It makes no difference if they share the same values. They will be treated as separate objects.

Let’s compare two instances of the same object using equitable.

First, we add Equatable to the current class and then override the getter method props.

import 'package:equatable/equatable.dart';

class Food extends Equatable {
  final String foodName;
  final String foodImage;

  const Food({
    required this.foodName,
    required this.foodImage,
  });

  @override
  List<Object?> get props => [foodName, foodImage];
}

Due to the fact that Equatable is only intended to deal with immutable objects, all member variables must be final.

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

Uses:

Equatable can very handy in a variety of situations, one of which is with flutter bloc. To use this capability in Bloc, we must extend Equatable to the States and Events classes. This is useful when it comes to stream, as we need to decide whether or not to update the state based on it.

As an example,

FetchUserState is an abstract class that extends Equatable.

If the same state happens, FetchUserState will not perform duplicate calls and will not rebuild the widget. Consider how many times the widget would have to be recreated if we hadn’t used Equatablehere.

Code:

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: 'Equatable',
      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 Food foodModel = const Food(
      foodName: 'mango', foodImage: 'assets/mango.jpg');
  final Food food =
      const Food(foodName: 'Mango', foodImage: 'assets/mango.jpg');
  final Food food2 =
      const Food(foodName: 'Mango', foodImage: 'assets/mango.jpg');

  compareFood(BuildContext context) {
    if (food == food2) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text("EQUAL")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("Not EQUAL")));
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title:  Text('Equatable'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            foodWidget(
              foodImage: food.foodImage, foodName: food.foodName,),
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.green),
              ),
              onPressed: () {
                compareFood(context);
              },
              child: const Text("Compare"),
            ),
            foodWidget(
              foodImage: food2.foodImage, foodName: food2.foodName,
            ),
          ],
        ),
      ),
    );
  }

  foodWidget({
    required foodImage,
    required foodName,
  }) {
    return Column(
      children: [
        Image.asset(foodImage, height: 200, width: 200,),
        const SizedBox(height: 5),
        Text(
          foodName,
          style: const TextStyle(
            fontSize: 15,
            fontWeight: FontWeight.w800,
          ),
        ),
      ],
    );
  }
}

Conclusion:

In the post, I explained the fundamental structure of the Equatable in a flutter application; you can modify this code as desired. This was a brief introduction to my Equatable package on User Interaction and how it works with Flutter.

I hope this blog has given you enough information to try out the Equatable package in your flutter projects. What exactly is the Equatable package? the Equatable package’s properties We created an example program to demonstrate how the Equatable package works. So please give it a shot.

Thank you for taking the time to read this article.

Submit a Comment

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

Subscribe

Select Categories