CopyWith ease with Flutter

Olivier Brand
2 min readOct 10, 2021

If you use Flutter Blocs you must be familiar with Equatable. Equatable is an extension that prevents you to override the “==” operator and hashCode functions, thus reducing boilerplate code.

Classes extending Equatable are by nature immutable and enforces you to define all instance variables as final. This is great until you have the need to modify a specific variable from an existing object of such classes.

Example:

class Book extends Equatable {  final String title;  final double rating;  Book({required this.title, this.rating=0.0});  @override  List<Object> get props => [title];}

So what if later you want to change the book rating?

You would usually define a factory constructor to do so. It becomes very tedious however to write as the number of class variables grows and forces you to check the value of each optional argument and take the original one if some of them are missing. The boilerplate code can become daunting…

https://pub.dev/packages/copy_with_extension_gen comes to the rescue.

This package generates the boilerplate code handling the copy operation for you. Just annotate…

--

--

Olivier Brand
Olivier Brand

Written by Olivier Brand

I am passionate about mobile, especially designing end to end processes for delivering solid apps and supporting backend systems.