When you have a data class in Flutter, like a User
class with a name
and age
, you often need to write a lot of extra stuff. You have to create a copyWith
method, override the ==
operator, and a hashCode
getter. All this is just to make the class work correctly for state management. It's a pain.
normal class looks:
class User {
final String name;
final int age;
User({required this.name, required this.age});
User copyWith({String? name, int? age}) {
return User(
name: name ?? this.name,
age: age ?? this.age,
);
}
// .. and the == and hashCode overrides you saw before
}
ow, check out how the freezed
package does it using freezed
:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
@freezed
class User with _$User {
const factory User({required String name, required int age}) = _User;
}
Comments
Post a Comment