Flutter: Optimized modeling
Optimize and increase your productivity, and consume lesser time in creating your script manually when you are building a model
Hello flutter devs! Are you having a hard time or consuming more time designing and creating a model class? well if you do this is the right article for you!
We are going to talk about creating model class without really creating it!
Yes! it doesnt make sense for some, but you will understand if you read this article more.
How can we create a model without really creating it? answer is `auto generated` files, you can have a plugin generated file in flutter and a watcher that runs the script each time you save a file in your flutter directory, sounds cool right?
Lets Get Started!
First, we will be tinkering our pubspec.yaml file then add some dependencies on it.
Our first dependency is called freezed, freezed is a native dart package so there will be no worries about any third party app or languages, to learn more what is freezed you check it by clicking the highlighted text.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
freezed_annotation:
we will be needing freezed annotation for our dependency then freezed on our dev_dependencies
dev_dependencies:
flutter_test:
sdk: flutter
freezed:
Now we have added what we need in freezed, next will be our watcher, called build_runner.
dev_dependencies:
flutter_test:
sdk: flutter
freezed:
build_runner:
Then our generator:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
freezed_annotation:
injectable:
dev_dependencies:
flutter_test:
sdk: flutter
build_runner:
injectable_generator:
freezed:
Note: always check the difference
And after this we are all set!
How to use
Create a dart file, example, user_model.dart, once created import freezed_annotation
import 'package:freezed_annotation/freezed_annotation.dart';
then add a `part`.
NOTE: Make sure your part folder has the same name as your current folder. then add `.freezed`
part 'user_model.freezed.dart';
finally do your thing!
@freezed
abstract class User with _$User {
factory User({required String name, int? age,}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
Save the file and then on your terminal run the following:
flutter packages pub run build_runner watch --delete-conflicting-outputs
this command will become our listener, but if you want a one time run, then do a
flutter packages pub run build_runner build --delete-conflicting-outputs
and this will auto generate a file in the same folder you created your dart file.
Congrats! You have made your computer work for you again!