{"id":29227,"date":"2022-07-22T11:24:52","date_gmt":"2022-07-22T11:24:52","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=29227"},"modified":"2026-02-24T09:42:09","modified_gmt":"2026-02-24T09:42:09","slug":"flutter-freezed-example","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/flutter-freezed-example","title":{"rendered":"Flutter Freezed Example: Crash Course to Learn Freezed in Flutter App"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>Are you willing to build a demo application and learn to work with freezed in your flutter app? Then here\u2019s a flutter freezed example for you! In today\u2019s tutorial, we will learn about the freezed package and how to implement it. <\/p>\n<h2>What is Freezed?<\/h2>\n<p>The freezed package is a code generator for data classes and union classes that is robust and scalable. In addition, it allows the serialization and deserialization of JSON data.<\/p>\n<p>R\u00e9mi Rousselet created Freezed to be a code generator for immutable classes, and you might remember him for the package: provider, riverpod, and hooks.<\/p>\n<h2>Flutter Freezed Example: Project Set Up <\/h2>\n<p>We will need a few dependencies in pubspec.yaml to get things working. So the first step in our flutter freezed tutorial is to set up the project and install the dependencies.<\/p>\n<pre>dependencies:\r\n flutter:\r\n   sdk: flutter\r\n\r\n freezed_annotation: ^2.0.3\r\n json_annotation: ^4.0.6\r\n\r\n\r\ndev_dependencies:\r\n flutter_test:\r\n   sdk: flutter\r\n\r\n freezed: ^2.0.3+1\r\n build_runner: ^2.1.11\r\n json_serializable: ^6.3.1<\/pre>\n<p>The following is a rundown of what these dependencies do:<\/p>\n<ul class=\"bullets text-left\">\n<li><strong>freezed_annotation:<\/strong> Annotations for the freezed code-generator.<\/li>\n<li><strong>freezed:<\/strong> Code generator with a simple API that can handle complex use-cases.<\/li>\n<li><strong>build_runner:<\/strong> It generates model files and watches for any changes, and rebuilds the models accordingly.<\/li>\n<li><strong>json_serializable:<\/strong> Annotating Dart classes automatically generates code for converting to and from JSON. The JsonSerializable annotation will generate code for a class to\/from JSON.<\/li>\n<li><strong>json_annotation:<\/strong> Json_serializable uses annotations to define its operations.<\/li>\n<\/ul>\n<p>Run the below command to <strong>install the dependencies.<\/strong><\/p>\n<pre>flutter pub get<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1100\" height=\"563\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter.jpg\" alt=\"Flutter code\" class=\"alignnone size-medium wp-image-29243\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter.jpg 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-300x154.jpg 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1024x524.jpg 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-768x393.jpg 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<p>We compare model classes with and without freezed. A model class generation without freezed means the &#8220;boilerplate&#8221; code isn&#8217;t useful in complex applications with a lot of functionality. A model class generation without freezed has a lot of code, and this approach doesn&#8217;t scale. Using the package, we can eliminate a lot of boilerplate code.<\/p>\n<p class=\"boxed bg--secondary\" style=\"border: 1px solid #c7c7c7; box-shadow: 0 0 40px rgba(0, 0, 0, 0.2);\"><strong><i><span style=\"font-size:22px; color:#000;\">Leverage World-Class Flutter Talent!<\/span><br \/>\nWant to develop a cost-effective Flutter application? Stuck with the question: where can you find proficient developers? Contact Bacancy now and <a href=\"https:\/\/www.bacancytechnology.com\/hire-flutter-developer\" target=\"_blank\" rel=\"noopener\">hire flutter developers<\/a> from us!<\/strong><\/i><\/p>\n<h2>Creating Model Classes with freezed <\/h2>\n<p>Firstly, you need to create a class that has the @freezed() annotation.<\/p>\n<pre>import 'package:freezed_annotation\/freezed_annotation.dart';\r\n\r\n@freezed\r\nclass UserModel{}<\/pre>\n<h2>Define Class with Mixins<\/h2>\n<p>The next step is to define a class with mixins.<\/p>\n<pre>import 'package:freezed_annotation\/freezed_annotation.dart';\r\n\r\n@freezed\r\nclass UserModel with _$UserModel{}<\/pre>\n<h2>Create a Constructor <\/h2>\n<p>Now we add a factory method as a constructor with a list of all the arguments\/properties. Here we have defined @Default inside the factory method which comes from <strong>\u2018freezed_annotation\u2019<\/strong>.The @Default annotation is used to set a default value for non-required properties.<\/p>\n<pre>import 'package:freezed_annotation\/freezed_annotation.dart';\r\n\r\n@freezed\r\nclass UserModel with _$UserModel {\r\n const factory UserModel({\r\n   required String firstName,\r\n   required String lastName,\r\n   required String emailId,\r\n   @Default(false) bool isActive,\r\n }) = _UserModel;<\/pre>\n<p>We have now created our constructor. Next, we want to implement <strong>fromJson\/toJson.<\/strong> In the freezed package, fromJson and toJson are not generated, but it knows what json_serializable is.<\/p>\n<p>Consider this snippet.<\/p>\n<pre>import 'package:freezed_annotation\/freezed_annotation.dart';\r\n\r\npart 'user_model.freezed.dart';\r\npart 'user_model.g.dart';\r\n\r\n@freezed\r\nclass UserModel with _$UserModel {\r\n const factory UserModel({\r\n   required String firstName,\r\n   required String lastName,\r\n   required String emailId,\r\n   @Default(false) bool isActive,\r\n }) = _UserModel;\r\n\r\n factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);\r\n}<\/pre>\n<p>Here we are done with a <strong>UserModel<\/strong> class with freezed code generation.<\/p>\n<h2>Generate Code using freezed <\/h2>\n<p>The above code snippet shows two lines of code that use part and contain freezed, and these are the ones that let the freezed package know when to generate code for us whenever we run the build_runner.<\/p>\n<p>Now we&#8217;re really getting close to the end. Our code generator will generate some errors if we miss something or add a typo.<\/p>\n<p>The next step is to navigate within the terminal to the folder where our project is located and execute the following command.<\/p>\n<pre>flutter pub run build_runner build --delete-conflicting-outputs<\/pre>\n<p>You will now see new files in your project explorer.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1100\" height=\"394\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-2.jpg\" alt=\"Flutter Generate Code using freezed\" class=\"alignnone size-medium wp-image-29244\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-2.jpg 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-2-300x107.jpg 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-2-1024x367.jpg 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-2-768x275.jpg 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<p>You can find the code in the .freezed.dart files. The code generator has added the following to each model class:<\/p>\n<p>A list of all the store arguments\/properties inside the factory method was made final<\/p>\n<ul class=\"bullets text-left\">\n<li>the toString() method<\/li>\n<li>the == operator<\/li>\n<li>the hashCode getter variable<\/li>\n<li>the copyWith() method<\/li>\n<li>the toJson() method<\/li>\n<\/ul>\n<p>The data class you have successfully created!<\/p>\n<h2>Using the &#8220;copyWith&#8221; method<\/h2>\n<p>The method returns an updated instance with the new properties.<\/p>\n<p>The state is updated when its value changes in state management solutions. State management solutions update the state when its value is changed. Here&#8217;s when copyWith comes in handy.<\/p>\n<p>To demonstrate, Assume the UserModel object we created in our state.<br \/>\nThe original UserModel object&#8217;s values would have been used to create a new UserModel object if we wanted to update our state.<\/p>\n<p>You&#8217;ll notice that we get immutability by default. We are also unable to directly assign the properties as expected despite getting the copyWith generated for us.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1100\" height=\"377\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1.jpg\" alt=\"Using the &quot;copyWith&quot; method - Flutter\" class=\"alignnone size-medium wp-image-29245\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1.jpg 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1-300x103.jpg 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1-1024x351.jpg 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-1-768x263.jpg 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<p>The error message indicates that there is a getter for the isActive, but no setter has been created, so value assignment is not possible. <\/p>\n<p>The correct way to assign new values is as follows.<\/p>\n<pre>void _updateActiveUser(int index) {\r\n userModel[index] = userModel[index].copyWith(\r\n     isActive: !userModel[index].isActive);\r\n setState(() {});\r\n}\r\n\r\n\/\/ \u2026\r\n\r\nchild: Column(\r\n children: [\r\n   ListView.builder(\r\n       shrinkWrap: true,\r\n       itemCount: userModel.length,\r\n       itemBuilder: (BuildContext context, int index) {\r\n         return Container(\r\n           margin: EdgeInsets.only(top: 20, left: 20, right: 20),\r\n           decoration: BoxDecoration(\r\n             color: Colors.grey.shade200,\r\n             borderRadius: BorderRadius.all(Radius.circular(10)),\r\n           ),\r\n           padding: EdgeInsets.all(10),\r\n           child: ListTile(\r\n             title: Text(userModel[index].firstName + \" \" + userModel[index].lastName),\r\n             subtitle: Text(userModel[index].emailId),\r\n             trailing: Transform.scale(\r\n                 scale: 1,\r\n                 child: Switch(\r\n                   onChanged: (val) {\r\n                     _updateActiveUser(index);\r\n                   },\r\n                   value: userModel[index].isActive,\r\n                   activeColor: Colors.blue,\r\n                   activeTrackColor: Colors.grey.shade700,\r\n                   inactiveThumbColor: Colors.white12,\r\n                   inactiveTrackColor: Colors.grey.shade700,\r\n                 )),\r\n           ),\r\n         );\r\n       }),\r\n ],\r\n)<\/pre>\n<p>We have implemented the following for the user who clicks on the switch under the list view. We will update the value of the isActive user to true or false. Let\u2019s create a function that attaches it to the switch onChange property and just passes in the current index of that item.<\/p>\n<p>On clicking any of the ListTile we will see the below output. <\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1100\" height=\"1831\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3.jpg\" alt=\"Flutter Freezed Example\" class=\"alignnone size-medium wp-image-29246\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3.jpg 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3-180x300.jpg 180w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3-615x1024.jpg 615w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3-768x1278.jpg 768w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/07\/Flutter-3-923x1536.jpg 923w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<p>In our latest blog we try to cover the <a href=\"https:\/\/www.bacancytechnology.com\/blog\/flutter-bloc-tutorial\" target=\"_blank\" rel=\"noopener\">Flutter BLoC tutorial<\/a> with state management using the BLoC pattern.<\/p>\n<h2>Github Repository: Flutter Freezed Example<\/h2>\n<p>Here&#8217;s the source code of code generation with the freezed package: <a href=\"https:\/\/github.com\/mohitsolankee22\/flutter_explore_freezed\" target=\"_blank\" rel=\"noopener\">flutter-freezed-example.<\/a> Take a look at the code, clone the repository and play around with the code.<\/p>\n<h2>Conclusion<\/h2>\n<p>That&#8217;s all for now. I hope the flutter freezed example has helped to get started with the freezed package. We learned how to create a data model with the help of the freezed package. Feel free to write us back and share your feedback. For flutter enthusiasts like you, we have a <a href=\"https:\/\/www.bacancytechnology.com\/tutorials\/flutter\" target=\"_blank\" rel=\"noopener\">Flutter tutorials<\/a> page where you can learn more about basic and advanced concepts of Flutter.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Are you willing to build a demo application and learn to work with freezed in your flutter app? Then here\u2019s a flutter freezed example for you! In today\u2019s tutorial, we will learn about the freezed package and how to implement it. What is Freezed? The freezed package is a code generator for data classes [&hellip;]<\/p>\n","protected":false},"author":171,"featured_media":29241,"comment_status":"open","ping_status":"open","sticky":false,"template":"blog-new-template.php","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[1200],"tags":[],"coauthors":[2425],"class_list":["post-29227","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-flutter"],"acf":[],"modified_by":"Nisarg Bhavsar","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/29227","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/171"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=29227"}],"version-history":[{"count":2,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/29227\/revisions"}],"predecessor-version":[{"id":57887,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/29227\/revisions\/57887"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/29241"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=29227"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=29227"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=29227"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=29227"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}