<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mostafahassan on Medium]]></title>
        <description><![CDATA[Stories by Mostafahassan on Medium]]></description>
        <link>https://medium.com/@mostafahassan8799?source=rss-b55906f0a6ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-071q5hDqgtToztB2jTgeg.png</url>
            <title>Stories by Mostafahassan on Medium</title>
            <link>https://medium.com/@mostafahassan8799?source=rss-b55906f0a6ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:36:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mostafahassan8799/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dart Primary Constructors: Syntax, Benefits, and Migration]]></title>
            <link>https://medium.com/@mostafahassan8799/dart-primary-constructors-writing-cleaner-flutter-code-with-less-boilerplate-cc221d739e60?source=rss-b55906f0a6ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc221d739e60</guid>
            <dc:creator><![CDATA[Mostafahassan]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 19:06:51 GMT</pubDate>
            <atom:updated>2026-11-22T19:24:01.911Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Exploring Dart’s Primary Constructors, their benefits, and how to safely migrate an existing Flutter codebase.</em></p><h3>Introduction</h3><p>As Flutter developers, we write classes every day. Whether we’re working with Entities, DTOs, Models, Bloc Events, or Widgets, constructors are a regular part of our code.</p><p>Over time, we get used to writing the same boilerplate:</p><ul><li>Declaring fields.</li><li>Defining constructor parameters.</li><li>Assigning parameters to fields using this.</li></ul><p>It works perfectly, but sometimes it feels like we’re writing the same information more than once.</p><p>With Dart 3.13, Primary Constructors introduce a more concise way to define constructors and fields directly in the class declaration.</p><p>Let’s explore what they are, why they matter, and how we can migrate an existing codebase safely.</p><h3>1. What Are Primary Constructors?</h3><p>Primary Constructors allow you to declare constructor parameters directly in the class header instead of defining a separate constructor inside the class body.</p><p>Consider this example:</p><h3>Before: Traditional Constructors</h3><pre>class BookingEntity {<br>  const BookingEntity({<br>    required this.id,<br>    required this.date,<br>    required this.status,<br>  });<br>  final String id;<br>  final DateTime date;<br>  final BookingStatus status;<br>}</pre><p>Notice how we declare the same properties in multiple places:</p><ol><li>Constructor parameters.</li><li>Field declarations.</li><li>Parameter-to-field assignments using this.</li></ol><p>Now, let’s see how Primary Constructors simplify this.</p><h3>After: Primary Constructors</h3><pre>class const BookingEntity({<br>  required final String id,<br>  required final DateTime date,<br>  required final BookingStatus status,<br>});</pre><p>That’s it!</p><p>We can declare the constructor parameters and their corresponding fields in one place.</p><p>A few things worth understanding:</p><ul><li>class const declares a constant primary constructor.</li><li>final declares a field rather than a regular constructor parameter.</li><li>required keeps the same required-parameter behavior.</li><li>The class can omit its body entirely when there is nothing else to define.</li></ul><p>The way we create instances doesn’t change:</p><pre>const booking = BookingEntity(<br>  id: &#39;123&#39;,<br>  date: DateTime(2026, 11, 22),<br>  status: BookingStatus.pending,<br>);</pre><p>The main idea is simple: <strong>less repetition without changing the behavior of the class.</strong></p><h3>2. Why Should Flutter Developers Care?</h3><p>Primary Constructors don’t introduce new runtime capabilities. Their main purpose is to make class declarations more concise.</p><p>However, this small improvement can make a noticeable difference in everyday Flutter development.</p><h3>Less Boilerplate</h3><p>We no longer need separate field declarations and constructor assignments for every property.</p><p>This becomes particularly useful when working with classes that contain several properties.</p><h3>Cleaner Entities and DTOs</h3><p>Flutter applications often contain many data classes.</p><p>For example:</p><ul><li>BookingEntity</li><li>UserEntity</li><li>ProductModel</li><li>PaymentRequest</li><li>API Response DTOs</li></ul><p>Primary Constructors can make these classes significantly shorter and easier to scan.</p><h3>Simpler Bloc Events and States</h3><p>If you’re using Bloc, you probably have several small classes representing events and states.</p><p>For example:</p><pre>sealed class BookingEvent {}</pre><pre>class const BookingRequested(final String id)<br>    extends BookingEvent;</pre><pre>class const BookingCancelled(<br>  final String id,<br>  final String reason,<br>) extends BookingEvent;</pre><p>This is another area where reducing boilerplate can make the codebase easier to maintain.</p><h3>3. How Can We Migrate an Existing Codebase?</h3><p>This is where things become more interesting.</p><p>When I explored this feature, I came across an article by Andrea Bizzotto titled:</p><p><strong>Safely Migrate to Primary Constructors</strong></p><p>The article focuses on a question that becomes important when adopting new language features:</p><p>How can we migrate an existing codebase without introducing unexpected problems?</p><p>There are generally three approaches:</p><h3>Approach 1: Manual Migration</h3><p>We can manually update each class.</p><p>This works for small projects, but it becomes tedious and error-prone when dealing with hundreds or thousands of declarations.</p><h3>Approach 2: Using AI Agents</h3><p>Another option is asking an AI agent to migrate the codebase.</p><p>AI agents are useful because they can understand context and reason about code.</p><p>However, the article highlights some limitations encountered during migration:</p><ul><li>Results weren’t always consistent.</li><li>Different agents and runs produced different results.</li><li>The process could consume significant time and tokens.</li><li>Maintaining a large set of migration instructions became difficult.</li></ul><h3>Approach 3: Deterministic CLI Tool</h3><p>The approach chosen in the article was building a CLI tool that uses AST (Abstract Syntax Tree) parsing.</p><p>Instead of asking an AI model to decide how every class should be transformed, the tool analyzes the code structure and applies predefined transformation rules.</p><p>The important part is that the tool is conservative.</p><p>It identifies situations where migration might not be safe and skips those declarations rather than risking incorrect transformations.</p><p>This is particularly important when dealing with:</p><ul><li>Custom constructor bodies.</li><li>late fields.</li><li>Fields without explicit types.</li><li>Complex super-constructor calls.</li><li>Other declarations that cannot be safely represented by the new syntax.</li></ul><p>The goal isn’t to migrate everything. The goal is to migrate everything that can be migrated safely.</p><h3>4. The Migration Workflow</h3><p>According to the article, the recommended workflow is straightforward.</p><p>Before doing anything, make sure your project is healthy.</p><h3>Step 1: Analyze the Existing Code</h3><pre>flutter analyze</pre><p>Establish a baseline before introducing changes.</p><h3>Step 2: Run the Migration Tool</h3><pre>act_dart_migrate</pre><p>The tool analyzes the codebase and migrates eligible declarations.</p><p>Note: act_dart_migrate is an external migration tool discussed in Andrea&#39;s article, not a built-in Dart SDK command. Follow the article&#39;s setup instructions before running it.</p><h3>Step 3: Format the Code</h3><pre>dart format .</pre><p>Make sure the migrated code follows Dart formatting conventions.</p><h3>Step 4: Analyze Again</h3><pre>flutter analyze</pre><p>Check for compilation and static analysis issues introduced by the migration.</p><h3>Step 5: Run Tests</h3><pre>flutter test</pre><p>Make sure existing application behavior remains correct.</p><p>One important point: successful compilation doesn’t necessarily mean a migration is correct. Tests are essential for catching behavioral problems that static analysis cannot detect.</p><h3>5. AI Agents vs. Deterministic Tools</h3><p>This was probably the most interesting takeaway for me.</p><p>AI agents are powerful, especially when dealing with tasks that require understanding context, making decisions, or handling complex refactoring.</p><p>But not every programming task requires that level of reasoning.</p><p>Consider these examples:</p><p>TaskBetter approachRenaming a package across a projectDeterministic toolApplying a syntax transformationAST-based codemodUnderstanding a complex architectureAI agent + developerRefactoring business logicDeveloper + AI assistanceMigrating code with predefined rulesDeterministic tool + tests</p><p>The distinction is important:</p><p><strong>AI is great at reasoning, but deterministic tools are often better at predictable transformations.</strong></p><p>Instead of choosing tools based on how powerful they seem, we should choose them based on the nature of the problem.</p><h3>7. Should You Start Using Primary Constructors?</h3><p>My recommendation would be to consider them for new code, especially when working with simple data classes.</p><p>Good candidates include:</p><ul><li>Entities.</li><li>DTOs.</li><li>Simple Models.</li><li>Bloc Events.</li><li>Simple immutable classes.</li><li>Widgets with straightforward constructors.</li></ul><p>However, traditional constructors are still useful.</p><p>If a class requires complex initialization logic, custom constructor bodies, or more complicated initialization patterns, forcing everything into a primary constructor might make the code harder to understand.</p><p>Also, consistency matters.</p><p>Using both styles randomly throughout the same codebase can make the project less predictable. It’s better to agree on a convention with your team.</p><p>For existing projects, I’d recommend migrating gradually, one feature or folder at a time, with code review and automated tests.</p><h3>Final Thoughts</h3><p>Primary Constructors are a relatively small language improvement, but they address something we deal with every day as Flutter developers: unnecessary repetition.</p><p>However, the bigger lesson from exploring this topic isn’t just about writing shorter classes.</p><p>It’s about how we approach changes in production codebases.</p><p>Automated migrations should be predictable, conservative, and properly tested. We shouldn’t consider a migration successful just because the generated code compiles.</p><p>And perhaps most importantly, choosing the right tool for the job matters more than choosing the most powerful tool available.</p><p><strong>Cleaner code is good, but maintaining correctness while improving it is even better.</strong></p><h3>Resources</h3><p>If you want to explore the feature and migration process in more detail, here are the resources I recommend:</p><ol><li><strong>Official Dart Documentation — Primary Constructors </strong><a href="https://dart.dev/language/primary-constructors">https://dart.dev/language/primary-constructors</a></li><li><strong>Andrea Bizzotto — Safely Migrate to Primary Constructors </strong><a href="https://codewithandrea.com/articles/safely-migrate-primary-constructors/">https://codewithandrea.com/articles/safely-migrate-primary-constructors/</a></li><li><strong>Dart Language Specification </strong><a href="https://github.com/dart-lang/language">https://github.com/dart-lang/language</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc221d739e60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>