<?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 Veli Bacık on Medium]]></title>
        <description><![CDATA[Stories by Veli Bacık on Medium]]></description>
        <link>https://medium.com/@vbacik-10?source=rss-c21b865a34b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a1lEHU5h9n2S4OziXk1exA.jpeg</url>
            <title>Stories by Veli Bacık on Medium</title>
            <link>https://medium.com/@vbacik-10?source=rss-c21b865a34b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:53:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vbacik-10/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[Flutter Web or Jaspr? I Built the Same App Twice to Decide]]></title>
            <link>https://medium.com/flutter-community/flutter-web-or-jaspr-i-built-the-same-app-twice-to-decide-a803ad6442c7?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a803ad6442c7</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[jaspr]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 10:22:33 GMT</pubDate>
            <atom:updated>2026-11-07T10:22:33.028Z</atom:updated>
            <content:encoded><![CDATA[<h4>Same Dart, same Cubits, same API. One ships a canvas, the other ships real HTML. Here is what that means for your next web project.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5tz8c7EUlGgzkMSKH_JqA.png" /></figure><h3>The question</h3><p>You know Flutter. Someone now wants a website. Which road do you take to the web?</p><p>The default answer is “Flutter Web, it is the same code.” It is a fair answer, and for some products it is the right one. But it hides a detail that matters the moment someone asks about SEO, link previews or first load: <strong>Flutter Web does not send the browser a web page. It sends an app.</strong></p><p>I mostly work on mobile, and I have not been a web person. But Flutter Web has become stable, and clients keep asking what it can and cannot do. I did not want to answer from opinion, so I tried it.</p><h3>What we built, and why twice</h3><p>I wrote the same small app two times: a made-up fashion store called ModaPazar, with a Login screen and a Home screen, both talking to the same API.</p><ul><li>One version uses <strong>Flutter Web</strong>.</li><li>The other uses <a href="https://pub.dev/packages/jaspr">Jaspr</a>, a Dart framework that renders real HTML and CSS.</li></ul><p>Both are Dart. Both use the same Cubits. That was on purpose: if the logic is identical, the only thing left to compare is <em>what the browser receives</em>. The code and a wiki with the concept diagrams are open source:</p><p><a href="https://github.com/VB10/flutterwebjaspr-basic">GitHub - VB10/flutterwebjaspr-basic: The same Dart shop app built twice: Flutter Web (canvas) vs Jaspr (real HTML). Same Cubits, same API, responsive login and home.</a></p><h3>The difference in one sentence</h3><p>Flutter paints its own pixels. On the web, your compiled Dart code boots an engine (CanvasKit) and your widgets are drawn onto a single canvas. Open DevTools on a Flutter Web app and look for your buttons and headings: they are not there. You find one canvas.</p><p>Jaspr keeps the Flutter-like way of writing UI (components, a build method, setState), but its output is real HTML and CSS. Every route is its own HTML file with the styles attached. Open DevTools and you see ordinary div and h1 elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzpAz_OJGYqsJN5ALo2X0w.png" /></figure><p>Flutter WebJasprWhat the browser getsAn app: the engine plus a canvasA page: HTML and CSSFirst openDownloads the engine before drawingOpens without waiting for JavaScriptSEO and meta tagsNeeds extra workOrdinary page content crawlers can readBest fitA web <em>application</em>A web <em>page</em></p><h3>Seeing it live</h3><p>I did not want to rely on a table, so the video includes a live test: open the same login page in both versions, then inspect the DOM. Here is the page open:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*tvYOaWUA6u1JrB-4ITcRMg.gif" /></figure><p><em>Left: reloading the Flutter Web login page. Right: opening the Jaspr login page. Recorded separately on the same machine and lined up at the moment of the page open.</em></p><p>A fair warning about this clip: both were local development runs (the Flutter app in debug mode, the Jaspr app on its dev server), so the exact times will differ on a release build and a real network. I am not using it as a benchmark. What it shows reliably is <em>what</em> each page waits for: Flutter Web draws nothing until its engine and app are up, while the Jaspr page arrives as finished HTML.</p><p>Then DevTools shows the other half of the story. One page is a single canvas element, the other is real elements you can select, copy and style:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtkWFh9gJmdCrx8z5MLeqg.png" /></figure><h3>Web application vs web page</h3><p>This is the frame that settled it for me. Flutter Web gives you a web <em>application</em>: dashboards, internal tools, anything where the experience is the point and nobody needs to find a deep link on Google. Jaspr gives you a web <em>page</em>, which is what most public websites are.</p><p>Neither is better in the abstract. They answer different requests, and the request usually tells you which one you need.</p><h3>Why we chose to look at Jaspr</h3><p>If you only build websites, you should simply pick an established web framework. I say that plainly, because it is true. Jaspr is not a reason to leave your web stack.</p><p>The case for Jaspr is narrower: <strong>you already have Flutter code and Flutter knowledge.</strong> Your models, services and state management already exist and work. A client asks for something Flutter Web does not hand over, such as pages a crawler can read. Instead of saying “Flutter can’t do that,” you deliver real HTML and reuse what you already know.</p><p>That is also why I published <a href="https://pub.dev/packages/vexana_jaspr">vexana_jaspr</a>, a Jaspr version of my networking package. If your Flutter work depends on a package, its equivalent has to exist on the other side too.</p><h3>This is not a landing page demo</h3><p>A hello-world comparison proves nothing, so the two apps are small but real, at 101 level:</p><ul><li><strong>Login:</strong> email or phone validation, field errors, a loading state, a failure state, “remember me”, a guest path and a saved session.</li><li><strong>Home:</strong> a feed from the API, banners, categories, a flash sale, product cards, and a bottom bar that becomes a top nav on desktop.</li><li><strong>A fake backend</strong> (shelf) with three endpoints: POST /auth/login, GET /home, GET /me.</li><li><strong>Responsive</strong> in both, mobile first, with breakpoints at 600 and 1024.</li><li><strong>Tests:</strong> 28 in the Flutter app, 9 in the Jaspr app, 7 for the API. Both apps read the same JSON fixture, written from the API itself, so they test against what the server really sends.</li></ul><h3>One architecture, two front ends</h3><p>Both apps use the same folder shape. Only the view layer differs.</p><pre>features/&lt;feature&gt;/cubit/   Cubit + state (a status enum)<br>features/&lt;feature&gt;/view/    page, mixin (builds the cubit, handlers), parts<br>product/service/&lt;x&gt;/        i_&lt;x&gt;_service.dart seam + impl, never throws<br>product/container/          AppContainer: the only place services are built<br>product/design/             colors, spacing, sizes: the only place for raw values</pre><h3>The Cubit does not know which UI it has</h3><p>package:bloc is plain Dart. The Jaspr LoginCubit is the Flutter one, line for line. It validates the input, calls a service through an interface and emits a new state:</p><pre>final class LoginCubit extends Cubit&lt;LoginState&gt; with SafeEmit&lt;LoginState&gt; {<br>  LoginCubit({<br>    required IAuthService authService,<br>    required ISessionStore sessionStore,<br>  }) : _authService = authService,<br>       _sessionStore = sessionStore,<br>       super(const LoginState());<br><br>Future&lt;void&gt; submit({<br>    required String identifier,<br>    required String password,<br>    required bool remember,<br>  }) async {<br>    if (state.isSubmitting) return;<br>    // ...validate, then:<br>    safeEmit(const LoginState(status: LoginStatus.submitting));<br>    final result = await _authService.login(<br>      identifier: cleanIdentifier,<br>      password: password,<br>    );<br>    // ...save the session, emit success or failure<br>  }<br>}</pre><p>That is why the comparison is fair: the business rules cannot drift between the two apps, because there is only one version of them.</p><h3>Wiring the Cubit to the view</h3><p>In Flutter you reach for flutter_bloc: a BlocProvider.value and a BlocListener. Jaspr has no equivalent that we could use. jaspr_bloc targets an older Jaspr release, and flutter_bloc depends on Flutter. So we wrote the small piece we actually need, about 50 lines: rebuild on every new state, and run an optional listener first, like BlocConsumer.</p><pre>class CubitBuilder&lt;C extends BlocBase&lt;S&gt;, S&gt; extends StatefulComponent {<br>  const CubitBuilder({<br>    required this.cubit,<br>    required this.builder,<br>    this.listener,<br>    super.key,<br>  });<br><br>  final C cubit;<br>  final Component Function(BuildContext context, S state) builder;<br>  final void Function(S state)? listener;<br>  // ...<br>}<br>// in State:<br>@override<br>void initState() {<br>  super.initState();<br>  _subscription = component.cubit.stream.listen((state) {<br>    component.listener?.call(state);<br>    setState(() =&gt; _state = state);<br>  });<br>}</pre><p>Using it looks like the Flutter version: the Cubit goes in, a builder comes out, and a listener reacts to state changes such as navigating after a successful login.</p><pre>CubitBuilder&lt;LoginCubit, LoginState&gt;(<br>  cubit: loginCubit,<br>  listener: onStateChanged,<br>  builder: (context, state) =&gt; div(classes: _LoginClass.pane, [<br>    // form card, social section, guest button ...<br>  ]),<br>)</pre><h3>The view mixin</h3><p>In both apps the view is split into a thin build method and a mixin that owns the logic: it builds the Cubit from AppContainer, holds the handlers and disposes everything. The two mixins have the same shape:</p><pre>// Flutter<br>mixin _LoginViewMixin on State&lt;LoginView&gt; {<br>  late final LoginCubit loginCubit = LoginCubit(<br>    authService: AppContainer.authService,<br>    sessionStore: AppContainer.sessionStore,<br>  );<br>  final identifierController = TextEditingController();<br>  // ...<br>}<br>// Jaspr<br>mixin _LoginViewMixin on State&lt;LoginView&gt; {<br>  late final LoginCubit loginCubit = LoginCubit(<br>    authService: AppContainer.authService,<br>    sessionStore: AppContainer.sessionStore,<br>  );<br>  String identifier = &#39;&#39;;   // plain fields instead of controllers<br>  // ...<br>}</pre><p>What changes is small and honest: Flutter uses TextEditingController and ValueNotifier, Jaspr uses plain fields and setState. A snack bar becomes a notice element. Navigation goes through AppContainer.navigator instead of go_router. The services are interfaces, so the container decides which implementation runs where.</p><h3>Server components and client components</h3><p>This is the part that has no Flutter equivalent, and it is where Jaspr earns its HTML. Each route is rendered to an HTML file at build time. The page itself is a plain server component that owns the &lt;head&gt;: the title and the meta description are in the HTML before any JavaScript runs.</p><pre>class LoginPage extends StatelessComponent {<br>  const LoginPage({super.key});<br>@override<br>  Component build(BuildContext context) =&gt; const Component.fragment([<br>    Document.head(<br>      title: Strings.loginPageTitle,<br>      meta: {&#39;description&#39;: Strings.metaDescription},<br>    ),<br>    LoginView(),<br>  ]);<br>}</pre><p>Only the interactive part, LoginView, is marked @client and comes alive in the browser. A @client component takes no constructor arguments, because only serializable values may cross from the server to the browser. That is exactly why the mixin builds its own Cubit from the container: the same pattern we already use in the Flutter app turned out to be what Jaspr requires.</p><h3>What we ran into</h3><ul><li><strong>A phone number rejected by the browser.</strong> type=&quot;email&quot; on the input made the browser refuse a phone number before our Cubit ever ran. The fix: type=&quot;text&quot; plus novalidate on the form, and let the Cubit validate.</li><li>dart:io<strong> on the web.</strong> It compiles and throws at runtime. Both apps need a conditional import and package:web. In Jaspr, browser APIs live only in lib/client/, and the build entry gets no-op stand-ins.</li><li><strong>Models.</strong> The Flutter app uses freezed. In Jaspr we wrote them by hand, because the generators needed an analyzer version that the Jaspr builder at the time did not allow.</li><li><strong>Hot reload.</strong> jaspr serve does not re-run top-level final style lists, so after editing a styles file you restart it.</li><li><strong>Browser tests.</strong> On a canvas you click by coordinates. On the Jaspr page you select by id, like #login-submit.</li></ul><h3>My honest answer</h3><ul><li><strong>Only building for the web, no Flutter history:</strong> use an established web framework.</li><li><strong>A real app that happens to run in a browser:</strong> Flutter Web.</li><li><strong>Public pages, SEO, link previews, and a team that already knows Flutter:</strong> Jaspr.</li></ul><p>The Dart brain is the same either way. What you choose is what the browser sees.</p><h3>What’s next</h3><p>In this repo each app keeps its own copy of the Cubits and services, which keeps the comparison simple. In the next post I will take it one step further: a single shared package for models, services and Cubits, consumed by both a Flutter app and a Jaspr site, plus how the add-screen-both Claude skill in the repo adds a new screen to both apps with the same Cubit.</p><p>Until then, which would you pick for your next web project, Flutter Web or Jaspr? I would like to hear why.</p><p>Code and wiki: <a href="https://github.com/VB10/flutterwebjaspr-basic">github.com/VB10/flutterwebjaspr-basic</a><br>Package: <a href="https://pub.dev/packages/vexana_jaspr">pub.dev/packages/vexana_jaspr</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGWKmcjASg3k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGWKmcjASg3k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGWKmcjASg3k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be93798f2c82a48dffaa378a9daab6a2/href">https://medium.com/media/be93798f2c82a48dffaa378a9daab6a2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a803ad6442c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-web-or-jaspr-i-built-the-same-app-twice-to-decide-a803ad6442c7">Flutter Web or Jaspr? I Built the Same App Twice to Decide</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flame Gallery: Drop-in Mini Games for Flutter Apps]]></title>
            <link>https://medium.com/flutter-community/flame-gallery-drop-in-mini-games-for-flutter-apps-6df3476482fb?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df3476482fb</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flame-engine]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 09:30:44 GMT</pubDate>
            <atom:updated>2026-10-28T17:02:26.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxZ5WTGjfHt2dmLt3oRxvg.png" /></figure><h3>One line, one game</h3><p>Marketing asks for “a little game in the app” every few months: a summer campaign, a loyalty reward, a daily challenge. Each time, a team builds a one-off screen that nobody wants to maintain afterwards.</p><p>Flame Gallery turns that into one dependency and one call:</p><pre>final result = await FlameGallery.show(context, game: const FruitSlice());</pre><p>The call pushes a full screen game with start, pause and game over menus, and completes with a GameResult you can turn into points, coupons or analytics. It is open source (MIT), built on <a href="https://flame-engine.org/">Flame</a>, and you can <a href="https://vb10.github.io/flutter_flame_gallery/play/">play it in your browser</a> right now.</p><p><strong>In numbers:</strong> 6 packages on pub.dev · 4 games · about 6,000 lines of library code · unit and game tests in every package · 6 Maestro end-to-end flows on iOS and Android.</p><h3>From WebView games to native power</h3><p>For years, the mini game inside a mobile app was usually an HTML5 game: JavaScript running in a WebView. It works, but you can feel it. Here is what changes when the game is drawn by Flutter itself:</p><ul><li><strong>Rendering.</strong> A WebView game runs a browser engine inside your app. Flame Gallery draws with Flutter’s own engine, the same one drawing the rest of your UI.</li><li><strong>First load.</strong> No pages, scripts or assets to download. Everything ships in the app bundle and works offline.</li><li><strong>Touch and frame rate.</strong> No extra layers between the finger and the frame. Gestures and frames are handled natively by Flutter.</li><li><strong>Score back to the app.</strong> No JavaScript bridge and string messages. You get a typed Dart GameResult from an await.</li><li><strong>Look and feel.</strong> No separate web styling to keep in sync. The game uses your app’s Theme, font and colors.</li><li><strong>Who maintains it.</strong> Not a separate web team: the same Flutter team, the same CI.</li></ul><p>That is the core idea: campaign games get the same native performance as the rest of your app, and the integration is one awaited function call instead of a bridge.</p><h3>Four games, four Flame techniques</h3><p>Every game package has the same inside: src/logic/ is pure Dart with unit tests, src/component/ holds one Flame component per file, and src/game/ only orchestrates.</p><h3>Fruit Slice · flame_gallery_slice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*kC9dzCkwwDQaW9qK.gif" /></figure><p>Swipe to slice fruit, slice three or more in one stroke for a combo, avoid the bomb.</p><ul><li><strong>Launch physics.</strong> LaunchPlanner picks an apex between 15% and 45% of the screen height, sets gravity to g = 1.2 · h · speed² and the launch speed to v = √(2gh). Harder levels make fruit faster, but it always reaches the same height.</li><li><strong>Cutting.</strong> Every segment of the swipe is tested against each fruit as a segment–circle intersection, so a fast swipe never skips a fruit between two frames.</li><li><strong>Halves.</strong> A sliced fruit is the same sprite cut in two with srcPosition; each half keeps the fruit’s motion and drifts away from the cut line.</li><li><strong>Look.</strong> A blade trail that thins and blurs as it ages, juice bursts from the shared GalleryBurst effect.</li></ul><h3>Ruins Runner · flame_gallery_runner</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*b6ylS9NYJ3NoMTm0.gif" /></figure><p>Top-down, three lanes. Swipe left or right to change lane, up to jump, down to slide, collect coins while the world speeds up.</p><ul><li><strong>Fixed time step.</strong> The simulated step is capped at 1/30 s. Flame does not cap dt, so one janky frame could otherwise move an obstacle straight through the player.</li><li><strong>Fair rows.</strong> ObstacleRowPlanner always leaves at least one passable lane, verified with 50 seeds × 200 rows in tests. Collision is a table of obstacle type against player pose.</li><li><strong>Feel.</strong> A jump and a slide can cancel each other, so back-to-back rows stay passable even at top speed. A short invulnerability window follows every hit.</li></ul><h3>Sweet Swap · flame_gallery_match</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*ExjYU7Orj80D4qSK.gif" /></figure><p>Swap neighbouring candies; three or more in a row clear, and chain reactions score ×2, ×3. Move limit, timer and target score are all optional.</p><ul><li><strong>Pure board.</strong> MatchBoard is plain Dart: matches, gravity, refill and chains come out as a list of CascadeStep records, fully deterministic for a given Random.</li><li><strong>Stage queue.</strong> Flame plays those steps through a queue where every stage returns its own duration. Input is locked while the queue is busy.</li><li><strong>No lost points.</strong> End conditions are checked only after the chain settles, so a timer that runs out mid-cascade never eats points already earned.</li><li><strong>Daily challenge.</strong> A seed gives every player the same board.</li></ul><h3>Note Rush · flame_gallery_rhythm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*Bv1qbBssAh6hv2nc.gif" /></figure><p>Notes fall down four lanes; tap when they reach the line. Perfect ≤ 60 ms, Great ≤ 120 ms, Good ≤ 180 ms, combos up to ×4.</p><ul><li><strong>Song clock.</strong> Note positions are computed every frame from the song clock instead of summing dt, so they never drift. The clock syncs to the audio player’s position each frame.</li><li><strong>Bring your own audio.</strong> The library only defines a RhythmAudio interface. audioLatency compensates for headphone delay; the example app plugs in flame_audio.</li><li><strong>Input.</strong> Lanes take taps independently, so multi-touch works.</li></ul><h3>Quick start</h3><pre>flutter pub add flame_gallery</pre><p>Only need one game? Each one is its own package, for example flame_gallery_slice.</p><pre>import &#39;package:flame_gallery/flame_gallery.dart&#39;;<br><br>final result = await FlameGallery.show(<br>  context,<br>  game: FruitSlice(<br>    config: const SliceConfig(timeLimit: Duration(seconds: 30), bomb: null),<br>  ),<br>  onEvent: (event) =&gt; analytics.log(&#39;$event&#39;),<br>);<br>if (result case GameResult(isCompleted: true, :final score) when score &gt;= 50) {<br>  grantCoupon();<br>}</pre><p>The result carries the score, play time, how the game ended and per-game stats. Stats are read through const keys, never string literals:</p><pre>final sliced = result.stats[SliceStatKeys.sliced];<br>final endedBy = result.stats[GameStatKeys.endedBy]; // &#39;timeUp&#39;, &#39;bomb&#39;, &#39;quit&#39;...</pre><p>onEvent streams GameStarted, GameScoreChanged, GamePaused, GameResumed and GameFinished. GameResult.toJson() gives a flat map for analytics or a platform channel.</p><h3>Make it your brand, without forking</h3><p>Everything a company wants to change is config: colors, font, logo, background, texts, sprites and rules. Pass no colors and the game simply follows your app’s theme.</p><pre>FlameGallery.show(<br>  context,<br>  game: FruitSlice(<br>    theme: GameTheme(<br>      colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF00897B)),<br>      logo: const AssetImage(&#39;assets/brand_logo.png&#39;),<br>      background: const GameBackground.gradient(<br>        LinearGradient(colors: [Color(0xFF004D40), Color(0xFF00897B)]),<br>      ),<br>    ),<br>    strings: FruitSlice.stringsTr.copyWith(title: &#39;Summer Campaign&#39;),<br>  ),<br>  overlays: GameOverlayBuilders(<br>    gameOver: (context, ui) =&gt; MyResultSheet(<br>      score: ui.result()?.score ?? 0,<br>      onAgain: ui.start,<br>      onClose: ui.close,<br>    ),<br>  ),<br>);</pre><ul><li><strong>Your own sprites.</strong> GameAsset(&#39;assets/products/can.png&#39;) swaps any image; GameAnimation turns a horizontal sprite strip into an animation.</li><li><strong>Your own menus.</strong> Replace the start, HUD, pause or game over overlay; ui hands you the strings, the score and the actions.</li><li><strong>Your own sounds.</strong> The library plays nothing itself. It emits cues (coin, hit, slice, noteHit…) and you map them to whatever audio package your app already uses.</li><li><strong>Your own difficulty.</strong> Presets like SliceDifficulty.hard stay, and copyWith tunes any number on top of them.</li></ul><h3>Architecture: how it fits together</h3><h3>Packages and their borders</h3><p>The repo is a pub workspace managed with Melos. Every game is its own package; all of them depend on one core and never see each other. Most host apps only add the facade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jhwed2h83TctOf9JrxrOuw.png" /></figure><p>Library packages depend only on flutter and flame: no bloc, freezed, get_it or audio package, so a host app never inherits our version choices. State lives in private ValueNotifiers exposed as read-only ValueListenables.</p><h3>A two-layer game contract</h3><ul><li>GalleryGame&lt;G&gt;<strong>, for the host app.</strong> An immutable recipe: config, GameTheme, GameStrings. createGame(colors) builds a fresh Flame game for every session and buildHud builds the HUD. FruitSlice, SweetSwap and the others are these.</li><li>GalleryFlameGame<strong>, for the game engine.</strong> Owns the phase machine, the score, the overlays and the event stream. A game only implements onRoundStart(), calls addScore() and finish(), and adds stats in collectStats().</li></ul><p>Only the core changes the phase. Games check isPlaying before scoring or penalising, so a late event after the round has ended can never change the score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpfLclyPyjOTrcGzNCQfBA.png" /></figure><h3>One session, start to finish</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xb7lGCbW00stVbrkDJHZA.png" /></figure><p>The event stream is synchronous on purpose: the quit result raised while the game is being removed still reaches the host before it unsubscribes.</p><h3>How graphics are managed</h3><p>A library that runs inside someone else’s app cannot leak memory, fight over a global cache or drain the battery. These are the rules every game follows.</p><ul><li><strong>A private image cache per game.</strong> GalleryFlameGame gives each game its own Images(prefix: &#39;&#39;). The global Flame.images is never touched, so other Flame games in the host app are not affected.</li><li><strong>The cache is cleared on close.</strong> Flame only clears images in dispose(), and GameWidget never calls it. The core clears the cache in onRemove, so opening a game fifty times does not grow memory fifty times.</li><li><strong>One way to name an asset.</strong> GameAsset(&#39;assets/my_fruit.png&#39;) (plus an optional package) becomes a bundle key. The same type points at our placeholder sprites or at the host’s product images.</li><li><strong>Parallel loading.</strong> loadSprites(assets) loads every sprite with Future.wait and keeps their order.</li><li><strong>Animations from strips.</strong> GameAnimation turns a horizontal sprite strip into a SpriteAnimation: frame count and step time, nothing else.</li><li><strong>Backgrounds behind the canvas.</strong> GameBackground is a sealed type (color, gradient or image). The host page draws it behind the GameWidget, and games return resolveBackground(colors.surface) from backgroundColor(), which turns transparent when a backdrop exists.</li><li><strong>Shared effects.</strong> Juice bursts and floating “+10” labels come from GalleryBurst and FloatingLabel in core. TextPaints are created once in onLoad, never per label.</li><li><strong>Two random sources.</strong> Particles use a separate _effectsRandom. The injected Random drives gameplay only, so a seed reproduces the same spawns however the player plays.</li><li><strong>Battery.</strong> The engine pauses 0.8 s after game over: enough for the last effects to finish, then frames stop.</li><li><strong>System UI.</strong> Games run in immersiveSticky and restore edgeToEdge on close; immersive: false opts out.</li><li><strong>IP-clean art.</strong> Mechanics are free, names and art are not. Every sprite and the music are generated placeholders, so companies can ship them or swap in their own.</li></ul><h3>Technical decisions and why</h3><ul><li><strong>One package per game.</strong> A company adds only the game it needs; games cannot break each other; shared needs go to core.</li><li><strong>Minimal dependencies.</strong> No version clashes with the host app. Even audio is an interface; the example app wires it with flame_audio.</li><li><strong>Pure Dart logic layer.</strong> Physics, rules and board logic are tested in milliseconds, without Flame.</li><li><strong>Immutable config + </strong>copyWith<strong>.</strong> Campaign variants are easy to derive. Nullable fields take a ValueGetter: copyWith(bomb: () =&gt; null) removes the bomb.</li><li>@internal<strong> entry points.</strong> Game classes are exported for the HUD, but methods like swipe or spawnWave stay closed outside the package.</li><li>final class<strong> everywhere.</strong> Concrete classes are final, contracts are abstract base or abstract interface, event families are sealed.</li></ul><h3>Testing a game engine, for real</h3><ul><li><strong>Rules, with </strong>test<strong>.</strong> Launch physics, slice geometry, combos, the row planner’s guarantee, board generation and cascades, timing windows, the song timeline.</li><li><strong>Game flow, with </strong>flame_test<strong>.</strong> Phases, score, end conditions, sound cue order; Random(seed) makes every run repeatable.</li><li><strong>End to end, with Maestro.</strong> All four games on an iPhone 17 simulator and a Pixel 7a emulator: menus, pause, HUD values, exact scores, the result returned to the host.</li></ul><p>Menus and HUD values carry Semantics(identifier:) ids (GalleryKeys, RunnerKeys, MatchKeys, RhythmKeys), so tests look for ids, not text, and work in any language. On the seeded Sweet Swap board, one specific swap is verified end to end to trigger a three-level chain worth exactly 210 points.</p><h3>Lessons from testing a Flame game with Maestro</h3><ul><li>A running game is never “idle”, and every element lookup waits for idle: 1–3 s on iOS, about 10 s on Android. HUD checks run while the game is paused.</li><li>On Android, a swipe that starts at the screen edge becomes the system back gesture (pause, then close). Test swipes start between 12% and 88% of the width.</li><li>The first switch to immersive mode shows a one-time Android hint; a shared sub-flow taps it away.</li></ul><h3>From merge to pub.dev</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjRHAOzlP1y04g7JAnSHZg.png" /></figure><p>A release is a version bump plus a CHANGELOG entry. When CI is green on main, release.yml tags every package whose version is not on pub.dev yet (flame_gallery_core-v0.2.0) and runs publish.yml on each tag in order. Publishing uses pub.dev’s GitHub OIDC, so no token lives in the repo. It runs flutter pub publish, because the stock dart-lang/setup-dart workflow cannot publish packages that depend on the Flutter SDK.</p><h3>The packages on pub.dev</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uaai_ztdn8aG3bARyO_2w.png" /></figure><ul><li><a href="https://pub.dev/packages/flame_gallery">flame_gallery</a>: the facade, FlameGallery.show and every game. Start here.</li><li><a href="https://pub.dev/packages/flame_gallery_core">flame_gallery_core</a>: contracts, host page, menus. Use it to build your own game.</li><li><a href="https://pub.dev/packages/flame_gallery_slice">flame_gallery_slice</a>: Fruit Slice</li><li><a href="https://pub.dev/packages/flame_gallery_runner">flame_gallery_runner</a>: Ruins Runner</li><li><a href="https://pub.dev/packages/flame_gallery_match">flame_gallery_match</a>: Sweet Swap</li><li><a href="https://pub.dev/packages/flame_gallery_rhythm">flame_gallery_rhythm</a>: Note Rush</li></ul><h3>What’s next</h3><ul><li>flame_gallery_native<strong>:</strong> native iOS and Android apps open the same games through Flutter add-to-app, with GameResult.toJson() as the payload back. A team without Flutter gets native-rendered mini games too.</li><li><strong>Android polish:</strong> keep the side-edge back gesture from interrupting play.</li><li><strong>Quality:</strong> golden tests for menus and HUD, and frame-time measurements in profile mode on physical devices.</li><li><strong>More games</strong> on the same core.</li></ul><p>Try it, break it and tell me what your campaign needs. Issues and pull requests are welcome.</p><ul><li>Play in the browser: <a href="https://vb10.github.io/flutter_flame_gallery/play/">vb10.github.io/flutter_flame_gallery/play</a></li><li>Website: <a href="https://vb10.github.io/flutter_flame_gallery/">vb10.github.io/flutter_flame_gallery</a></li><li>GitHub: <a href="https://github.com/VB10/flutter_flame_gallery">VB10/flutter_flame_gallery</a></li><li>pub.dev: <a href="https://pub.dev/packages/flame_gallery">flame_gallery</a></li></ul><p><a href="https://github.com/VB10/flutter_flame_gallery">GitHub - VB10/flutter_flame_gallery: Drop-in, brandable 2D mini games for Flutter apps, built on Flame: Fruit Slice, Ruins Runner, Sweet Swap (match-3) and Note Rush (rhythm). One call: FlameGallery.show(context, game: ...).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df3476482fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flame-gallery-drop-in-mini-games-for-flutter-apps-6df3476482fb">Flame Gallery: Drop-in Mini Games for Flutter Apps</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Hand-Writing Your Flutter Network Layer: vexana 6 + AI Skills]]></title>
            <link>https://medium.com/flutter-community/stop-hand-writing-your-flutter-network-layer-vexana-6-ai-skills-24f09e67bf73?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f09e67bf73</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 12:13:20 GMT</pubDate>
            <atom:updated>2026-09-29T12:13:20.945Z</atom:updated>
            <content:encoded><![CDATA[<h4>A typed, testable networking layer on top of dio, and AI skills that write it for you</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcKgyTb8rhlZ0DQLWmnC4w.png" /><figcaption><a href="https://pub.dev/packages/vexana">https://pub.dev/packages/vexana</a></figcaption></figure><p>Every Flutter app has the same chore hiding in it: the network layer. A Dio instance, a base URL, an error model, a model class per endpoint with fromJson and toJson, a service that wraps the calls, and — if you are disciplined — tests with fixtures and mocks.</p><p>None of it is hard. All of it is repetitive. And in 2026 it is exactly the kind of work you should not be typing by hand.</p><p>This post covers four things:</p><ol><li><strong>Why vexana</strong>: what it handles for you that plain dio doesn’t.</li><li><strong>Building a user list, step by step</strong>, from model to screen.</li><li><strong>The live playground</strong>, so you can try it without installing anything.</li><li><strong>The new vexana AI skills</strong>: four skills your AI assistant can follow to set up the layer, turn JSON into models, services, fakes and tests, and migrate old projects.</li></ol><h3>1. Why vexana?</h3><p><a href="https://pub.dev/packages/vexana">vexana</a> is a networking layer for Flutter built on <a href="https://pub.dev/packages/dio">dio</a>. You keep everything dio gives you (interceptors, adapters, CancelToken, FormData) and stop rewriting the parts every app ends up needing.</p><blockquote>Where does the name come from? Vexana is a hero in Mobile Legends, and the one I loved playing the most. When I was writing a library whose whole job is to pull data in from the network, her name was the first thing that came to mind, and it stuck.</blockquote><h3>Typed models and a sealed result</h3><p>You parse into your own classes, not Map&lt;String, dynamic&gt;, and every request returns a NetworkResult: either NetworkSuccessResult with your data or NetworkErrorResult with the error. It&#39;s a sealed class, so a switch that forgets the error case doesn&#39;t compile.</p><pre>final result = await manager.sendRequest&lt;User, List&lt;User&gt;&gt;(<br>  &#39;/users&#39;,<br>  parseModel: const User(),<br>  method: RequestType.GET,<br>);<br><br>final message = switch (result) {<br>  NetworkSuccessResult(:final data) =&gt; &#39;${data.length} users&#39;,<br>  NetworkErrorResult(:final error) =&gt; &#39;Failed: ${error.description}&#39;,<br>};</pre><p>Prefer callbacks? result.fold(onSuccess: ..., onError: ...) does the same.</p><h3>Refresh tokens without the race conditions</h3><p>When a request comes back 401, vexana calls your onRefreshToken callback and retries the original request with the new token. 401s are handled one at a time in a queue, so parallel requests don&#39;t race each other with half-refreshed tokens; once the token is refreshed, they all go through. If the retried request still fails after maxRetryCount attempts, onRefreshFail runs, which is where you send the user back to login.</p><pre>final manager = NetworkManager&lt;EmptyModel&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://api.example.com&#39;),<br>  onRefreshToken: (error, newService) async {<br>    final token = await authRepository.refresh(newService);<br>    error.requestOptions.headers[&#39;Authorization&#39;] = &#39;Bearer $token&#39;;<br>    return error;<br>  },<br>  onRefreshFail: () =&gt; router.goToLogin(),<br>  maxRetryCount: 3,<br>);</pre><p>newService is a separate manager without the refresh interceptor, so your refresh call can&#39;t end up refreshing itself.</p><h3>Your API’s error body, parsed</h3><p>Give the manager your error model and error responses are parsed into it, so the UI reads error.model?.message instead of digging through a raw response.</p><pre>final manager = NetworkManager&lt;ApiError&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://api.example.com&#39;),<br>  errorModel: const ApiError(),<br>);</pre><h3>Cache with one parameter</h3><p>Pass a fileManager (LocalFile or LocalPreferences) to the manager, then add expiration to any request. Until it expires, the same request is answered from the cache: no network call, typically in about a millisecond. cache.removeAll() clears it, for example on logout.</p><pre>final manager = NetworkManager&lt;EmptyModel&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://api.example.com&#39;),<br>  fileManager: LocalFile(), // or LocalPreferences()<br>);<br><br>await manager.sendRequest&lt;User, List&lt;User&gt;&gt;(<br>  &#39;/users&#39;,<br>  parseModel: const User(),<br>  method: RequestType.GET,<br>  expiration: const Duration(minutes: 10),<br>);<br>await manager.cache.removeAll(); // e.g. on logout</pre><h3>No-network retry, built in</h3><p>Pass noNetwork: NoNetwork(context) and a request that fails for lack of a connection shows a bottom sheet with a retry button. You can supply your own widget with customNoNetwork.</p><pre>NetworkManager&lt;EmptyModel&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://api.example.com&#39;),<br>  noNetwork: NoNetwork(<br>    context,<br>    customNoNetwork: (onRetry) =&gt; TextButton(<br>      onPressed: onRetry,<br>      child: const Text(&#39;No connection. Try again&#39;),<br>    ),<br>  ),<br>);</pre><h3>And the rest</h3><p>A request logger (isEnableLogger), file upload with FormData, downloads with progress, CancelToken support, and it runs on mobile and on the web, including WebAssembly.</p><pre>final manager = NetworkManager&lt;EmptyModel&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://api.example.com&#39;),<br>  isEnableLogger: true,<br>);<br><br>// Upload<br>await manager.uploadFile&lt;Map&lt;String, dynamic&gt;&gt;(<br>  &#39;/avatar&#39;,<br>  FormData.fromMap({&#39;file&#39;: await MultipartFile.fromFile(filePath)}),<br>);<br>// Download with progress<br>await manager.downloadFile(<br>  &#39;/report.pdf&#39;,<br>  (received, total) =&gt; print(&#39;$received / $total&#39;),<br>);<br>// Cancel<br>final cancelToken = CancelToken();<br>manager.sendRequest&lt;User, List&lt;User&gt;&gt;(<br>  &#39;/users&#39;,<br>  parseModel: const User(),<br>  method: RequestType.GET,<br>  cancelToken: cancelToken,<br>);<br>cancelToken.cancel();</pre><h3>2. Let’s build a user list, step by step</h3><p>Let’s fetch users from <a href="https://jsonplaceholder.typicode.com/users">JSONPlaceholder</a> and show them in a list.</p><h3>Step 1: Describe the data</h3><p>A response model extends INetworkModel&lt;T&gt;, which tells vexana how to parse it:</p><pre>final class User extends INetworkModel&lt;User&gt; {<br>  const User({this.id, this.name, this.email});<br><br>factory User.fromMap(Map&lt;String, dynamic&gt; json) =&gt; User(<br>        id: json[&#39;id&#39;] as int?,<br>        name: json[&#39;name&#39;] as String?,<br>        email: json[&#39;email&#39;] as String?,<br>      );<br>  final int? id;<br>  final String? name;<br>  final String? email;<br>  @override<br>  User fromJson(Map&lt;String, dynamic&gt; json) =&gt; User.fromMap(json);<br>  @override<br>  Map&lt;String, dynamic&gt; toJson() =&gt; {&#39;id&#39;: id, &#39;name&#39;: name, &#39;email&#39;: email};<br>}</pre><h3>Step 2: Create one manager</h3><pre>final INetworkManager&lt;EmptyModel&gt; manager = NetworkManager&lt;EmptyModel&gt;(<br>  options: BaseOptions(baseUrl: &#39;https://jsonplaceholder.typicode.com&#39;),<br>  fileManager: LocalPreferences(),<br>);</pre><p>EmptyModel means &quot;this API has no error body to parse&quot;. LocalPreferences enables the cache.</p><h3>Step 3: Fetch the users</h3><pre>Future&lt;NetworkResult&lt;List&lt;User&gt;, EmptyModel&gt;&gt; fetchUsers() =&gt;<br>    manager.sendRequest&lt;User, List&lt;User&gt;&gt;(<br>      &#39;/users&#39;,<br>      parseModel: const User(),<br>      method: RequestType.GET,<br>      expiration: const Duration(minutes: 5),<br>    );</pre><p>The first type argument is the model to parse, and the second is what you get back: List&lt;User&gt; because /users returns a JSON array. With expiration, calls in the next five minutes come from the cache.</p><h3>Step 4: Show them on screen</h3><pre>FutureBuilder(<br>  future: _users, // = fetchUsers()<br>  builder: (context, snapshot) =&gt; switch (snapshot.data) {<br>    null =&gt; const Center(child: CircularProgressIndicator()),<br>    NetworkSuccessResult(:final data) =&gt; ListView.builder(<br>        itemCount: data.length,<br>        itemBuilder: (context, index) =&gt; ListTile(<br>          leading: CircleAvatar(child: Text(&#39;${data[index].id}&#39;)),<br>          title: Text(data[index].name ?? &#39;&#39;),<br>          subtitle: Text(data[index].email ?? &#39;&#39;),<br>        ),<br>      ),<br>    NetworkErrorResult(:final error) =&gt; Center(<br>        child: Text(&#39;Error ${error.statusCode}: ${error.description}&#39;),<br>      ),<br>  },<br>)</pre><p>The switch covers loading (null), success and error, and the compiler checks that none is missing.</p><h3>The result</h3><p>the user list running in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Vb17IKj2ZTwpW7_JDPEfUw.png" /></figure><p>Notice what is <em>not</em> there: no jsonDecode, no try/catch around the request, no Map&lt;String, dynamic&gt; in the UI. The package&#39;s <a href="https://pub.dev/packages/vexana/example">example</a> has the same pattern as a complete page, with pull-to-refresh.</p><h3>3. Try it in your browser: the playground</h3><p>Reading about a networking library only gets you so far. The <strong>vexana playground</strong> is a Flutter Web app (compiled to WebAssembly) that runs the real package:</p><p>👉 <a href="https://vb10.github.io/vexana/"><strong>https://vb10.github.io/vexana/</strong></a></p><ul><li>Pick an endpoint and send a request.</li><li>Turn on <strong>Cache</strong>, set the expiration, and send the same request again. The first call goes to the network (around 400 ms); the second comes back from the cache in about <strong>1 ms</strong> and is marked cache hit.</li><li>Turn on the <strong>Logger</strong> to see what vexana does under the hood.</li><li>The <strong>Session metrics</strong> table shows count, p50, p95, max, errors and cache hits for each endpoint, with network and parse time listed separately.</li></ul><p>It’s the quickest way to see how the options behave before you add the package to your app.</p><h3>4. Let your AI assistant write the boilerplate: vexana AI skills</h3><p>This is the part I’m most excited about.</p><p>You <em>could</em> ask an AI assistant to “write a vexana model for this JSON” and hope for the best. Sometimes you’d get the old API, sometimes a model that doesn’t compile, and almost never tests.</p><p>So vexana now ships <strong>AI skills</strong>: a set of playbooks written by the package maintainers. Each skill contains the exact vexana 6 API, templates that have been compiled and tested, and a procedure that ends by running dart analyze and flutter test. The assistant doesn&#39;t improvise the layer; it follows a playbook.</p><p>The skills are plain Markdown files (SKILL.md), so they aren&#39;t tied to one tool.</p><h3>Install</h3><p><strong>Claude Code</strong> has a ready-made plugin:</p><pre>/plugin marketplace add VB10/vexana<br>/plugin install vexana@vexana</pre><p><strong>Other AI assistants</strong> (Cursor, GitHub Copilot, Codex, Gemini CLI, …): copy the <a href="https://github.com/VB10/vexana/tree/master/plugins/vexana/skills">plugins/vexana/skills</a> folder into your project and ask the assistant to follow a skill, for example <em>&quot;follow skills/add/SKILL.md for this JSON&quot;</em>.</p><p>There are four skills. The examples below use Claude Code’s command syntax; with another assistant, describe the same request in plain words.</p><h3>/vexana:init: set up the layer</h3><pre>/vexana:init base URL https://api.example.com, cache LocalFile</pre><p>It reads your project first and puts files where your structure expects them. If you already have lib/product/… or lib/core/…, it uses that instead of inventing a new layout. Then it:</p><ul><li>adds vexana and mocktail (dev),</li><li>creates a single AppNetworkManager whose base URL can be overridden with --dart-define=BASE_URL=...,</li><li>generates an error model if you paste an error response,</li><li>adds a small fixture helper for tests.</li></ul><p>Run it twice and nothing changes. It never overwrites your files.</p><h3>/vexana:add: JSON in, typed code out</h3><pre>/vexana:add GET /posts and GET /posts/{id}, feature post, JSON in api/posts.json</pre><p>From one JSON sample you get:</p><ul><li>a Post model (nested objects become their own classes),</li><li>a PostService behind an IPostService interface, using sendRequest,</li><li>the sample saved as a test fixture,</li><li>a round-trip test: fixture → fromJson → toJson → same JSON.</li></ul><pre>@override<br>Future&lt;NetworkResult&lt;List&lt;Post&gt;, EmptyModel&gt;&gt; fetchPosts() {<br>  return _manager.sendRequest&lt;Post, List&lt;Post&gt;&gt;(<br>    &#39;/posts&#39;,<br>    parseModel: const Post(),<br>    method: RequestType.GET,<br>  );<br>}</pre><p>It also handles the awkward parts of real APIs:</p><ul><li>Keys like class, default, 2fa or user-name become valid Dart fields (class_, default_, n2fa, userName), while the original JSON keys are kept for parsing.</li><li>1 in one element and 1.5 in another means double.</li><li>An empty array or a field that is always null is typed as Object?, and the report lists it so you can decide the real type instead of the tool guessing.</li></ul><h3>/vexana:multiple-add: a whole API at once</h3><p>Point it at a folder of JSON responses:</p><pre>/vexana:multiple-add api_samples/ — GET /posts, GET /users, GET /comments, GET /companies</pre><p>It first shows a plan (model, feature, endpoint) and waits for your OK. Then, for each feature, it writes:</p><ul><li>the model(s), <strong>with shared types deduplicated</strong>: if users.json has a nested company and companies.json has the same shape, you get one Company class;</li><li>the service and its interface;</li><li>a <strong>Fake service</strong> with a few embedded sample items, so you can build UI before the backend is ready;</li><li><strong>mocktail service tests</strong> (success and error for every method) and model tests.</li></ul><p>In my test run, four JSON files became <strong>20 files and 16 passing tests</strong>, with dart analyze reporting no issues.</p><h3>/vexana:refactor: bring old projects to vexana 6</h3><pre>/vexana:refactor</pre><p>For projects on vexana 4.x or 5.x, it:</p><ul><li>runs your tests first to record a baseline,</li><li>shows the planned changes and asks before touching anything,</li><li>bumps the dependency and fixes imports that no longer exist,</li><li><strong>flags the calls whose behaviour changed</strong>, with an explanation. For example, removeAll() now clears only that manager&#39;s cache, and sendPrimitive now runs through your interceptors.</li></ul><p>At the end it compares your tests against the baseline, so a regression isn’t mistaken for a failure that was already there.</p><h3>Why skills and not just a prompt?</h3><p>Because the skills already contain the parts you would otherwise have to check yourself:</p><ul><li><strong>The right API.</strong> The skills carry a reference of the vexana 6 surface, so there are no hallucinated methods.</li><li><strong>Tested templates.</strong> Every template was compiled and tested in a real Flutter project before it went into the plugin.</li><li><strong>Verification.</strong> Every command ends with dart analyze and flutter test, and reports failures as they are instead of claiming success.</li><li><strong>Safe defaults.</strong> It asks before overwriting, asks on name collisions, and waits for confirmation on bulk changes.</li></ul><h3>Get started</h3><ul><li>📦 flutter pub add vexana, then see <a href="https://pub.dev/packages/vexana">pub.dev/packages/vexana</a></li><li>▶️ Playground: <a href="https://vb10.github.io/vexana/">vb10.github.io/vexana</a></li><li>🤖 AI skills: <a href="https://github.com/VB10/vexana/tree/master/plugins/vexana/skills">plugins/vexana/skills</a>. In Claude Code: /plugin marketplace add VB10/vexana, then /plugin install vexana@vexana</li><li>⭐ Source: <a href="https://github.com/VB10/vexana">github.com/VB10/vexana</a></li></ul><p>If the skills save you an afternoon of boilerplate, a star on GitHub helps other Flutter developers find it. And if a skill generates something you’d write differently, open an issue: the templates are plain Markdown and easy to improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f09e67bf73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/stop-hand-writing-your-flutter-network-layer-vexana-6-ai-skills-24f09e67bf73">Stop Hand-Writing Your Flutter Network Layer: vexana 6 + AI Skills</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autonomous Flutter UI Testing: Claude Code + Maestro MCP on a Real, Live App]]></title>
            <link>https://medium.com/flutter-community/autonomous-flutter-ui-testing-claude-code-maestro-mcp-on-a-real-live-app-d9cdf68bac8d?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9cdf68bac8d</guid>
            <category><![CDATA[maestros]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ui-test-automation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-07-31T06:01:01.905Z</atom:updated>
            <content:encoded><![CDATA[<p>No hand-written selectors, no guessing from source code. I pointed an agent at a live Flutter app and it drove the simulator itself — reading the real view hierarchy, writing its own tests, and coming back with an honest list of what it couldn’t reach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVNDTf-esOzvT2h2wUXcJw.png" /></figure><p>I connected <a href="https://maestro.dev/">Maestro</a>’s MCP server to <a href="https://claude.com/claude-code">Claude Code</a>, gave it a 624-line instruction manual, and let it loose on a Flutter app that’s live on both app stores. It explored the app on an iOS simulator by itself and wrote the E2E suite.</p><ul><li><strong>Generated</strong> — 8 smoke flows + 5 reusable sub-flows, 444 lines of YAML</li><li><strong>Result</strong> — one run, <strong>218 seconds, 0 failures</strong>, against live Firestore</li><li><strong>Source changes</strong> — <strong>zero lines under </strong><strong>lib/</strong>, and that was a hard rule</li><li><strong>Best find</strong> — 7 accessibility ids in my own app that don’t exist on the device</li></ul><p>Three things worth your time even if you never touch Maestro:</p><ul><li><strong>Flutter’s </strong><strong>Key() is invisible to UI automation.</strong> Only Semantics(identifier:) becomes a native accessibility id. My &quot;instrumented&quot; home screen was opaque.</li><li><strong>Giving an agent tools ≠ giving it judgement.</strong> The rules that mattered were all <em>prohibitions</em>.</li><li><strong>The shift isn’t that AI writes tests. It’s that it can now check its own work</strong> against a running device instead of guessing from source.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgeo.dailymotion.com%2Fplayer.html%3Fvideo%3Dxatiaue%26&amp;display_name=Dailymotion&amp;url=https%3A%2F%2Fwww.dailymotion.com%2Fvideo%2Fxatiaue&amp;image=https%3A%2F%2Fs2.dmcdn.net%2Fv%2Fc_gnc1gQwrXN4Tich%2Fx240&amp;type=text%2Fhtml&amp;schema=dailymotion" width="480" height="269" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2ebd5221feff15e6dd32c67428bf1c3/href">https://medium.com/media/a2ebd5221feff15e6dd32c67428bf1c3/href</a></iframe><h3>The app</h3><p><strong>Hatayı Yaşat</strong> (“Keep Hatay Alive”) — open-source Flutter app for Hatay, the Turkish province hit hardest by the February 2023 earthquakes. Thousands of local businesses were destroyed or relocated into container marketplaces; the app exists so people can find them again, and so the city’s visual memory doesn’t disappear with its buildings.</p><p>Place directory · maps &amp; directions · community feed (news / events / jobs) · a shared before-and-after photo gallery · favourites · TR/EN · Material 3 light + dark.</p><p>Flutter 3.7+, <strong>Riverpod v3</strong> (@riverpod codegen, no Freezed), go_router typed routes, get_it, and a <strong>live Firestore backend</strong> — that last one shapes every testing decision below.</p><p><a href="https://play.google.com/store/apps/details?id=com.hatayiyasat.app&amp;hl=tr">Google Play</a> · <a href="https://apps.apple.com/us/app/hatay%C4%B1-ya%C5%9Fat/id6465691080">App Store</a> · <a href="https://github.com/VB-CORE/life_client">GitHub</a> (MIT, v8.1.0) · <a href="https://www.instagram.com/hatayiyasat/">Instagram</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwceOHcGJjmANqC3SzUo-g.png" /><figcaption>The place directory, a place detail, and the shared memories gallery. All three frames were captured by the agent, not by me.</figcaption></figure><h3>The problem: zero UI tests</h3><p>Four bottom tabs. A directory backed by live Firestore. A community feed with three sub-tabs. A memories gallery with a first-visit dialog. An onboarding flow, a version-gated “What’s New” sheet, and a FAB speed dial with three forms that write to production.</p><p>And <strong>zero end-to-end tests</strong> — not because nobody cared, but because writing them is a grind that never gets prioritised: tap around, write a selector, it breaks, discover the button has no accessible id, add one, rebuild, retry. Multiply by forty screens.</p><p>So instead of writing the tests, I wrote <strong>the thing that writes the tests</strong>, and got out of its way. The whole session is on video — in Turkish, but the terminal and the simulator carry it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8xSukTDwe8A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8xSukTDwe8A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8xSukTDwe8A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/353cc1b078f3913d6924e1578ba082d5/href">https://medium.com/media/353cc1b078f3913d6924e1578ba082d5/href</a></iframe><h3>Piece 1: Maestro over MCP</h3><p>Maestro flows are plain YAML. No compilation, no page-object ceremony:</p><pre>appId: com.hatayiyasat.app<br>---<br>- launchApp<br>- tapOn: &quot;Mekanlar&quot;<br>- assertVisible: &quot;İşletme Açıklaması&quot;</pre><p>Great format — but you still had to <em>write</em> it, which means knowing what’s on screen first.</p><p>Then Maestro shipped an <strong>MCP server</strong>. <a href="https://modelcontextprotocol.io/">MCP</a> is the standard that lets an agent call real tools instead of hallucinating about them. Connected, the agent gets a physical toolbox:</p><pre>list_devices · start_device · launch_app · stop_app<br>inspect_view_hierarchy · take_screenshot<br>tap_on · input_text · back<br>run_flow · run_flow_files · check_flow_syntax<br>cheat_sheet · query_docs</pre><p>Three of those change everything:</p><ul><li><strong>inspect_view_hierarchy</strong> — reads what&#39;s <em>actually rendered</em>, real ids and real labels, not source-code guesses.</li><li><strong>take_screenshot</strong> — the agent sees the result of its own action.</li><li><strong>run_flow</strong> — it verifies the YAML it just wrote, immediately, on a live device.</li></ul><p>The agent stops being a code generator and becomes something closer to a QA engineer holding the phone. Wiring it up is nine lines at the repo root:</p><pre>// .mcp.json<br>{<br>  &quot;mcpServers&quot;: {<br>    &quot;maestro&quot;: { &quot;command&quot;: &quot;maestro&quot;, &quot;args&quot;: [&quot;mcp&quot;], &quot;env&quot;: {} }<br>  }<br>}</pre><p>Restart Claude Code and the tools are live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bUXz9OMtPskeYBYZRqs5hQ.png" /><figcaption><em>claude mcp list output showing </em><em>maestro: connected</em></figcaption></figure><h3>Piece 2: the skill, because tools aren’t judgement</h3><p>With just the MCP connected and a prompt like <em>“write me some UI tests”</em>, the agent does exactly what you’d fear. It reads the source, sees Key(&#39;homeSearchField&#39;), writes tapOn: { id: &quot;homeSearchField&quot; }, gets a failure — and starts <strong>improvising</strong>: retrying blindly, tapping coordinates, loosening assertions until something goes green. You get a suite that passes and proves nothing.</p><p>A <a href="https://docs.claude.com/en/docs/claude-code/skills"><strong>Claude Code skill</strong></a> is a folder of markdown loaded into context when a matching task shows up. Not code — an operating manual:</p><pre>.claude/skills/hata-maestro-auto/<br>├── SKILL.md                        188 lines — 4-phase protocol + 10 hard rules<br>└── references/<br>    ├── screen-map.md                64 lines — 25+ screens: route, path, anchor, gaps<br>    ├── selectors.md                121 lines — live Semantics ids vs. text anchors<br>    ├── flow-templates.md           189 lines — bootstrap / goto-* / smoke starters<br>    └── key-injection.md             62 lines — what to do when a control has no selector</pre><p>624 lines of instructions to produce 444 lines of tests. That ratio looks absurd until you notice the instructions are reusable and the tests are disposable.</p><h3>The rules that changed the output</h3><ol><li><strong>Never write a selector you haven’t inspected.</strong> Re-inspect after <em>every</em> navigation — a stale tree produces confident, wrong selectors.</li><li><strong>Never touch </strong><strong>lib/.</strong> If a control can&#39;t be selected, write it down and ask. The most important rule in the file; there&#39;s a whole section on why below.</li><li><strong>Never assert on live data.</strong> Static labels or structural facts only — place names and news items come from Firestore and change hourly.</li><li><strong>Never assert on version-dependent text.</strong> Yenilikler v8.1.0 🎉 dies at the next release. Catch that sheet with id: whatsNewSheet instead.</li><li><strong>Maestro YAML text matching is exact regex.</strong> &quot;Mekanlar&quot; won&#39;t match &quot;Mekanlar!&quot;. Meanwhile the MCP tap_on tool is <em>fuzzy</em> by default — so a tap that works interactively can fail inside the flow.</li><li><strong>iOS tab labels are multiline <em>and</em> localised.</strong> Tab 4 reads &quot;Sekme 4 / 4\nFavoriler&quot; — position first, label second, both translated. The English mental model (&quot;Favorites\nTab 4 of 4&quot;) is wrong twice over.</li><li><strong>On failure, STOP.</strong> Screenshot, report the failing step and the screen state, then wait. <em>A stuck screen is itself a finding.</em> This is the rule that separates a test suite from a green-checkmark generator.</li><li><strong>Flutter </strong><strong>Key is not an accessibility id.</strong> This one deserves its own section. ↓</li></ol><h3>The finding that justified the whole exercise</h3><p>references/selectors.md has a column that reads &quot;is it live?&quot; — and seven entries marked <strong>no</strong>:</p><pre>homeView · homeScrollView · homeSliverAppBar · homeSearchFilterRow ·<br>homeSearchField · homeFilterButton · homeCategoriesSection</pre><p>The project has a proper id registry: a GeneralSemanticKeys enum plus a GeneralSemantic wrapper. All seven names are <em>defined</em> in that enum. Someone did the work. But in home_view.dart they&#39;re wired with Flutter&#39;s Key(...) instead of the wrapper:</p><pre>// invisible to Maestro, and to VoiceOver<br>TextField(key: const Key(&#39;homeSearchField&#39;), …)</pre><pre>// produces a real native id<br>GeneralSemantic(semanticKey: GeneralSemanticKeys.homeTab, child: …)</pre><blockquote><em>Semantics(identifier: &#39;foo&#39;) compiles to </em><em>accessibilityIdentifier on iOS and </em><em>resource-id on Android — what Maestro matches with </em><em>id: &quot;foo&quot;. </em><em>Key / </em><em>ValueKey produces </em><strong><em>no native id at all</em></strong><em>. It exists for widget tests.</em></blockquote><p>So the home screen <em>looked</em> fully instrumented in code review and was completely opaque to any external automation tool. The agent found it in minutes — not by reading code, but by comparing the enum against the live tree and noticing the enum was lying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRhLELlaWLP-cX1_rURm6g.png" /><figcaption>Same enum, wired two ways. The search field arrives on the device with no <em>resource-id</em>. The tab next to it arrives with one. Same tree, same run.</figcaption></figure><h3>Three more things it found just by looking</h3><p><strong>A dialog nobody remembered.</strong> The Memories tab opens a one-time info dialog on first visit — SharedCache.isFirstHistoryPageVisit, post-frame, barrierDismissible: false. I wrote that code and had completely forgotten it: on my device it fired once, in 2024. The agent hit it on the first clearState run and the flow died — with a non-dismissible modal up, <strong>every control underneath disappears from the accessibility tree</strong>, so even &quot;is the Memories tab selected?&quot; fails. It now has an explicit guard, and flow 05 asserts the dialog on purpose.</p><p><strong>back doesn&#39;t always mean back on iOS.</strong> The photo viewer is a full-screen modal route. Maestro&#39;s back — a left-edge swipe — doesn&#39;t close it; you have to tap the X. Worth knowing before you sprinkle back through a suite.</p><p><strong>My own reference doc was lying.</strong> I’d hand-written the community sub-tab order as <em>News / Jobs / Events</em>. On the device it’s <em>News / </em><strong><em>Events</em></strong><em> / Jobs</em>. I got my own app’s tab order wrong in the document I wrote to make the agent accurate — and the only reason it didn’t matter is that rule #1 forbids trusting exactly that kind of note. Static docs drift; the running device doesn’t.</p><h3>How the run actually works</h3><h3>Phase 0 — prove the ground is solid</h3><p>Check the MCP responds, boot a simulator, and make sure the installed binary is current:</p><pre>flutter build ios --simulator --debug<br>xcrun simctl install Booted build/ios/iphonesimulator/Runner.app</pre><p>If the install is stale, launch_app silently opens the old binary and you spend an hour debugging selectors that were fixed yesterday.</p><p>Then the gate: <strong>bootstrap.yaml green twice in a row</strong> before writing anything else. If the entry point isn&#39;t boringly repeatable, every flow inherits the flakiness. (Mine passed this gate and <em>still</em> had a race in it — below.)</p><h3>Phase 1 — autonomous exploration</h3><p>One action at a time, always from the live tree. Never batched from memory:</p><pre>inspect → pick exactly ONE next action from what&#39;s ACTUALLY on screen<br>        → tap / type / swipe / back<br>        → screenshot to maestro/reports/explore-&lt;area&gt;/NN-&lt;label&gt;.png<br>        → inspect again</pre><p>The target list: four bottom tabs, home category chips and search delegate, filter screen, a place detail, community sub-tabs, AppBar overflow, the FAB speed dial (<strong>open the forms, go back, never submit</strong> — that’s a live Firestore write), settings.</p><p>Output is a regenerated screen-map.md. Per screen: entry route, path from home, a durable anchor, which sub-flow to reuse, and a <strong>needs-id</strong> column. A slice of it:</p><pre>SCREEN          ROUTE                    FROM HOME          ANCHOR                NEEDS-ID?<br>──────────────  ───────────────────────  ─────────────────  ────────────────────  ─────────────────────────────<br>Main shell      /main                    —                  id: mainTabView       —<br>Home            tab 0                    id: homeTab        &quot;Mekanlar&quot;            search field, filter button,<br>                                                                                  category strip — Key(), NOT LIVE<br>Filter          /main/filter             filter btn (icon)  &quot;İlçeler&quot;             icon-only + no id → point:<br>Place detail    /main/placeDetail/:id    tap a card         &quot;İşletme Açıklaması&quot;  card ids dynamic, grid only<br>Community       tab 1                    id: communityTab   &quot;Haberler&quot;            sub-tabs have no ids<br>Business form   /main/placeRequestForm   FAB → menu         &quot;Yeni İşletme Talebi&quot; FAB icon-only · NEVER SUBMIT</pre><h3>Phase 2 — write the suite</h3><p>Five reusable sub-flows (one bootstrap + a goto_* per tab), then eight smoke flows on top. bootstrap.yaml is the spine — and the comment in it is scar tissue from a bug two sections down:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22bb9d84ba9f066f42fc7d7b478ffa1f/href">https://medium.com/media/22bb9d84ba9f066f42fc7d7b478ffa1f/href</a></iframe><p>The eight smoke flows and what each one locks down:</p><ul><li><strong>01_app_launch</strong> — cold start: splash → onboarding → what&#39;s-new → the four-tab shell.</li><li><strong>02_home_tab</strong> — home: place list loaded, search field present, no empty-state.</li><li><strong>03_home_place_detail</strong> — detail: Call / Directions buttons, tab bar hidden, back works.</li><li><strong>04_community_tab</strong> — the News / Events / Jobs sub-tab strip.</li><li><strong>05_memories_tab</strong> — first-visit dialog, photo grid, favourite-memories sheet.</li><li><strong>06_favorite_tab</strong> — favourites empty state.</li><li><strong>07_favorite_add_and_list</strong> — <strong>end-to-end:</strong> favourite from a detail screen → see it in the list → clear all.</li><li><strong>08_tab_bar_navigation</strong> — full tab tour plus the &quot;exactly one tab selected&quot; invariant.</li></ul><p>The design decision worth stealing: <strong>every flow starts from </strong><strong>bootstrap with </strong><strong>clearState.</strong> Tests are fully isolated — the favourite flow 07 adds can&#39;t leak into flow 06&#39;s empty-state assertion. Costs a few seconds each, buys a red result you can trust.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b64fb59826ede2a6d6cde64c6653f8/href">https://medium.com/media/09b64fb59826ede2a6d6cde64c6653f8/href</a></iframe><p>Here’s flow 07 actually running — no human touching the device. Open a place from the directory, favourite it, go back (the card’s heart is red now), switch to the Favourites tab, find it there, then clear the list and land back on the empty state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*k4rjRusGJEXiKNPy3BauHA.gif" /><figcaption><em>Flow 07 in 19 seconds: favourite a place, verify it in the Favourites tab, clean up after itself. Every tap here is an assertion that has to hold.”</em></figcaption></figure><h3>Phase 3 — report the gaps, don’t fix them</h3><p>When a control has no stable selector: prove the gap live, locate the widget in lib/, <strong>write it down, stop</strong>, and ask the user once. Only on an explicit yes does the id actually get added. So the generated YAML ships comments like this on purpose:</p><pre># NEEDS-ID: the heart FAB has no id, tapped by position (endDocked, bottom-right).<br># If `GeneralSemanticKeys.memoryFavoriteButton` is added, replace this with `id:`.<br>- tapOn:<br>    point: &quot;89%,75%&quot;</pre><p>This is the design choice I’d defend hardest. <strong>An agent that can edit your app to make its own tests pass has a conflict of interest.</strong> The moment “the test is red” and “I can change the app” are both true, the cheapest path to green stops going through <em>correctness</em>. Cutting that path means every red result is information — and the diff stays reviewable.</p><h3>The two parts where it broke</h3><p>Neither bug was in the app. Both are the kind you only find by running the thing on a device.</p><h3>Bug one: the screenshots went somewhere else</h3><p>First full-suite run, actual JUnit:</p><pre>&lt;testcase id=&quot;smoke_test_auto&quot; status=&quot;ERROR&quot; time=&quot;19.0&quot;&gt;<br>  &lt;failure&gt;Unknown error&lt;/failure&gt;<br>&lt;/testcase&gt;</pre><p>Two minutes later, a single flow: status=&quot;SUCCESS&quot;. Individual green, combined red.</p><p>The cause: flows wrote screenshots to &quot;../../reports/smoke/…&quot;, relative to the flow file. <strong>Maestro resolves </strong><strong>takeScreenshot paths against the project root.</strong> Twelve paths across eight files, plus a runner that didn&#39;t guarantee its working directory:</p><pre># takeScreenshot paths resolve against the PROJECT ROOT (&quot;maestro/reports/smoke/…&quot;),<br># so maestro is always invoked from the project root.<br>cd &quot;$PROJECT_DIR&quot;</pre><p>The honest version of “AI wrote my tests” includes the twenty minutes of path debugging. The agent produced a suite that was structurally correct and environmentally wrong — exactly the failure mode to expect and plan for.</p><h3>Bug two: waiting for a screen that’s already gone</h3><p>This one was mine, and it’s more interesting because it <em>passed</em> for a while first:</p><pre>- extendedWaitUntil: { visible:    { id: &quot;splashView&quot; }, timeout: 30000 }<br>- extendedWaitUntil: { notVisible: { id: &quot;splashView&quot; }, timeout: 60000 }</pre><p>Read it out loud and it sounds careful. Then, mid-suite, flow 02 died on the first line:</p><pre>Assertion &#39;id: splashView is visible&#39; failed.</pre><p>The splash had come and gone faster than Maestro’s first poll. <strong>Waiting for a transient screen to appear is a race by construction</strong> — the faster the app gets, the more often you lose. And because it only loses <em>sometimes</em>, it reads as flaky infrastructure rather than a wrong test.</p><p>The same reasoning killed the two when: guards that used to wrap onboarding and the what&#39;s-new sheet. when: visible: reads as robustness but it&#39;s a <strong>snapshot, not a wait</strong> — if the state hasn&#39;t rendered yet, the guard silently skips and the flow marches into a screen it doesn&#39;t understand. With clearState both sheets are certainties, so asserting them outright is simpler <em>and</em> stricter: if either stops appearing, I want a red line, not a shrug.</p><h3>The result</h3><pre>&lt;testsuite device=&quot;iPhone 17 - iOS 26.4&quot; tests=&quot;1&quot; failures=&quot;0&quot; time=&quot;218.0&quot;&gt;<br>  &lt;testcase id=&quot;smoke_test_auto&quot; status=&quot;SUCCESS&quot; time=&quot;218.0&quot;/&gt;<br>&lt;/testsuite&gt;</pre><p>Eight flows chained into one run, 218 seconds, against live Firestore. Thirteen screenshots, none of them taken by a human:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB0-zzBPuEY1mvQ9soR0CQ.png" /><figcaption>One run, 218 seconds, thirteen frames. A storyboard of an app being exercised end to end by something that had never seen it before.</figcaption></figure><p>Maestro will also record the whole thing as video, which is the fastest way to show someone what “the agent drove the app” actually means — terminal steps going green on the left, the app being driven on the right:</p><pre>maestro record --local maestro/flows/smoke_test_auto.yaml smoke_test_auto.mp4</pre><p>One warning worth passing on: record re-runs the flow and records <em>whatever happens</em>, including a failure. My first recording was a tidy 19 seconds and I nearly shipped it — until I noticed 19 seconds was exactly how long the suite survived before the screenshot-path bug killed it. A short video isn&#39;t a compact video; it&#39;s a dead run. Check the duration against your JUnit time before you publish it anywhere.</p><h3>Steal this for your own app</h3><pre># 1) Maestro<br>curl -fsSL &quot;https://get.maestro.mobile.dev&quot; | bash</pre><pre># 2) MCP definition at the repo root<br>cat &gt; .mcp.json &lt;&lt;&#39;JSON&#39;<br>{ &quot;mcpServers&quot;: { &quot;maestro&quot;: { &quot;command&quot;: &quot;maestro&quot;, &quot;args&quot;: [&quot;mcp&quot;], &quot;env&quot;: {} } } }<br>JSON</pre><pre># 3) the skill<br>npx degit VB-CORE/life_client/.claude/skills/hata-maestro-auto#release/v2/1.0.0_1 \<br>  .claude/skills/hata-maestro-auto</pre><pre># 4) restart Claude Code, then verify<br>claude mcp list</pre><p>One script wraps boot → build → install → run → JUnit report, and the output drops straight into CI:</p><pre>./maestro/run.sh                # smoke_test_auto — every flow in one run<br>./maestro/run.sh --build        # build + install first<br>./maestro/run.sh smoke          # the smoke/ flows one by one<br>./maestro/run.sh flows/smoke/01_app_launch.yaml   # a single flow</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e43d3d3623f75637ea306f40e49b2e2/href">https://medium.com/media/3e43d3d3623f75637ea306f40e49b2e2/href</a></iframe><p>The folder contract the skill maintains — flows that stay green get <strong>promoted</strong> from smoke/ to regression/, and the regression set only ever grows:</p><pre>maestro/<br>├── flows/<br>│   ├── core/         bootstrap + goto_* sub-flows<br>│   ├── smoke/        [smoke]       the critical path — always green<br>│   ├── regression/   [regression]  promoted, stable — only grows<br>│   └── bugs/         [bug]         reproductions, kept until fixed<br>├── reports/          screenshots, JUnit, run notes<br>└── run.sh</pre><p><strong>Three things to change:</strong> the appId, the text anchors (mine are Turkish, pulled from assets/translations/tr.json), and the path to your accessibility-id registry. The phases, the rules and the folder contract transfer as is.</p><p><strong>Repo:</strong> <a href="https://github.com/VB-CORE/life_client/tree/release/v2/1.0.0_1/.claude/skills/hata-maestro-auto">the skill</a> · <a href="https://github.com/VB-CORE/life_client/blob/release/v2/1.0.0_1/.claude/skills/hata-maestro-auto/SKILL.md">SKILL.md</a> · <a href="https://github.com/VB-CORE/life_client/tree/release/v2/1.0.0_1/maestro">the flows</a></p><h3>The MCP servers in my setup</h3><p>Only the first was needed here, but for the curious:</p><ul><li><a href="https://docs.maestro.dev/"><strong>Maestro</strong></a> — drives the device: inspect, tap, screenshot, run flows.</li><li><strong>codebase-memory-mcp</strong> — code knowledge graph: call chains, impact analysis.</li><li><a href="https://github.com/thedotmack/claude-mem"><strong>claude-mem</strong></a> — persistent memory across sessions.</li><li><strong>Figma</strong> — design → code.</li></ul><h3>What’s next</h3><p>The suite covers the critical path. Next, in order: <strong>close the needs-id list</strong> — three coordinate taps today, plus roughly ten more controls with no selector at all (the filter button, the AppBar icons, the ⋮ menu, the FAB dial). Then <strong>home search and filter</strong>, the two highest-traffic interactions in the app and still uncovered. Then <strong>the three request forms</strong>: fill them, assert validation, go back without submitting — which really needs a separate Firebase test project. Then <strong>settings</strong>, because switching TR → EN invalidates every text anchor in the suite, which is exactly why it’s worth testing. Then <strong>CI + Android</strong>, where resource-id is the other side of the same Semantics(identifier:) coin.</p><p>The pattern I’d suggest: cover the critical path first with hard, data-independent assertions, then expand into the surfaces where regressions actually cost you — and let the needs-id list drive your accessibility work as a side effect. <strong>Better test selectors and better VoiceOver support are literally the same task.</strong></p><h3>Takeaways</h3><p>Beyond the eight rules above, the things that cost me real time:</p><ul><li><strong>iOS merges sibling text into one accessibility node.</strong> A place detail’s whole description block arrives as a single node, so assertVisible: &quot;İşletme Açıklaması&quot; finds nothing — you need &#39;[\s\S]*İşletme Açıklaması[\s\S]*&#39;.</li><li><strong>selected: is a selector, not just an attribute.</strong> On a screen with literally no text — the Memories tab is a photo grid and two icon FABs — assertVisible: { id: &quot;memoriesTab&quot;, selected: true } was the <em>only</em> assertion available. Bonus: it gives you the &quot;exactly one tab selected&quot; invariant for free.</li><li><strong>point: percentages must be integers.</strong> &quot;89%,13.4%&quot; throws For input string: &quot;13.4&quot; — reads like a Maestro bug, isn&#39;t.</li><li><strong>Screenshot every state.</strong> The exploration contact sheet turned out to be as useful as the tests.</li><li><strong>Instructions are the reusable asset.</strong> 624 lines of skill outlived the 444 lines of YAML it produced. The YAML is regenerable; the judgement isn’t.</li></ul><p>Plausible-looking YAML has been cheap for a while, and it’s worth very little. What changed is that the agent could <strong>check</strong> — tap, look, re-read the tree, and find out it was wrong in seconds instead of at code review.</p><p>The other half is the constraint: the most valuable rules in that skill are all prohibitions. Tools made the agent capable; the rules made the output trustworthy. Ship either one without the other and you get a suite that’s green and useless.</p><p>The generated tests will rot. The skill won’t.</p><p><a href="https://github.com/VB-CORE/hatayi_yasat">GitHub - VB-CORE/hatayi_yasat: 6 Şubat depreminin Hatay&#39;da ki yaralarını sarmak için tasarlayıp, geliştirdiğimiz mobil uygulamamız AppStore ve Google Play mağazalarında yayında!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9cdf68bac8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/autonomous-flutter-ui-testing-claude-code-maestro-mcp-on-a-real-live-app-d9cdf68bac8d">Autonomous Flutter UI Testing: Claude Code + Maestro MCP on a Real, Live App</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Testable Network Layer and Three-Tier State Management in Flutter]]></title>
            <link>https://medium.com/flutter-community/building-a-testable-network-layer-and-three-tier-state-management-in-flutter-bebdd831cf25?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebdd831cf25</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[masterclass]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 09:07:14 GMT</pubDate>
            <atom:updated>2026-07-08T15:56:50.882Z</atom:updated>
            <content:encoded><![CDATA[<p>How to wrap HTTP behind a generic, testable network manager with sealed results — then drive your screens with a three-tier state model: global Cubit, page Cubit, and widget-local ValueNotifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Kko0J125ig0Uq3nfD040A.png" /></figure><h3>Flutter Refactoring Masterclass — Part 3</h3><p><a href="https://github.com/VB10/flight_booking">GitHub - VB10/flight_booking: Flight App for refactoring real project</a></p><blockquote><strong><em>PRs:</em></strong><em> </em><a href="https://github.com/VB10/flight_booking/pull/11"><em>#11</em></a><em>, </em><a href="https://github.com/VB10/flight_booking/pull/12"><em>#12</em></a></blockquote><p>📺 <strong>Video Series:</strong></p><p><strong>Network &amp; Service Layer</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYvZtk_6mV2s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYvZtk_6mV2s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYvZtk_6mV2s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d40d555e4d8968f1d15fb35e2e91553/href">https://medium.com/media/2d40d555e4d8968f1d15fb35e2e91553/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP5hpxaFRJNw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP5hpxaFRJNw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP5hpxaFRJNw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8a8a32a77c98177ba10492a892aed6/href">https://medium.com/media/3d8a8a32a77c98177ba10492a892aed6/href</a></iframe><p>🤖 <em>Want to apply these changes to your project? See the </em><a href="#-apply-this-to-your-project"><em>AI prompt</em></a><em> at the end.</em></p><h3>The Problem</h3><p>In Part 2 we split the login page into View, ViewModel, and Mixin — but the ViewModel still new&#39;d up a Dio() instance and hard-coded http://localhost:8080 inline. Every screen that talked to the backend did the same thing: create a fresh Dio, paste the base URL, decode JSON by hand, and copy-paste the same if (statusCode == 200) … else … catch (e) ladder.</p><p>That pattern rots fast. A URL change means a project-wide search. A new header (auth token, API version) has to be added everywhere. Error handling drifts — one screen returns &#39;Server hatası&#39;, another swallows the exception. And nothing is testable, because the network call is welded to the widget. As the video puts it: <em>the person writing the code shouldn&#39;t be able to say &quot;this only works with internet&quot; — the network is a dependency, and dependencies must be managed.</em></p><p>There’s a second rot: <strong>state</strong>. setState rebuilds the whole widget on every field change. A page with a loading flag, an error string, and a list re-renders all three even when only one changed. And there&#39;s no consistent home for &quot;where does the loading state live&quot; — sometimes a ValueNotifier, sometimes a bool, sometimes buried in _PageState.</p><p>This article fixes both on the same module. PR #11 builds a <strong>generic network + service + model layer</strong>. PR #12 layers a <strong>three-tier state model</strong> on top — Cubit for business, BlocSelector for surgical rebuilds, ValueNotifier for widget-local UI.</p><h3>What We Changed</h3><p><strong>Network &amp; Service Layer (PR #11):</strong></p><ul><li>lib/product/network/network_manager.dart — IProductNetworkManager interface</li><li>lib/product/network/product_network_manager.dart — Vexana-backed singleton implementation</li><li>lib/product/network/network_constants.dart — base URL, timeouts, endpoint paths</li><li>lib/product/network/error_model.dart — global ProductErrorModel + error codes</li><li>lib/product/service/flight_service.dart + impl/flight_service_impl.dart — abstract service + implementation</li><li>lib/product/service/auth_service.dart + impl/auth_service_impl.dart — same for auth</li><li>lib/feature/**/*_response_model.dart — models migrated to json_serializable + Equatable</li><li>build.yaml — scoped code generation</li><li>test/product/service/*_test.dart — service integration tests</li></ul><p><strong>State Management (PR #12):</strong></p><ul><li>lib/product/container/product_container.dart — GetIt DI container</li><li>lib/product/application/application_cubit.dart + application_state.dart — global app Cubit (theme)</li><li>lib/feature/**/cubit/*_cubit.dart + *_state.dart — page-level Cubits</li><li>lib/feature/unauth/login/login_page.dart — BlocProvider + BlocListener wiring</li><li>lib/feature/unauth/login/view/widget/login_page_body.dart — BlocSelector + local ValueNotifiers</li></ul><h3>Part A — The Network &amp; Service Layer</h3><h3>1. One Interface, Not Ten Dio Instances</h3><p>Every network call funnels through a single interface. The interface is the contract; the concrete class is swappable — which is exactly what makes it testable.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/product/network/network_manager.dart<br>/// Abstract interface for network operations.<br>/// This allows for easy testing and mocking.<br>abstract interface class IProductNetworkManager {<br>  /// Send a network request using the sealed NetworkResult pattern.<br>  Future&lt;NetworkResult&lt;R, ProductErrorModel&gt;&gt; sendRequest&lt;<br>      T extends INetworkModel&lt;T&gt;, R&gt;(<br>    String path, {<br>    required T parseModel,<br>    required RequestType method,<br>    dynamic body,<br>  });<br><br>void setAuthToken(String token);   // call once after login<br>  void clearAuthToken();             // call on logout<br>  bool get isAuthenticated;<br>  void addBaseHeader(MapEntry&lt;String, String&gt; header);<br>  void removeHeader(String key);<br>  void clearHeaders();<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> The generic bounds do the heavy lifting. </em><em>T extends INetworkModel&lt;T&gt; guarantees every model has </em><em>fromJson/</em><em>toJson, so parsing is never hand-rolled. </em><em>setAuthToken is called </em><strong><em>once</em></strong><em> — the token lives on the manager, and every later request inherits it. No more pasting headers per call.</em></blockquote><h3>2. The Concrete Manager: A Configured Singleton</h3><p>The implementation wraps <a href="https://pub.dev/packages/vexana">Vexana</a> (a Dio-based strategy-pattern network layer). The key move: <strong>the error model is set once, at construction.</strong> Every failed request comes back already typed as ProductErrorModel.</p><p><strong>Before:</strong></p><pre>// ❌ Before — a fresh Dio in every method<br>void fetchFlights() async {<br>  Dio dio = Dio();                          // new instance every call<br>  String baseUrl = &#39;http://localhost:8080&#39;; // hard-coded, repeated<br>  Response response = await dio.get(&#39;$baseUrl/flights&#39;);<br>  if (response.statusCode == 200) {<br>    final json = jsonDecode(response.data);<br>    // ...manual parsing, manual status checks, manual catch<br>  }<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — lib/product/network/product_network_manager.dart<br>final class ProductNetworkManager implements IProductNetworkManager {<br>  ProductNetworkManager._({String? baseUrl})<br>      : _networkManager = NetworkManager&lt;ProductErrorModel&gt;(<br>          isEnableLogger: true,<br>          errorModel: const ProductErrorModel(), // typed errors, set once<br>          options: BaseOptions(<br>            baseUrl: baseUrl ?? NetworkConstants.baseUrl,<br>            connectTimeout: NetworkConstants.connectTimeout,<br>            receiveTimeout: NetworkConstants.receiveTimeout,<br>            sendTimeout: NetworkConstants.sendTimeout,<br>            headers: {<br>              &#39;Content-Type&#39;: &#39;application/json&#39;,<br>              &#39;Accept&#39;: &#39;application/json&#39;,<br>            },<br>          ),<br>        );<br>  static ProductNetworkManager? _instance;<br>  static ProductNetworkManager get instance =&gt;<br>      _instance ??= ProductNetworkManager._();<br>/// Call in main.dart before runApp() to point at a different environment.<br>  static void setup({String? baseUrl}) =&gt;<br>      _instance = ProductNetworkManager._(baseUrl: baseUrl);<br>/// Reset for tests.<br>  static void reset() =&gt; _instance = null;<br>  @override<br>  void setAuthToken(String token) {<br>    _networkManager.addBaseHeader(<br>      MapEntry(HttpHeaders.authorizationHeader, &#39;Bearer $token&#39;),<br>    );<br>  }<br>  // ...clearAuthToken, isAuthenticated, header helpers<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>setup() swaps the base URL for staging/prod without touching a single call site. </em><em>reset() gives tests a clean slate. And because </em><em>errorModel is fixed at construction, the </em><em>onError branch downstream receives a real </em><em>ProductErrorModel — not </em><em>dynamic, not a raw </em><em>DioException.</em></blockquote><h3>3. Endpoints and Errors as Constants</h3><p>No magic strings. Paths, timeouts, and error codes live in one file each.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/product/network/network_constants.dart<br>final class NetworkConstants {<br>  const NetworkConstants._();<br>  static const String baseUrl = &#39;http://localhost:8080&#39;;<br>  static const Duration connectTimeout = Duration(seconds: 30);<br>  static const Duration receiveTimeout = Duration(seconds: 30);<br>  static const Duration sendTimeout = Duration(seconds: 30);<br>}<br><br>final class NetworkPaths {<br>  const NetworkPaths._();<br>  static const String login = &#39;/login&#39;;<br>  static const String flights = &#39;/flights&#39;;<br>  static const String checkout = &#39;/checkout&#39;;<br>  static const String profile = &#39;/profile&#39;;<br>}</pre><p>The global error model mirrors the backend’s error shape exactly, so it deserializes in one shot:</p><pre>// ✅ After — lib/product/network/error_model.dart<br>@JsonSerializable()<br>final class ProductErrorModel extends Equatable<br>    implements INetworkModel&lt;ProductErrorModel&gt; {<br>  const ProductErrorModel({<br>    this.success = false,<br>    this.message,<br>    this.errorCode,<br>    this.details,<br>  });<br><br>factory ProductErrorModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$ProductErrorModelFromJson(json);<br>  @JsonKey(defaultValue: false)<br>  final bool success;<br>  final String? message;<br>  final String? errorCode;<br>  final Map&lt;String, dynamic&gt;? details;<br>  @override<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$ProductErrorModelToJson(this);<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [success, message, errorCode, details];<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> A structured backend always returns errors in one shape (</em><em>success, </em><em>message, </em><em>errorCode, </em><em>details). Model it once, and every error handler in the app reads </em><em>error.model.errorCode with full type safety.</em></blockquote><h3>4. Models: Generated, Not Hand-Written</h3><p>The old models had 40 lines of manual fromJson loops per class. json_serializable + Equatable replaces all of it. The one rule the video stresses: <strong>every model must implement </strong>INetworkModel so the network manager can trust its toJson/fromJson.</p><p><strong>Before:</strong></p><pre>// ❌ Before — flights_response_model.dart (hand-rolled)<br>class FlightsResponseModel {<br>  bool success;<br>  List&lt;FlightModel&gt; data;<br>  String message;<br><br>factory FlightsResponseModel.fromJson(Map&lt;String, dynamic&gt; json) {<br>    List&lt;FlightModel&gt; flightList = [];<br>    if (json[&#39;data&#39;] != null) {<br>      for (var item in json[&#39;data&#39;] as List&lt;dynamic&gt;) {<br>        flightList.add(FlightModel.fromJson(item)); // manual loop<br>      }<br>    }<br>    return FlightsResponseModel(<br>      success: json[&#39;success&#39;] ?? false,<br>      data: flightList,<br>      message: json[&#39;message&#39;] ?? &#39;&#39;,<br>    );<br>  }<br>  // ...plus a hand-written toJson<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — flights_response_model.dart (generated)<br>@JsonSerializable()<br>final class FlightsResponseModel extends Equatable<br>    implements INetworkModel&lt;FlightsResponseModel&gt; {<br>  const FlightsResponseModel({<br>    required this.success,<br>    required this.data,<br>    required this.message,<br>  });<br>factory FlightsResponseModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$FlightsResponseModelFromJson(json);<br>final bool success;<br>  final List&lt;FlightModel&gt; data;<br>  final String message;<br>  @override<br>  FlightsResponseModel fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      FlightsResponseModel.fromJson(json);<br>  @override<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$FlightsResponseModelToJson(this);<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [success, data, message];<br>}</pre><p>Code generation is <strong>scoped</strong> so build_runner doesn&#39;t crawl the entire project:</p><pre># ✅ After — build.yaml<br>targets:<br>  $default:<br>    builders:<br>      json_serializable:<br>        generate_for:<br>          include:<br>            - lib/feature/**/model/*.dart<br>            - lib/feature/**/*_response_model.dart<br>            - lib/product/network/error_model.dart<br>        options:<br>          explicit_to_json: true<br>          include_if_null: false</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>const constructors + immutable </em><em>final fields + </em><em>Equatable give you free value comparison (crucial for state, next section). Scoping </em><em>generate_for is a real performance win on large projects — the generator only touches files that match, instead of scanning everything.</em></blockquote><h3>5. Abstract Services with Injected Managers</h3><p>Business code never talks to the network manager directly — it talks to a service. And every service is <strong>an interface first</strong>, so you can swap the real implementation for a fake in tests.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/product/service/flight_service.dart<br>abstract interface class IFlightService {<br>  Future&lt;NetworkResult&lt;FlightsResponseModel, ProductErrorModel&gt;&gt; getFlights();<br>  Future&lt;NetworkResult&lt;CheckoutResponseModel, ProductErrorModel&gt;&gt; checkout({<br>    required List&lt;FlightModel&gt; cartItems,<br>    required String userEmail,<br>  });<br>}<br><br>// ✅ After - lib/product/service/impl/flight_service_impl.dart<br>final class FlightServiceImpl implements IFlightService {<br>  FlightServiceImpl([IProductNetworkManager? networkManager])<br>      : _networkManager = networkManager ?? ProductNetworkManager.instance;<br>final IProductNetworkManager _networkManager;<br>  @override<br>  Future&lt;NetworkResult&lt;FlightsResponseModel, ProductErrorModel&gt;&gt; getFlights() {<br>    return _networkManager<br>        .sendRequest&lt;FlightsResponseModel, FlightsResponseModel&gt;(<br>      NetworkPaths.flights,<br>      parseModel: const FlightsResponseModel(<br>        success: false,<br>        data: [],<br>        message: &#39;&#39;,<br>      ),<br>      method: RequestType.GET,<br>    );<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> Note the constructor: </em><em>[IProductNetworkManager? networkManager]. Pass a </em><strong><em>test</em></strong><em> manager in unit tests; pass nothing in production and it defaults to the global singleton. This is dependency injection with zero ceremony — and it&#39;s why the services stay out of the container as </em>concrete<em> types (they&#39;re registered by their interface, more on that in Part B).</em></blockquote><h3>6. The Call Site: fold Instead of try/catch</h3><p>Here’s the payoff. The flight page’s fetch drops from a 30-line try/catch ladder to a sealed result you fold over.</p><p><strong>Before:</strong></p><pre>// ❌ Before — flight_list_page.dart<br>void fetchFlights() async {<br>  setState(() { isLoading = true; errorMessage = &#39;&#39;; });<br>  Dio dio = Dio();<br>  String baseUrl = &#39;http://localhost:8080&#39;;<br>  try {<br>    Response response = await dio.get(&#39;$baseUrl/flights&#39;);<br>    if (response.statusCode == 200) {<br>      final json = jsonDecode(response.data);<br>      final flightsResponse = FlightsResponseModel.fromJson(json);<br>      if (flightsResponse.success) {<br>        setState(() { flights = flightsResponse.data; isLoading = false; });<br>      } else {<br>        setState(() { isLoading = false; errorMessage = flightsResponse.message; });<br>      }<br>    } else {<br>      setState(() { isLoading = false; errorMessage = &#39;Server hatası&#39;; });<br>    }<br>  } catch (e) {<br>    setState(() { isLoading = false; errorMessage = &#39;Bağlantı hatası: $e&#39;; });<br>  }<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — flight_list_page.dart<br>final result = await FlightServiceImpl().getFlights();<br>result.fold(<br>  onSuccess: (response) {<br>    if (response.success) {<br>      setState(() { flights = response.data; isLoading = false; });<br>    } else {<br>      setState(() { isLoading = false; errorMessage = response.message; });<br>    }<br>  },<br>  onError: (error) {<br>    setState(() {<br>      isLoading = false;<br>      errorMessage = error.description ?? &#39;Bağlantı hatası&#39;;<br>    });<br>  },<br>);</pre><blockquote><strong><em>Why this matters:</em></strong><em> A </em><em>NetworkResult is a </em>sealed<em> type — it&#39;s </em><em>onSuccess </em><strong><em>or</em></strong><em> </em><em>onError, never both, never null. The compiler forces you to handle both branches, and </em><em>onError hands you a typed </em><em>ProductErrorModel. This is the exact seam that makes Part B&#39;s Cubit clean.</em></blockquote><p>Because services are interfaces, the integration test just points the manager at localhost and asserts on the folded result:</p><pre>// ✅ After — test/product/service/flight_service_test.dart<br>setUpAll(() {<br>  ProductNetworkManager.reset();<br>  ProductNetworkManager.setup(baseUrl: &#39;http://localhost:8080&#39;);<br>  flightService = FlightServiceImpl();<br>});<br><br>test(&#39;getFlights should return flight list&#39;, () async {<br>  final result = await flightService.getFlights();<br>  result.fold(<br>    onSuccess: (response) {<br>      expect(response.success, isTrue);<br>      expect(response.data, isNotEmpty);<br>    },<br>    onError: (error) =&gt; fail(&#39;Expected success: ${error.description}&#39;),<br>  );<br>});</pre><h3>Part B — Three-Tier State Management</h3><p>The video’s core message: <strong>state management is an approach, not a package.</strong> Don’t let the library get in front of your architecture. Whether you use Riverpod or Bloc, the discipline is what matters. This project uses flutter_bloc&#39;s <strong>Cubit</strong> — but the three-tier model applies anywhere.</p><p>The three tiers:</p><ul><li><strong>Global</strong> — lives across the whole app, a Cubit held in the DI container. Example: theme, localization, user session.</li><li><strong>Page</strong> — lives on one screen, a page Cubit + State. Example: login flow, flight list.</li><li><strong>Widget-local</strong> — lives inside one widget, a ValueNotifier. Example: password visibility, expand toggle.</li></ul><h3>7. The DI Container: One Box, Registered by Interface</h3><p>Global objects go in a GetIt container, registered <strong>by their interface</strong>. This is where the “inject a fake in tests” promise from Part A is cashed in.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/product/container/product_container.dart<br>final class ProductContainer {<br>  ProductContainer._();<br>  static final ProductContainer instance = ProductContainer._();<br><br>final GetIt _getIt = GetIt.instance;<br>  T get&lt;T extends Object&gt;() =&gt; _getIt&lt;T&gt;();<br>  void setup() {<br>    if (_getIt.isRegistered&lt;IProductNetworkManager&gt;()) return;<br>    _getIt<br>      ..registerLazySingleton&lt;IProductNetworkManager&gt;(<br>        () =&gt; ProductNetworkManager.instance,<br>      )<br>      ..registerLazySingleton&lt;IAuthService&gt;(<br>        () =&gt; AuthServiceImpl(_getIt&lt;IProductNetworkManager&gt;()),<br>      )<br>      ..registerLazySingleton&lt;IFlightService&gt;(<br>        () =&gt; FlightServiceImpl(_getIt&lt;IProductNetworkManager&gt;()),<br>      )<br>      ..registerLazySingleton&lt;ApplicationCubit&gt;(ApplicationCubit.new);<br>  }<br>}</pre><p>Wired once, before runApp:</p><pre>// ✅ After — lib/main.dart<br>void main() async {<br>  AppInitializer.run();<br>  await AppInitializer().prepare();<br>  ProductContainer.instance.setup();<br>  runApp(const MainApp());<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> Register the </em>interface<em> → </em><em>IAuthService, not </em><em>AuthServiceImpl. The whole app depends on the abstraction. Change one line in the container and every consumer gets the new implementation. </em><em>registerLazySingleton means the object is built on first use, not at startup.</em></blockquote><h3>8. Global State: One Cubit for the Whole App</h3><p>Theme is app-wide — flip it on the login screen, every page reacts. That’s a job for a global Cubit provided at the root and consumed with a BlocSelector.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/product/application/application_cubit.dart<br>final class ApplicationCubit extends Cubit&lt;ApplicationState&gt; {<br>  ApplicationCubit() : super(const ApplicationState(themeMode: ThemeMode.light));<br><br>void toggleTheme() {<br>    final next = state.themeMode == ThemeMode.light<br>        ? ThemeMode.dark<br>        : ThemeMode.light;<br>    emit(state.copyWith(themeMode: next));<br>  }<br>}<br><br>// ✅ After - lib/feature/sub_feature/main/main_app.dart<br>return MultiBlocProvider(<br>  providers: [<br>    BlocProvider(<br>      create: (_) =&gt; ProductContainer.instance.get&lt;ApplicationCubit&gt;(),<br>    ),<br>  ],<br>  child: BlocSelector&lt;ApplicationCubit, ApplicationState, ThemeMode&gt;(<br>    selector: (state) =&gt; state.themeMode,<br>    builder: (context, themeMode) {<br>      return MaterialApp(<br>        theme: AppTheme.lightTheme,<br>        darkTheme: AppTheme.darkTheme,<br>        themeMode: themeMode,<br>        home: SplashPage(),<br>      );<br>    },<br>  ),<br>);</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>BlocSelector&lt;…, ThemeMode&gt; rebuilds </em><em>MaterialApp </em><strong><em>only</em></strong><em> when </em><em>themeMode changes — not when any other global field mutates. Provide global Cubits at the app root and every subtree can reach them with </em><em>context.read&lt;ApplicationCubit&gt;().</em></blockquote><h3>9. Page State: Cubit is the Business Layer</h3><p>Part 2’s LoginViewModel becomes a LoginCubit. The rename isn&#39;t cosmetic — the Cubit now <strong>owns the state</strong> and emits it, instead of returning values the widget has to juggle.</p><p><strong>Before:</strong></p><pre>// ❌ Before — login_view_model.dart returns a value, widget manages state<br>Future&lt;LoginResponseModel&gt; login({required String email, required String password}) async {<br>  final result = await _authService.login(email: email, password: password);<br>  LoginResponseModel? response;<br>  String? errorMessage;<br>  result.fold(<br>    onSuccess: (data) { response = data; },<br>    onError: (error) { errorMessage = error.model?.message ?? &#39;Giriş başarısız&#39;; },<br>  );<br>  if (response != null) return response!;<br>  throw Exception(errorMessage); // widget has to try/catch this<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — lib/feature/unauth/login/cubit/login_cubit.dart<br>final class LoginCubit extends Cubit&lt;LoginState&gt; {<br>  LoginCubit(this._authService, this._networkManager) : super(const LoginState());<br><br>final IAuthService _authService;<br>  final IProductNetworkManager _networkManager;<br>  Future&lt;void&gt; login({required String email, required String password}) async {<br>    emit(state.copyWith(isLoading: true, errorMessage: &#39;&#39;, isSuccess: false));<br>    final result = await _authService.login(email: email, password: password);<br>    LoginResponseModel? successResponse;<br>    String? failureMessage;<br>    result.fold(<br>      onSuccess: (data) {<br>        if (data.success) {<br>          _networkManager.setAuthToken(data.token); // token set once, here<br>          successResponse = data;<br>        } else {<br>          failureMessage = data.message;<br>        }<br>      },<br>      onError: (error) {<br>        failureMessage = error.model?.message ?? error.description ?? &#39;Giriş başarısız&#39;;<br>      },<br>    );<br>    if (successResponse != null) {<br>      await _saveUserToCache(successResponse!);<br>      await _logSuccessfulLogin(successResponse!);<br>      emit(state.copyWith(isLoading: false, isSuccess: true));<br>    } else {<br>      emit(state.copyWith(isLoading: false, errorMessage: failureMessage ?? &#39;Giriş başarısız&#39;));<br>    }<br>  }<br>}</pre><p>The state is immutable, comparable, copyWith-friendly:</p><pre>// ✅ After — lib/feature/unauth/login/cubit/login_state.dart<br>@immutable<br>final class LoginState extends Equatable {<br>  const LoginState({<br>    this.isLoading = false,<br>    this.errorMessage = &#39;&#39;,<br>    this.isSuccess = false,<br>  });<br><br>final bool isLoading;<br>  final String errorMessage;<br>  final bool isSuccess;<br>  LoginState copyWith({bool? isLoading, String? errorMessage, bool? isSuccess}) {<br>    return LoginState(<br>      isLoading: isLoading ?? this.isLoading,<br>      errorMessage: errorMessage ?? this.errorMessage,<br>      isSuccess: isSuccess ?? this.isSuccess,<br>    );<br>  }<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [isLoading, errorMessage, isSuccess];<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> The Cubit is a </em><strong><em>business manager</em></strong><em> — “logging in is a business operation.” It never holds view objects (no </em><em>BuildContext, no </em><em>Navigator). It just emits state. Notice </em><em>isSuccess is state, not a callback — navigation reacts to it in the next section.</em></blockquote><h3>10. Wiring: BlocListener for Side Effects</h3><p>The Cubit is provided at the page root. Navigation is a <em>side effect</em> of isSuccess flipping true — and side effects belong in a BlocListener, never in a builder.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/feature/unauth/login/login_page.dart<br>return BlocProvider(<br>  create: (_) =&gt; loginCubit,<br>  child: BlocListener&lt;LoginCubit, LoginState&gt;(<br>    listenWhen: (previous, current) =&gt; current.isSuccess &amp;&amp; !previous.isSuccess,<br>    listener: (context, state) {<br>      if (state.isSuccess) navigateToFlightList();<br>    },<br>    child: Scaffold(<br>      body: _LoginPageBody(<br>        emailController: emailController,<br>        passwordController: passwordController,<br>        onLogin: () =&gt; onLoginPressed(context),<br>      ),<br>    ),<br>  ),<br>);</pre><p>The mixin now just builds the Cubit (from the container) and fires the action — no more setState, no more manual state juggling:</p><pre>// ✅ After — lib/feature/unauth/login/view/login_page_mixin.dart<br>mixin LoginPageMixin on State&lt;LoginPage&gt; {<br>  late final TextEditingController emailController;<br>  late final TextEditingController passwordController;<br><br>late final LoginCubit loginCubit = LoginCubit(<br>    ProductContainer.instance.get&lt;IAuthService&gt;(),<br>    ProductContainer.instance.get&lt;IProductNetworkManager&gt;(),<br>  );<br>  void navigateToFlightList() {<br>    Navigator.pushReplacement&lt;void, void&gt;(<br>      context,<br>      MaterialPageRoute&lt;void&gt;(builder: (_) =&gt; const FlightListPage()),<br>    );<br>  }<br>  void onLoginPressed(BuildContext context) {<br>    unawaited(loginCubit.login(<br>      email: emailController.text,<br>      password: passwordController.text,<br>    ));<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>listenWhen fires the listener </em><strong><em>only</em></strong><em> on the </em><em>false → true transition, so navigation runs exactly once. Business (Cubit) and view (Navigator) stay separated: the Cubit reports &quot;success,&quot; the listener decides &quot;navigate.&quot;</em></blockquote><h3>11. Surgical Rebuilds: BlocSelector per Field</h3><p>Here’s where immutable state pays off. Instead of one BlocBuilder rebuilding the whole page, each widget subscribes to <strong>only the field it cares about</strong> with a BlocSelector. The error text listens to errorMessage; the button listens to isLoading. Neither rebuilds when the other changes.</p><p><strong>After:</strong></p><pre>// ✅ After — login_page_body.dart — error text listens to errorMessage only<br>final class _LoginErrorText extends StatelessWidget {<br>  const _LoginErrorText();<br><br>@override<br>  Widget build(BuildContext context) {<br>    return BlocSelector&lt;LoginCubit, LoginState, String&gt;(<br>      selector: (state) =&gt; state.errorMessage,<br>      builder: (context, errorMessage) {<br>        if (errorMessage.isEmpty) return const SizedBox.shrink();<br>        return ProductText.bodySmall(context, errorMessage,<br>            color: context.colorScheme.error);<br>      },<br>    );<br>  }<br>}<br>// ✅ Button listens to isLoading only<br>final class _LoginButton extends StatelessWidget {<br>  const _LoginButton({required this.onPressed});<br>  final VoidCallback onPressed;<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocSelector&lt;LoginCubit, LoginState, bool&gt;(<br>      selector: (state) =&gt; state.isLoading,<br>      // builder: shows spinner when true, ElevatedButton otherwise<br>    );<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> As the video says — </em>“as long as nobody emits a change to <em>isLoading</em>, this widget never re-renders.&quot;<em> Because </em><em>LoginState is </em><em>Equatable, the selector compares by value and skips rebuilds when the selected field is unchanged. The widget also stops needing props passed down from the parent; it reads its slice of state directly.</em></blockquote><h3>12. Widget-Local State: ValueNotifier, No setState</h3><p>The bottom tier: purely visual toggles that no business logic and no page state should ever know about — password visibility, “show test account” expand. These get their own ValueNotifier, scoped to the widget.</p><p><strong>After:</strong></p><pre>// ✅ After — password field owns its own obscure toggle<br>class _LoginPasswordFieldState extends State&lt;_LoginPasswordField&gt; {<br>  late final ValueNotifier&lt;bool&gt; obscureNotifier;<br><br>@override<br>  void initState() {<br>    super.initState();<br>    obscureNotifier = ValueNotifier(true);<br>  }<br>  @override<br>  void dispose() {<br>    obscureNotifier.dispose();<br>    super.dispose();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return ValueListenableBuilder&lt;bool&gt;(<br>      valueListenable: obscureNotifier,<br>      builder: (context, obscure, _) {<br>        return TextField(<br>          controller: widget.controller,<br>          obscureText: obscure,<br>          // suffix icon toggles obscureNotifier.value<br>        );<br>      },<br>    );<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> Password visibility is </em>nobody’s<em> business but this text field’s. Putting it in the Cubit would pollute business state and trigger page-wide rebuilds. A local </em><em>ValueNotifier keeps the rebuild scoped to the one widget. Tip from the video: give the notifier a descriptive name (</em><em>obscureNotifier, </em><em>expandedNotifier) — a bare </em><em>ValueNotifier&lt;bool&gt; tells the reader nothing.</em></blockquote><h3>Key Takeaways</h3><ol><li><strong>Network is a dependency — manage it centrally.</strong> One IProductNetworkManager, one base URL, one place for auth headers. setAuthToken is called exactly once.</li><li>sealed<strong> results beat try/catch.</strong> NetworkResult.fold(onSuccess, onError) forces both branches and hands you a <em>typed</em> error, not a dynamic.</li><li><strong>Every model implements </strong>INetworkModel<strong> + is generated.</strong> json_serializable + Equatable kills hand-written parsing and gives you value equality for free. Scope build.yaml so generation is fast.</li><li><strong>Services are interfaces; managers are injected.</strong> FlightServiceImpl([manager]) defaults to the singleton in prod, accepts a fake in tests. Register by interface in the container.</li><li><strong>State has three tiers.</strong> Global (Cubit in DI) → Page (Cubit + State) → Widget-local (ValueNotifier). Match the tier to the scope of the change.</li><li><strong>Cubit is business; the View is view.</strong> No BuildContext in the Cubit. Emit isSuccess; let a BlocListener handle navigation.</li><li>BlocSelector<strong> per field, not </strong>BlocBuilder<strong> per page.</strong> Immutable Equatable state means each widget rebuilds only when <em>its</em> slice changes.</li><li><strong>State management is an approach, not a package.</strong> The three-tier discipline outlives whatever library you pick.</li></ol><h3>What’s Next</h3><p>In <strong>Part 4</strong>, we’ll wire up <strong>navigation with </strong>go_router — typed routes, auth guards that react to the session Cubit we just built, and a GoRouterRefreshStream that redirects on 401. The isSuccess flag from LoginCubit becomes a router redirect instead of a manual Navigator.pushReplacement.</p><p><em>This article is part of the </em><strong><em>Flutter Refactoring Masterclass</em></strong><em> series, where we transform a messy real-world project into production-ready code, one PR at a time.</em></p><h3>📺 Watch the Full Series</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La%26si%3D7W1cepc3u1v3wdX0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkaqIas6nXZc%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLBoqyP9P4JS_VLHi4U4DrczN8t1gA%26days_since_epoch%3D20636&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed2775283a60c45c9033356cdb000b4/href">https://medium.com/media/4ed2775283a60c45c9033356cdb000b4/href</a></iframe><h3>🤖 Apply This to Your Project</h3><p>Use this prompt with Claude or your AI assistant:</p><pre>Refactor my Flutter project&#39;s networking and state management into a<br>layered, testable architecture.<br>Network layer (lib/product/network/):<br>1. Create IProductNetworkManager (abstract interface) with a generic<br>   sendRequest&lt;T extends INetworkModel&lt;T&gt;, R&gt;() returning a sealed<br>   NetworkResult&lt;R, ProductErrorModel&gt;, plus setAuthToken / clearAuthToken /<br>   header helpers.<br>2. Implement it as a singleton (Vexana or Dio) that sets the error model ONCE<br>   at construction. Add static setup({baseUrl}) and reset() for env + tests.<br>3. Create NetworkConstants (baseUrl, timeouts) and NetworkPaths (endpoints).<br>4. Create a global ProductErrorModel (success, message, errorCode, details)<br>   implementing INetworkModel.<br>Models:<br>5. Convert every response model to @JsonSerializable + Equatable +<br>   INetworkModel&lt;T&gt; with const constructor and final fields. Add a scoped<br>   build.yaml (generate_for include patterns, explicit_to_json: true,<br>   include_if_null: false).<br>Service layer (lib/product/service/):<br>6. For each domain, create an abstract interface (IFlightService) and an<br>   impl that takes an optional IProductNetworkManager (defaulting to the<br>   singleton). Call sites use result.fold(onSuccess:, onError:).<br>DI (lib/product/container/):<br>7. Create a GetIt-based ProductContainer with setup(), registering services<br>   and global cubits BY INTERFACE via registerLazySingleton. Call setup()<br>   in main() before runApp().<br>State management (three tiers):<br>8. Global: an ApplicationCubit for app-wide state (theme). Provide it at the<br>   app root via MultiBlocProvider; consume with BlocSelector.<br>9. Page: a &lt;Feature&gt;Cubit extends Cubit&lt;&lt;Feature&gt;State&gt;. State is @immutable<br>   + Equatable + copyWith. Cubit holds NO BuildContext - it emits state only.<br>   Provide via BlocProvider at the page root. Handle navigation/side-effects<br>   in a BlocListener (use listenWhen for one-shot transitions).<br>10. Widget-local: use a named ValueNotifier + ValueListenableBuilder for<br>    purely visual toggles (obscurePassword, expanded). Never setState.<br>11. Subscribe each widget to only its field with BlocSelector, not one<br>    page-wide BlocBuilder.<br>Show before/after for one screen and list every new file.</pre><p>Or invoke the existing skills directly:</p><pre>/flutter-network-generator   # scaffolds the network + service + model layer<br>/cubit-add lib/feature/&lt;area&gt;/&lt;feature&gt;   # adds Cubit + state + mixin + ValueListenable</pre><p>Also you can find my commands and skills from repository directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BduCnObJ0ykjCNGAaCVgEA.png" /></figure><p><a href="https://github.com/VB10/flight_booking/tree/main/.claude/commands">flight_booking/.claude/commands at main · VB10/flight_booking</a></p><h3>📋 Full Series Roadmap</h3><p>This is Part 3 of a 20-part series. Here’s the complete roadmap:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e922c9e1da1454a09a1642f1cb07711c/href">https://medium.com/media/e922c9e1da1454a09a1642f1cb07711c/href</a></iframe><p><strong>Completed:</strong> v1–v5 (Project Setup), v6 (Theme &amp; Design System), v7 (View-ViewModel-Mixin), v8 (Network &amp; Service Layer), v9 (State Management with Cubit)</p><p><strong>Coming Next:</strong> v10 Navigation with go_router (typed routes + auth guards), plus code generation, caching, and more.</p><p><em>⭐ </em><a href="https://github.com/VB10/flight_booking"><em>github.com/VB10/flight_booking</em></a></p><p><a href="https://github.com/VB10/flight_booking">GitHub - VB10/flight_booking: Flight App for refactoring real project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebdd831cf25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/building-a-testable-network-layer-and-three-tier-state-management-in-flutter-bebdd831cf25">Building a Testable Network Layer and Three-Tier State Management in Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theme System and View-ViewModel-Mixin: Building a Scalable Flutter UI Layer]]></title>
            <link>https://medium.com/flutter-community/theme-system-and-view-viewmodel-mixin-building-a-scalable-flutter-ui-layer-2a19c8885125?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a19c8885125</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Sun, 03 May 2026 12:18:14 GMT</pubDate>
            <atom:updated>2026-05-26T14:39:21.857Z</atom:updated>
            <content:encoded><![CDATA[<p>How to centralize design tokens with ThemeExtension, then split chaotic page widgets into View, ViewModel, and Mixin layers — without any state management library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yELa3SP4lunUG6F8NTdmw.png" /></figure><h3>Flutter Refactoring Masterclass — Part 2</h3><p><a href="https://github.com/VB10/flight_booking">GitHub - VB10/flight_booking: Flight App for refactoring real project</a></p><blockquote><strong><em>PRs:</em></strong><em> </em><a href="https://github.com/VB10/flight_booking/pull/7"><em>#7</em></a><em>, </em><a href="https://github.com/VB10/flight_booking/pull/9"><em>#9</em></a></blockquote><p>📺 <strong>Video Series:</strong> <a href="https://youtu.be/2-Q91EDSiTg">6-Theme &amp; Design System</a> · <a href="https://youtu.be/Uyp0rWupYJc">7.1-View-ViewModel-Mixin</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUyp0rWupYJc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUyp0rWupYJc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUyp0rWupYJc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d88bc7bc6608c8a7a6d3b6f476eb7ef8/href">https://medium.com/media/d88bc7bc6608c8a7a6d3b6f476eb7ef8/href</a></iframe><p>🤖 <em>Want to apply these changes to your project? See the </em><a href="#-apply-this-to-your-project"><em>AI prompt</em></a><em> at the end.</em></p><h3>The Problem</h3><p>Two patterns kill Flutter projects faster than any other: <strong>scattered design tokens</strong> and <strong>god-class widgets</strong>.</p><p>A typical login page accumulates network calls, cache writes, analytics events, controllers, error state, loading flags, and 100 lines of UI — all in one _LoginPageState. Padding values like EdgeInsets.all(20) get sprinkled across files. Hex colors live next to widgets. When the design team renames &quot;primary&quot; to &quot;brand,&quot; you&#39;re searching the entire codebase by hand.</p><p>When a new developer joins the team, they ask “where’s the loading state for login?” and the answer is “scroll to line 137.” When the designer asks for dark mode, you cry.</p><p>This article fixes both problems on the same module — first by establishing a <strong>centralized theme system</strong> (PR #7), then by <strong>splitting the login page</strong> into View, ViewModel, and Mixin layers (PR #9). Same module, two complementary refactors.</p><h3>What We Changed</h3><p><strong>Theme System (PR #7):</strong></p><ul><li>lib/core/theme/app_color_scheme.dart — Material 3 ColorScheme generator from palette</li><li>lib/core/theme/app_colors.dart — Light/dark color palette (single source of truth)</li><li>lib/core/theme/app_theme.dart — Final ThemeData factories (no getters)</li><li>lib/core/theme/app_theme_extension.dart — Custom brand colors via ThemeExtension</li><li>lib/core/theme/app_text_styles.dart — Typography scale (h1, h3, body, caption)</li><li>lib/core/theme/app_page_padding.dart — Const-only spacing primitives</li><li>lib/core/theme/product_text.dart — Reusable text widget bound to theme</li><li>docs/theme.md + .cursor/skills/theme/SKILL.md — Documentation + AI skill</li></ul><p><strong>View Architecture (PR #9):</strong></p><ul><li>lib/feature/unauth/login/login_page.dart — Reduced from 211 → 37 lines</li><li>lib/feature/unauth/login/view/login_page_mixin.dart — Controllers + actions</li><li>lib/feature/unauth/login/view/login_page_state.dart — Immutable state (Equatable)</li><li>lib/feature/unauth/login/view/widget/login_page_body.dart — UI body</li><li>lib/feature/unauth/login/view_model/login_view_model.dart — Business logic</li><li>docs/prompt/view_refactor_prompt.md + .claude/commands/flutter-view-refactor.md — Reusable refactor prompt</li></ul><h3>1. Final ThemeData, Not Getters</h3><p>A theme is built once and lives for the app’s lifetime. Defining it as a getter forces Flutter to recompute the entire ThemeData graph on every read. That&#39;s wasteful and signals the wrong intent.</p><p><strong>Before:</strong></p><pre>// ❌ Before — typical pattern in many projects<br>class AppTheme {<br>  static ThemeData get lightTheme {<br>    return ThemeData(<br>      primarySwatch: Colors.blue,<br>      // ...everything inline, mixed with magic numbers<br>    );<br>  }<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — lib/core/theme/app_theme.dart<br>final class AppTheme {<br>  AppTheme._();<br>   <br>   static ThemeData get lightTheme {<br>    final scheme = AppColorScheme.light;<br>    return ThemeData(<br>      useMaterial3: true,<br>      colorScheme: scheme,<br>      textTheme: AppTextStyles.textTheme.apply(<br>        bodyColor: scheme.onSurface,<br>        displayColor: scheme.onSurface,<br>      ),<br>      fontFamily: &#39;Roboto&#39;,<br>      extensions: &lt;ThemeExtension&lt;dynamic&gt;&gt;[<br>        AppThemeExtension.light,<br>      ],<br>    );<br>  }<br>  static ThemeData get darkTheme { /* mirror of lightTheme */ }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>final class prevents accidental inheritance. The private constructor (</em><em>AppTheme._()) prevents instantiation. The theme delegates to specialized files (</em><em>AppColorScheme, </em><em>AppTextStyles, </em><em>AppThemeExtension) — each one a single concern.</em></blockquote><h3>2. ColorScheme as the Source of Truth</h3><p>Material 3’s ColorScheme already covers 90% of UI use cases. Don&#39;t reinvent it — generate it from your palette.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/core/theme/app_color_scheme.dart<br>final class AppColorScheme {<br>  AppColorScheme._();<br>  static ColorScheme get light {<br>    final palette = AppColors.light;<br>    return ColorScheme(<br>      brightness: Brightness.light,<br>      primary: palette.primary,<br>      onPrimary: palette.onPrimary,<br>      primaryContainer: palette.primaryContainer,<br>      onPrimaryContainer: palette.onPrimaryContainer,<br>      secondary: palette.secondary,<br>      onSecondary: palette.onSecondary,<br>      tertiary: palette.tertiary,<br>      onTertiary: palette.onTertiary,<br>      error: palette.error,<br>      onError: palette.onError,<br>      surface: palette.surface,<br>      onSurface: palette.onSurface,<br>      surfaceContainerHighest: palette.surfaceContainerHighest,<br>      onSurfaceVariant: palette.onSurfaceVariant,<br>      outline: palette.outline,<br>      outlineVariant: palette.outlineVariant,<br>      // ...full M3 token coverage<br>    );<br>  }<br>  static ColorScheme get dark { /* mirror with AppColors.dark */ }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> Every screen reads colors from </em><em>Theme.of(context).colorScheme. Switching to dark mode is one prop change on </em><em>MaterialApp. The palette in </em><em>AppColors is the </em>only<em> place hex codes live.</em></blockquote><h3>3. ThemeExtension for Brand-Specific Colors</h3><p>Not every color fits Material’s slot system. “Brand primary,” “shimmer base,” “warning amber” — these are app-specific. ThemeExtension is built for exactly this case: extra theme data that travels with the theme and respects light/dark mode.</p><p><strong>After:</strong></p><pre>// ✅ After — lib/core/theme/app_theme_extension.dart<br>final class AppThemeExtension extends ThemeExtension&lt;AppThemeExtension&gt; {<br>  const AppThemeExtension({<br>    required this.brandPrimary,<br>    required this.brandSecondary,<br>    required this.success,<br>    required this.warning,<br>    required this.cardBackground,<br>    required this.shimmerBase,<br>    required this.shimmerHighlight,<br>    // ...<br>  });<br>  final Color brandPrimary;<br>  final Color brandSecondary;<br>  final Color success;<br>  final Color warning;<br>  final Color cardBackground;<br>  final Color shimmerBase;<br>  final Color shimmerHighlight;<br>  <br>static AppThemeExtension light = AppThemeExtension(<br>    brandPrimary: AppColors.light.primary,<br>    brandSecondary: AppColors.light.secondary,<br>    success: AppColors.light.tertiary,<br>    warning: const Color(0xFFFF9800),<br>    cardBackground: AppColors.light.surface,<br>    shimmerBase: const Color(0xFFE0E0E0),<br>    shimmerHighlight: const Color(0xFFF5F5F5),<br>  );<br> static AppThemeExtension dark = AppThemeExtension(<br>    // ...dark variants<br>  );<br>@override<br>  ThemeExtension&lt;AppThemeExtension&gt; copyWith({ /* ... */ }) { /* ... */ }<br>@override<br>  ThemeExtension&lt;AppThemeExtension&gt; lerp(<br>    ThemeExtension&lt;AppThemeExtension&gt;? other,<br>    double t,<br>  ) {<br>    // Color.lerp for every field — gives you free animations<br>  }<br><br>  extension AppThemeExtensionContext on BuildContext {<br>  AppThemeExtension get appTheme =&gt;<br>      Theme.of(this).extension&lt;AppThemeExtension&gt;()!;<br>}<br><br>extension AppTextThemeContext on BuildContext {<br>  TextTheme get appTextTheme =&gt; Theme.of(this).textTheme;<br>  ColorScheme get colorScheme =&gt; Theme.of(this).colorScheme;<br>}</pre><p>Usage in widgets:</p><pre>// Before<br>Container(color: const Color(0xFF1976D2))<br><br>// After<br>Container(color: context.appTheme.brandPrimary)</pre><blockquote><strong><em>Why this matters:</em></strong><em> Colors that change at runtime (light/dark, theme switching) </em><strong><em>must</em></strong><em> come from context, not from constants. The </em><em>BuildContext extension makes that one-liner ergonomic. </em><em>lerp gives you free crossfade animations during theme changes.</em></blockquote><h3>4. Padding That Doesn’t Allocate</h3><p>EdgeInsets.all(20) is fine — but writing it on every widget is noise. And making spacing helpers into getters allocates a fresh EdgeInsets on every call.</p><p><strong>Before:</strong></p><pre>// ❌ Before — scattered across the codebase<br>Padding(padding: const EdgeInsets.all(20), child: ...)<br>Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: ...)<br>SizedBox(height: 20)</pre><p><strong>After:</strong></p><pre>// ✅ After — lib/core/theme/app_page_padding.dart<br>final class AppPagePadding extends EdgeInsets {<br>  const AppPagePadding.all16() : super.all(_spacingM);<br>  const AppPagePadding.all20() : super.all(_spacingL);<br>  const AppPagePadding.all24() : super.all(_spacingXl);<br>const AppPagePadding.horizontalSymmetric()<br>      : super.symmetric(horizontal: _spacingL);<br>  const AppPagePadding.verticalSymmetric()<br>      : super.symmetric(vertical: _spacingL);<br>  const AppPagePadding.marginBottom16() : super.only(bottom: _spacingM);<br><br>static const double _spacingXs = 8;<br>  static const double _spacingM = 16;<br>  static const double _spacingL = 20;<br>  static const double _spacingXl = 24;<br>  static const double _spacingXXl = 32;<br>}<br><br>// Usage<br>Padding(padding: const AppPagePadding.all20(), child: ...)</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>const constructors mean zero allocation — Dart canonicalizes them at compile time. The named constructors (</em><em>all16, </em><em>marginBottom16) read like intent, not magic numbers. The </em><em>_spacingXs/</em><em>_spacingM/</em><em>_spacingL ladder enforces a 4-multiple system.</em></blockquote><h3>5. The Login Page Before View-ViewModel-Mixin</h3><p>Now the second refactor. Here’s what the login page looked like before PR #9 — even <em>after</em> the theme refactor was applied.</p><p><strong>Before:</strong></p><pre>// ❌ Before — login_page.dart (211 lines)<br>class LoginPage extends StatefulWidget {<br>  @override<br>  _LoginPageState createState() =&gt; _LoginPageState();<br>}<br><br>class _LoginPageState extends State&lt;LoginPage&gt; {<br>  TextEditingController emailController = TextEditingController();<br>  TextEditingController passwordController = TextEditingController();<br>  String errorMessage = &#39;&#39;;<br>  bool isLoading = false;<br><br>  void login() async {<br>    setState(() {<br>      isLoading = true;<br>      errorMessage = &#39;&#39;;<br>    });<br><br>Dio dio = Dio();<br>    String baseUrl = &#39;http://localhost:8080&#39;; // hard-coded URL<br><br>try {<br>      Response response = await dio.post(&#39;$baseUrl/login&#39;, data: {<br>        &#39;email&#39;: emailController.text,<br>        &#39;password&#39;: passwordController.text,<br>      });<br>if (response.statusCode == 200) {<br>        final loginResponse = LoginResponseModel.fromJson(<br>          jsonDecode(response.data),<br>        );<br>        if (loginResponse.success) {<br>          await saveUserToCache(loginResponse);     // cache logic in widget<br>          await _logSuccessfulLogin(loginResponse); // analytics in widget<br>          setState(() =&gt; isLoading = false);<br>          Navigator.pushReplacement(/* ... */);<br>        } else {<br>          setState(() {<br>            isLoading = false;<br>            errorMessage = loginResponse.message;<br>          });<br>        }<br>      }<br>    } catch (e) {<br>      setState(() =&gt; errorMessage = &#39;Bağlantı hatası: $e&#39;);<br>    }<br>  <br>  Future&lt;void&gt; saveUserToCache(LoginResponseModel r) async { /* ... */ }<br>  Future&lt;void&gt; _logSuccessfulLogin(LoginResponseModel r) async { /* ... */ }<br><br>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      // 100+ lines of UI mixed with controllers and state<br>    );<br>  }<br>}</pre><p>Network logic, SharedPreferences writes, Firebase Analytics calls, error formatting, and 100 lines of widget tree — all in _LoginPageState. This is the file I was talking about: when you open the file, you can&#39;t reach build() without scrolling.</p><h3>6. Splitting Into View, ViewModel, and Mixin</h3><p>The fix is structural, not stateful. Three rules:</p><ol><li><strong>View</strong> owns layout. Nothing else.</li><li><strong>Mixin</strong> owns controllers, lifecycle, and UI actions.</li><li><strong>ViewModel</strong> owns business operations (network, cache, analytics).</li></ol><p>part/part of keeps related files visually separate but lexically one unit — no public API leakage.</p><p><strong>After:</strong></p><pre>// ✅ After — login_page.dart (37 lines)<br>import &#39;package:flight_booking/core/theme/theme.dart&#39;;<br>import &#39;package:flight_booking/feature/auth/flight/flight_list_page.dart&#39;;<br>import &#39;package:flight_booking/feature/unauth/login/view/login_page_state.dart&#39;;<br>import &#39;package:flight_booking/feature/unauth/login/view_model/login_view_model.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_svg/flutter_svg.dart&#39;<br><br>part &#39;view/login_page_mixin.dart&#39;;<br>part &#39;view/widget/_login_test_account_info.dart&#39;;<br>part &#39;view/widget/login_page_body.dart&#39;;<br><br>final class LoginPage extends StatefulWidget {<br>  const LoginPage({super.key});<br><br>  @override<br>  State&lt;LoginPage&gt; createState() =&gt; _LoginPageState();<br>}<br><br>final class _LoginPageState extends State&lt;LoginPage&gt; with LoginPageMixin {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      backgroundColor: context.colorScheme.surface,<br>      appBar: AppBar(<br>        title: ProductText.h3(context, &#39;Flight Booking&#39;),<br>        centerTitle: true,<br>        backgroundColor: context.colorScheme.primary,<br>      ),<br>      body: _LoginPageBody(<br>        emailController: emailController,<br>        passwordController: passwordController,<br>        state: state,<br>        onLogin: onLoginPressed,<br>      ),<br>    );<br>  }<br>}</pre><p>That’s the whole page. You can read it in 5 seconds.</p><blockquote><strong><em>Why this matters:</em></strong><em> The </em><em>View only knows three things: layout, what controllers to pass down, and what callback to wire. Everything else — controllers, state, network — lives next door, accessible because of </em><em>part of.</em></blockquote><h3>7. The Mixin: Controllers and UI Actions</h3><p>Controllers are stateful. Their lifecycle is tied to the widget. They belong to the mixin, not the build method.</p><p><strong>After:</strong></p><pre>// ✅ After — view/login_page_mixin.dart<br>part of &#39;../login_page.dart&#39;;<br><br>mixin LoginPageMixin on State&lt;LoginPage&gt; {<br>  // ViewModel<br>  late final LoginViewModel _viewModel;<br><br>// Controllers<br>  late final TextEditingController emailController;<br>  late final TextEditingController passwordController;<br>// UI state via ValueNotifier — no setState<br>  late final ValueNotifier&lt;LoginPageState&gt; state;<br><br>@override<br>  void initState() {<br>    super.initState();<br>    _viewModel = LoginViewModel();<br>    emailController = TextEditingController();<br>    passwordController = TextEditingController();<br>    state = ValueNotifier(const LoginPageState());<br>  }<br><br>@override<br>  void dispose() {<br>    emailController.dispose();<br>    passwordController.dispose();<br>    state.dispose();<br>    super.dispose();<br>  }<br><br>Future&lt;void&gt; onLoginPressed() async {<br>    state.value = state.value.copyWith(isLoading: true, errorMessage: &#39;&#39;);<br>try {<br>      final response = await _viewModel.login(<br>        email: emailController.text,<br>        password: passwordController.text,<br>      );<br><br>if (response.success) {<br>        await _viewModel.saveUserToCache(response);<br>        await _viewModel.logSuccessfulLogin(response);<br>if (!mounted) return;<br>        state.value = state.value.copyWith(isLoading: false);<br>await Navigator.pushReplacement&lt;void, void&gt;(<br>          context,<br>          MaterialPageRoute&lt;void&gt;(builder: (_) =&gt; FlightListPage()),<br>        );<br>      } else {<br>        state.value = state.value.copyWith(<br>          isLoading: false,<br>          errorMessage: response.message,<br>        );<br>      }<br>    } on Exception catch (e) {<br>      state.value = state.value.copyWith(<br>        isLoading: false,<br>        errorMessage: &#39;Bağlantı hatası: $e&#39;,<br>      );<br>    }<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> A mixin is an abstract “plugin” you attach to a class. Only widgets that opt into </em><em>LoginPageMixin get these controllers — no global access, no leak. </em><em>late final lets us defer initialization to </em><em>initState while keeping fields immutable. </em><em>ValueNotifier replaces </em><em>setState so the page rebuilds nothing it doesn&#39;t have to.</em></blockquote><h3>8. Immutable State with Equatable</h3><p>bool isLoading; String errorMessage; works — but every setState mutates the widget directly. Equatable + copyWith give you predictable, comparable, history-friendly state.</p><p><strong>After:</strong></p><pre>// ✅ After — view/login_page_state.dart<br>@immutable<br>final class LoginPageState extends Equatable {<br>  const LoginPageState({<br>    this.errorMessage = &#39;&#39;,<br>    this.isLoading = false,<br>  });<br><br>final String errorMessage;<br>  final bool isLoading;<br><br>LoginPageState copyWith({String? errorMessage, bool? isLoading}) {<br>    return LoginPageState(<br>      errorMessage: errorMessage ?? this.errorMessage,<br>      isLoading: isLoading ?? this.isLoading,<br>    );<br>  }<br><br>@override<br>  List&lt;Object?&gt; get props =&gt; [errorMessage, isLoading];<br>}</pre><p>Wired to the body via ValueListenableBuilder:</p><pre>// In login_page_body.dart<br>ValueListenableBuilder&lt;LoginPageState&gt;(<br>  valueListenable: state,<br>  builder: (context, value, _) {<br>    if (value.isLoading) return const CircularProgressIndicator();<br>    if (value.errorMessage.isNotEmpty) {<br>      return ProductText.bodySmall(<br>        context,<br>        value.errorMessage,<br>        color: context.colorScheme.error,<br>      );<br>    }<br>    return ElevatedButton(onPressed: onLogin, child: const Text(&#39;Login&#39;));<br>  },<br>);</pre><blockquote><strong><em>Why this matters:</em></strong><em> No state management library needed. </em><em>ValueNotifier ships with Flutter. Equatable makes </em><em>state == oldState cheap and reliable, so </em><em>ValueListenableBuilder only rebuilds when fields actually change. For most pages, this is enough — Bloc/Riverpod come later when you outgrow it.</em></blockquote><h3>9. The ViewModel: Pure Business Logic</h3><p>The ViewModel doesn’t know about widgets, BuildContext, or navigation. It returns data and throws exceptions. The mixin decides what to do with results.</p><p><strong>After:</strong></p><pre>// ✅ After — view_model/login_view_model.dart<br>final class LoginViewModel {<br>  LoginViewModel();<br><br>static const String _baseUrl = &#39;http://localhost:8080&#39;;<br><br>Future&lt;LoginResponseModel&gt; login({<br>    required String email,<br>    required String password,<br>  }) async {<br>    final dio = Dio();<br>    final response = await dio.post&lt;String&gt;(<br>      &#39;$_baseUrl/login&#39;,<br>      data: {&#39;email&#39;: email, &#39;password&#39;: password},<br>    );<br>    if (response.statusCode == 200) {<br>      return LoginResponseModel.fromJson(<br>        jsonDecode(response.data!) as Map&lt;String, dynamic&gt;,<br>      );<br>    }<br>    throw Exception(&#39;Exception: ${response.statusCode}&#39;);<br>  }<br><br>Future&lt;void&gt; saveUserToCache(LoginResponseModel r) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(&#39;user_token&#39;, r.token);<br>    await prefs.setString(&#39;user_email&#39;, r.user.email);<br>    await prefs.setBool(&#39;is_logged_in&#39;, true);<br>    // ...<br>  }<br><br>Future&lt;void&gt; logSuccessfulLogin(LoginResponseModel r) async {<br>    try {<br>      await CustomRemoteConfig.instance.analytics.logLogin(loginMethod: &#39;email&#39;);<br>      await CustomRemoteConfig.instance.analytics.logEvent(<br>        name: &#39;successful_login&#39;,<br>        parameters: {<br>          &#39;login_timestamp&#39;: DateTime.now().millisecondsSinceEpoch,<br>          &#39;user_id&#39;: r.user.id,<br>          &#39;platform&#39;: &#39;mobile&#39;,<br>        },<br>      );<br>    } on Exception catch (e) {<br>      debugPrint(&#39;Analytics logging failed: $e&#39;);<br>    }<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> This file is testable without a Flutter binding. You can mock Dio, call </em><em>login(), assert the response. The </em><em>saveUserToCache call doesn&#39;t sit inside a widget anymore — it&#39;s a method you can run in isolation. The next step (covered in PR #11) is wrapping </em><em>Dio in an </em><em>INetworkManager interface — but the seam is already cut here.</em></blockquote><h3>Key Takeaways</h3><ol><li><strong>Theme = </strong><strong>final class + private constructor</strong> — Themes are built once. Don&#39;t make them getters that recompute. Don&#39;t allow inheritance you don&#39;t need.</li><li><strong>ColorScheme first, </strong><strong>ThemeExtension second</strong> — Material 3 covers most slots. Use ThemeExtension only for <em>brand-specific</em> additions, never for things M3 already provides.</li><li><strong>AppPagePadding with </strong><strong>const constructors</strong> — Named, intent-revealing, zero-allocation spacing. The 4-multiple ladder (8/16/20/24/32) becomes a contract.</li><li><strong>part/</strong><strong>part of over public files</strong> — When the View, Mixin, State, and Body are conceptually one page, lexically separating with part keeps the file count small and the imports clean.</li><li><strong>Mixin owns lifecycle, ViewModel owns business</strong> — Controllers and ValueNotifiers die with the widget (mixin). Network/cache/analytics outlive the widget conceptually (ViewModel).</li><li><strong>ValueNotifier + Equatable beats </strong><strong>setState for state pages</strong> — You don&#39;t need Bloc on day one. Start with what Flutter ships with. Migrate when you actually need cross-widget state.</li><li><strong>The View should be readable in 5 seconds</strong> — If you can’t see the widget tree without scrolling, the page is doing too much. Refactor until build() fits on one screen.</li></ol><h3>What’s Next</h3><p>In <strong>Part 3</strong>, we’ll tackle the <strong>Network &amp; Service Layer</strong> — wrapping Dio behind an INetworkManager interface, generating models with freezed/json_serializable, and centralizing error handling. The LoginViewModel we built here will become a thin caller of IAuthService.</p><p><em>This article is part of the </em><strong><em>Flutter Refactoring Masterclass</em></strong><em> series, where we transform a messy real-world project into production-ready code, one PR at a time.</em></p><h3>📺 Watch the Full Series</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La%26si%3DZv6Z2Xli_dVzB6qJ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkaqIas6nXZc%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLBoqyP9P4JS_VLHi4U4DrczN8t1gA%26days_since_epoch%3D20576&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/58386b8f7db3bd4e1e5df2d45aafc958/href">https://medium.com/media/58386b8f7db3bd4e1e5df2d45aafc958/href</a></iframe><h3>🤖 Apply This to Your Project</h3><p>Use this prompt with Claude or your AI assistant to refactor an existing Flutter screen:</p><pre>Refactor my Flutter feature into the View / ViewModel / Mixin architecture<br>and align it with a centralized theme system.<br>Theme layer (lib/core/theme/):<br>1. Create AppColors (light/dark palettes — single source of truth for hex values).<br>2. Create AppColorScheme with two static getters that map AppColors → Material 3 ColorScheme.<br>3. Create AppTheme as a `final class` with private constructor and static<br>   `lightTheme`/`darkTheme` getters that compose ColorScheme + TextTheme + extensions.<br>4. Create AppThemeExtension extends ThemeExtension&lt;AppThemeExtension&gt; for brand-specific<br>   colors (brandPrimary, success, warning, shimmer, etc.). Implement copyWith and lerp.<br>5. Add BuildContext extensions: `context.appTheme`, `context.colorScheme`,<br>   `context.appTextTheme`.<br>6. Create AppPagePadding extends EdgeInsets with named const constructors<br>   (all16, all20, horizontalSymmetric, marginBottom16, etc.) backed by 4-multiple<br>   spacing constants.<br>7. Create AppTextStyles (h1, h3, body, caption) and a ProductText widget that<br>   reads from theme.<br>View architecture (lib/feature/&lt;area&gt;/&lt;feature&gt;/):<br>1. Reduce the page file to &lt;50 lines. It should only contain the StatefulWidget,<br>   _&lt;Page&gt;State with the mixin, and a build() method that returns Scaffold +<br>   _&lt;Page&gt;Body.<br>2. Create view/&lt;feature&gt;_page_mixin.dart as a `part of` the page.<br>   Move all controllers, ValueNotifiers, initState, dispose, and UI action<br>   methods (onXPressed) here.<br>3. Create view/&lt;feature&gt;_page_state.dart with @immutable + Equatable +<br>   copyWith. Default-init all fields. props lists every field.<br>4. Create view/widget/&lt;feature&gt;_page_body.dart as `part of` the page.<br>   This is the large UI tree. Use ValueListenableBuilder for state-driven<br>   sections.<br>5. Create view_model/&lt;feature&gt;_view_model.dart as a final class with no<br>   Flutter imports. Network calls, cache writes, analytics — all return<br>   plain data or throw.<br>Rules:<br>- Use `final class` everywhere unless the class is meant to be extended.<br>- Replace setState with ValueNotifier&lt;State&gt; + ValueListenableBuilder.<br>- No raw EdgeInsets in widgets — always AppPagePadding.<br>- No raw hex colors in widgets — always context.colorScheme or context.appTheme.<br>- Files inside the same feature use `part`/`part of`, not public exports,<br>  unless shared across features.<br>Show before/after for the page file and list every new file created.</pre><p>Or invoke the existing skill directly:</p><pre>/flutter-view-refactor lib/feature/unauth/login</pre><h3>📋 Full Series Roadmap</h3><p><em>⭐ </em><a href="https://github.com/VB10/flight_booking"><em>github.com/VB10/flight_booking</em></a></p><p>This is Part 2 of a 20-part series. Here’s the complete roadmap:</p><p><strong>Completed:</strong> v1–v5 (Project Setup), v6 (Theme &amp; Design System), v7.1 (View-ViewModel-Mixin)</p><p><strong>Coming Next:</strong> v7.2 Service &amp; Model Layer, v8 Network Architecture, v9 State Management with Cubit, v10 Navigation with go_router, plus testing, code generation, and more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e922c9e1da1454a09a1642f1cb07711c/href">https://medium.com/media/e922c9e1da1454a09a1642f1cb07711c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a19c8885125" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/theme-system-and-view-viewmodel-mixin-building-a-scalable-flutter-ui-layer-2a19c8885125">Theme System and View-ViewModel-Mixin: Building a Scalable Flutter UI Layer</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Refactoring Masterclass — Part 1]]></title>
            <link>https://medium.com/flutter-community/flutter-refactoring-masterclass-part-1-045afd0fa493?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/045afd0fa493</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 08:33:44 GMT</pubDate>
            <atom:updated>2026-03-21T15:04:53.733Z</atom:updated>
            <content:encoded><![CDATA[<p>Transform a messy Flutter project into a professional codebase — one PR at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyCa015QLNVqAVjOI_zAVA.png" /><figcaption>Let’s upgrade our coding practices using a real-world project.</figcaption></figure><p><a href="https://github.com/VB10/flight_booking">GitHub - VB10/flight_booking: Flight App for refactoring real project</a></p><p><em>⭐ </em><a href="https://github.com/VB10/flight_booking"><em>github.com/VB10/flight_booking</em></a></p><p><strong><em>PRs:</em></strong><em> </em><a href="https://github.com/VB10/flight_booking/pull/1"><em>#1</em></a><em>, </em><a href="https://github.com/VB10/flight_booking/pull/2"><em>#2</em></a><em>, </em><a href="https://github.com/VB10/flight_booking/pull/3"><em>#3</em></a><em>, </em><a href="https://github.com/VB10/flight_booking/pull/5"><em>#5</em></a></p><p>📺 <strong>Video Series:</strong> <a href="https://youtu.be/Lz9TJJPqi1o">1-Overview</a> · <a href="https://youtu.be/A8RQupxiv5A">2-Pubspec</a> · <a href="https://youtu.be/fMlJAy3pr0k">3-Linter</a> · <a href="https://youtu.be/fSDYS5Lr59g">4-Architecture</a> · <a href="https://youtu.be/JAzdG1_MKWw">5-Main.dart</a></p><p>🤖 <em>Want to apply these changes to your project? See the </em><a href="#-apply-this-to-your-project"><em>AI prompt</em></a><em> at the end.</em></p><h3>What is Flutter Refactoring Masterclass?</h3><p>After years of building Flutter applications — some from scratch, some inherited — I’ve seen the same patterns repeat. Projects that start clean eventually become messy. New team members struggle to understand the codebase. Even the original developers forget why things are the way they are.</p><p>This series is my attempt to fix that. I took a typical “bad” Flutter project and I’m cleaning it up <strong>piece by piece</strong>, documenting every step with:</p><ul><li><strong>YouTube videos</strong> — Walking through the reasoning and implementation</li><li><strong>GitHub PRs</strong> — Real code changes you can review and copy</li><li><strong>Articles</strong> — Written summaries with before/after comparisons</li><li><strong>AI prompts</strong> — So you can apply the same refactoring to your own projects</li></ul><p>The goal isn’t to teach you something new — it’s to show you <strong>how to apply what you already know</strong> in a systematic, repeatable way. When a new developer joins your team, they should be able to understand the project structure in minutes, not hours.</p><p>Let’s start with the foundation.</p><h3>The Problem</h3><p>Every Flutter developer has inherited — or created — a messy project. Files scattered in lib/ root. Dependencies listed without any organization. Default linter rules that catch nothing. A main.dart bloated with Firebase initialization, analytics setup, and business logic.</p><p>When someone new joins the team, they spend hours just understanding where things are. When you return to the project after a month, you wonder who wrote this chaos. That developer was you.</p><p>This article covers the <strong>foundation refactoring</strong> — the boring-but-essential changes that transform a hobby project into a professional codebase. We’ll work through real PR diffs from the <a href="https://github.com/VB10/flight_booking">flight_booking</a> repository.</p><h3>What We Changed</h3><ul><li><strong>pubspec.yaml</strong> — Organized dependencies by category, removed boilerplate comments</li><li><strong>analysis_options.yaml</strong> — Switched to very_good_analysis, enabled strict mode</li><li><strong>.gitignore</strong> — Added *.lock pattern</li><li><strong>.vscode/settings.json</strong> — Format on save, organize imports</li><li><strong>.vscode/launch.json</strong> — Flavor-based launch configurations</li><li><strong>lib/ folder structure</strong> — Feature-based architecture</li><li><strong>main.dart</strong> — Clean initialization with AppInitializer pattern</li></ul><h3>1. Pubspec.yaml: Your Project’s Table of Contents</h3><p>The pubspec is the first file anyone reads. It should communicate what your project does and what it depends on — at a glance.</p><p><strong>Before:</strong></p><pre># ❌ Before — pubspec.yaml (86 lines with comments)<br>dependencies:<br>  flutter:<br>    sdk: flutter</pre><pre>  # The following adds the Cupertino Icons font to your application.<br>  # Use with the CupertinoIcons class for iOS style icons.<br>  cupertino_icons: ^1.0.8<br>  dio: ^5.3.2<br>  shared_preferences: ^2.2.2<br>  shimmer: ^3.0.0<br>  lottie: ^2.7.0<br>  flutter_svg: ^2.0.9<br>  firebase_core: ^2.24.2<br>  firebase_remote_config: ^4.3.8<br>  firebase_analytics: ^10.7.4<br>  package_info_plus: ^4.2.0</pre><pre># ... 40 more lines of Flutter-generated comments</pre><p><strong>After:</strong></p><pre># ✅ After — pubspec.yaml (64 lines, organized)<br>dependencies:<br>  flutter:<br>    sdk: flutter<br>  cupertino_icons: ^1.0.8<br><br>  # Network<br>  dio: ^5.3.2<br>  # Database<br>  shared_preferences: ^2.2.2<br>  # Firebase<br>  firebase_core: ^2.24.2<br>  firebase_remote_config: ^4.3.8<br>  firebase_analytics: ^10.7.4<br>  # View utilities<br>  shimmer: ^3.0.0<br>  lottie: ^2.7.0<br>  flutter_svg: ^2.0.9<br>  # Native plugins<br>  package_info_plus: ^4.2.0<br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^5.0.0<br>  very_good_analysis: ^10.0.0<br>  build_runner: ^2.9.0</pre><blockquote><strong><em>Why this matters:</em></strong><em> When a package causes issues, you immediately know which category it belongs to. When onboarding a new developer, they understand the project’s tech stack in seconds.</em></blockquote><h3>2. Analysis Options: The Team’s Code Contract</h3><p>Default Flutter linting catches almost nothing. When you write code that works but isn’t maintainable, nobody tells you. The very_good_analysis package changes that—it&#39;s the linter used by Very Good Ventures, one of the most respected Flutter consultancies.</p><p><strong>Before:</strong></p><pre># ❌ Before — analysis_options.yaml<br>include: package:flutter_lints/flutter.yaml</pre><pre>linter:<br>  rules:<br>    # avoid_print: false  # Uncomment to disable the `avoid_print` rule<br>    # prefer_single_quotes: true  # Uncomment to enable...</pre><p><strong>After:</strong></p><pre># ✅ After — analysis_options.yaml<br>include: package:very_good_analysis/analysis_options.yaml<br>analyzer:<br>  language:<br>    strict-casts: true<br>    strict-raw-types: true<br>  exclude:<br>    - &quot;**/*.g.dart&quot;<br>    - &quot;**/*.freezed.dart&quot;<br>    - test/**<br>  errors:<br>    missing_return: error<br>    dead_code: error<br>    unused_import: error<br>    argument_type_not_assignable: info  # TODO: fix this<br>linter:<br>  rules:<br>    avoid_print: true<br>    prefer_single_quotes: true<br>    always_declare_return_types: true<br>    prefer_const_constructors: true<br>    prefer_final_locals: true<br>    use_super_parameters: true<br>    public_member_api_docs: false<br>    lines_longer_than_80_chars: false</pre><blockquote><strong><em>Why this matters:</em></strong><em> </em><em>strict-casts: true catches implicit type conversions that cause runtime crashes. </em><em>prefer_final_locals enforces immutability. These aren&#39;t preferences—they&#39;re bug prevention.</em></blockquote><h3>3. VSCode Settings &amp; .gitignore</h3><p>Lock files cause merge conflicts. Team members have different editors. Imports get shuffled randomly.</p><p><strong>New: </strong><strong>.vscode/settings.json</strong></p><pre>{<br>    &quot;dart.lineLength&quot;: 80,<br>    &quot;[dart]&quot;: {<br>        &quot;editor.formatOnSave&quot;: true,<br>        &quot;editor.formatOnType&quot;: true,<br>        &quot;editor.rulers&quot;: [80],<br>        &quot;editor.codeActionsOnSave&quot;: {<br>            &quot;source.organizeImports&quot;: &quot;explicit&quot;,<br>            &quot;source.fixAll&quot;: &quot;explicit&quot;<br>        }<br>    }<br>}</pre><p><strong>New: </strong><strong>.vscode/launch.json</strong></p><pre>{<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;App (Development)&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;toolArgs&quot;: [&quot;--dart-define&quot;, &quot;FLAVOR=development&quot;]<br>        },<br>        {<br>            &quot;name&quot;: &quot;App (Production)&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;toolArgs&quot;: [&quot;--dart-define&quot;, &quot;FLAVOR=production&quot;]<br>        }<br>    ]<br>}</pre><p><strong>Updated: </strong><strong>.gitignore</strong></p><pre># Added<br>*.lock</pre><blockquote><strong><em>Why this matters:</em></strong><em> When every save auto-formats and organizes imports, code reviews focus on logic — not style. Removing lock files from git eliminates 90% of merge conflicts in iOS projects.</em></blockquote><h3>4. Folder Structure: Feature-Based Architecture</h3><p>All files dumped in lib/ root is the #1 sign of a beginner project.</p><p><strong>Before:</strong></p><pre>lib/<br>├── main.dart<br>├── cart_page.dart<br>├── checkout_response_model.dart<br>├── flight_detail_page.dart<br>├── flight_list_page.dart<br>├── flights_response_model.dart<br>├── login_page.dart<br>├── login_response_model.dart<br>├── profile_page.dart<br>├── splash_page.dart<br>└── firebase_options.dart</pre><p><strong>After:</strong></p><pre>lib/<br>├── main.dart<br>├── core/<br>│   └── util/<br>│       └── string_helper.dart<br>├── feature/<br>│   ├── auth/<br>│   │   ├── cart/<br>│   │   │   ├── cart_page.dart<br>│   │   │   └── checkout_response_model.dart<br>│   │   ├── flight/<br>│   │   │   ├── flight_list_page.dart<br>│   │   │   └── flights_response_model.dart<br>│   │   ├── flight_detail/<br>│   │   │   └── flight_detail_page.dart<br>│   │   └── profile/<br>│   │       └── profile_page.dart<br>│   ├── unauth/<br>│   │   ├── login/<br>│   │   │   ├── login_page.dart<br>│   │   │   └── login_response_model.dart<br>│   │   └── splash/<br>│   │       └── splash_page.dart<br>│   └── sub_feature/<br>│       └── main/<br>│           └── main_app.dart<br>├── product/<br>│   ├── initialize/<br>│   │   ├── app_initializer.dart<br>│   │   ├── platform_initializer.dart<br>│   │   └── firebase/<br>│   │       └── custom_remote_config.dart<br>│   └── package/<br>│       └── firebase/<br>│           └── firebase_options.dart<br>└── module/<br>    └── utils/</pre><blockquote><strong><em>Why this matters:</em></strong><em> When someone asks “where’s the login logic?”, the answer is obvious: </em><em>feature/unauth/login/. When you need to add a new feature, you know exactly where to create the folder.</em></blockquote><h3>5. Main.dart: The 10-Line Ideal</h3><p>Your main.dart should be readable in 5 seconds.</p><p><strong>Before:</strong></p><pre>// ❌ Before — main.dart (65 lines)<br>import &#39;package:firebase_analytics/firebase_analytics.dart&#39;;<br>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:firebase_remote_config/firebase_remote_config.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;</pre><pre>// Global variables - bad practice<br>late FirebaseRemoteConfig remoteConfig;<br>late FirebaseAnalytics analytics;<br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  remoteConfig = FirebaseRemoteConfig.instance;<br>  await remoteConfig.setDefaults({<br>    &#39;minimum_app_version&#39;: &#39;1.0.0&#39;,<br>    &#39;force_update_required&#39;: false,<br>    // ... more config<br>  });<br>  analytics = FirebaseAnalytics.instance;<br>  await analytics.setAnalyticsCollectionEnabled(true);<br>  runApp(MyApp());<br>}</pre><p><strong>After:</strong></p><pre>// ✅ After — main.dart (10 lines)<br>import &#39;package:flight_booking/feature/sub_feature/main/main_app.dart&#39;;<br>import &#39;package:flight_booking/product/initialize/app_initializer.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() async {<br>  AppInitializer.run();<br>  await AppInitializer().prepare();<br>  runApp(const MainApp());<br>}</pre><p><strong>New: </strong><strong>app_initializer.dart</strong></p><pre>// ✅ After — product/initialize/app_initializer.dart<br>final class AppInitializer {<br>  AppInitializer() {<br>    platformInitializer = kIsWeb<br>        ? WebPlatformInitializer()<br>        : MobilePlatformInitializer();<br>  }</pre><pre>static void run() {<br>    WidgetsFlutterBinding.ensureInitialized();<br>  }<br>  late final PlatformInitializer platformInitializer;<br>  Future&lt;void&gt; prepare() async {<br>    await Future.wait([<br>      platformInitializer.prepare(),<br>      Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform),<br>      CustomRemoteConfig.instance.initialize(),<br>    ]);<br>  }<br>}</pre><p><strong>New: </strong><strong>custom_remote_config.dart</strong></p><pre>// ✅ After — product/initialize/firebase/custom_remote_config.dart<br>final class CustomRemoteConfig {<br>  static final CustomRemoteConfig instance = CustomRemoteConfig._();<br>  CustomRemoteConfig._();<br><br>final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.instance;<br>  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;<br>  Future&lt;void&gt; initialize() async {<br>    await remoteConfig.setDefaults({<br>      &#39;minimum_app_version&#39;: &#39;1.0.0&#39;,<br>      &#39;force_update_required&#39;: false,<br>    });<br>  }<br>}</pre><blockquote><strong><em>Why this matters:</em></strong><em> Global variables are gone. Firebase logic is encapsulated. Platform-specific initialization is abstracted. Adding a new initialization step means adding one line to </em><em>Future.wait().</em></blockquote><h3>Key Takeaways</h3><ol><li><strong>Organize pubspec.yaml by category</strong> — Network, Database, Firebase, UI. Future you will thank present you.</li><li><strong>Use </strong><strong>very_good_analysis</strong> — It catches bugs before they reach production. Enable strict-casts and strict-raw-types.</li><li><strong>Remove lock files from git</strong> — Add *.lock to .gitignore. Run pod install locally.</li><li><strong>Feature-based folder structure</strong> — feature/auth/, feature/unauth/, product/, core/. Each feature is self-contained.</li><li><strong>10-line main.dart</strong> — Everything else goes in AppInitializer. Parallel initialization with Future.wait().</li></ol><h3>What’s Next</h3><p>In <strong>Part 2</strong>, we’ll tackle the <strong>Theme &amp; Design System</strong> — building a proper AppTheme, AppColors, and AppTextStyles that support light/dark modes and scale across the app.</p><p><em>This article is part of the </em><strong><em>Flutter Refactoring Masterclass</em></strong><em> series, where we transform a messy real-world project into production-ready code, one PR at a time.</em></p><h3>📺 Watch the Full Series</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxhHRhwAT1z2_0WfF2bMzQ.png" /><figcaption><a href="https://www.youtube.com/playlist?list=PL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La">https://www.youtube.com/playlist?list=PL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPL1k5oWAuBhgUh7_hMrTDxZHsGOPGSP9La&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUyp0rWupYJc%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLDRVzQ3W7yWf8HVczkS-bx7OYxPFA%26days_since_epoch%3D20523&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e70ff851e515db4f1062c6309451b5f9/href">https://medium.com/media/e70ff851e515db4f1062c6309451b5f9/href</a></iframe><h3>🤖 Apply This to Your Project</h3><p>Use this prompt with Claude or your AI assistant to analyze and refactor your Flutter project:</p><pre>Analyze my Flutter project and apply these refactoring steps:<br>1. **pubspec.yaml** - Organize dependencies by category (Network, Database, Firebase, UI, Native plugins). Remove all Flutter-generated comments.<br>2. **analysis_options.yaml** - Switch to very_good_analysis with strict-casts and strict-raw-types enabled. Add exclude patterns for generated files.<br>3. **.gitignore** - Add *.lock pattern to prevent merge conflicts.<br>4. **.vscode/settings.json** - Add formatOnSave, organizeImports, and 80-char ruler for Dart files.<br>5. **Folder structure** - Reorganize lib/ into feature-based architecture:<br>   - feature/auth/ (authenticated screens)<br>   - feature/unauth/ (login, splash)<br>   - product/initialize/ (app initialization)<br>   - core/util/ (shared utilities)<br>6. **main.dart** - Reduce to ~10 lines using AppInitializer pattern. Move all Firebase/analytics setup to separate initialization classes.<br>Show before/after for each change. Create PRs or commits for each step.</pre><h3>📋 Full Series Roadmap</h3><p>This is Part 1 of a 20-part series. Here’s the complete roadmap:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca3bdfc0fbdc91575d08ae719c2f0a8/href">https://medium.com/media/6ca3bdfc0fbdc91575d08ae719c2f0a8/href</a></iframe><p><strong>Completed:</strong> v1–v7 (Project Setup, Theme, View-ViewModel-Mixin)</p><p><strong>Coming Next:</strong> Navigation, State Management, Network Layer, Code Generation, Testing, and more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=045afd0fa493" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-refactoring-masterclass-part-1-045afd0fa493">Flutter Refactoring Masterclass — Part 1</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Patrol‑Driven UI Test Architecture for Flutter]]></title>
            <link>https://vbacik-10.medium.com/patrol-driven-ui-test-architecture-for-flutter-2e92923cfa49?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e92923cfa49</guid>
            <category><![CDATA[patrol]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ui-test-automation]]></category>
            <category><![CDATA[flutter-ui-test]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 09:20:33 GMT</pubDate>
            <atom:updated>2025-06-30T09:20:33.954Z</atom:updated>
            <content:encoded><![CDATA[<p>UI testing has become very important in recent years. Application development has sped up thanks to new AI tools. This article will help you create a structure for an enterprise application. Let’s get started</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIhfsj72zN34qxFWT_c8XQ.png" /><figcaption>Presentation link: <a href="https://www.canva.com/design/DAGozyMAJlE/jMXUaevEiHWItxyxCKAefQ/view?utm_content=DAGozyMAJlE&amp;utm_campaign=designshare&amp;utm_medium=link2&amp;utm_source=uniquelinks&amp;utlId=h680425d73d">https://www.canva.com/design/DAGozyMAJlE/jMXUaevEiHWItxyxCKAefQ/view?utm_content=DAGozyMAJlE&amp;utm_campaign=designshare&amp;utm_medium=link2&amp;utm_source=uniquelinks&amp;utlId=h680425d73d</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1097455561%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1097455561&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2031809613-c60bc65088edfb518c4cc716c892561d4fc67293e99316571b3f27804f7da02c-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7099f07f6510c9669024d93f1949b4c/href">https://medium.com/media/f7099f07f6510c9669024d93f1949b4c/href</a></iframe><p>I also presented this topic during an online session at the Flutter Global Summit. You can watch the full recording of my talk here</p><p><a href="https://www.youtube.com/live/L2uJ5iXm4O8?si=p1ow4QnOmbaVLTF6&amp;t=7870">- YouTube</a></p><h3><strong>Agenda</strong></h3><p>In this article, we’ll build a complete UI testing architecture for a Flutter application from scratch. Here’s a look at what we’ll cover:</p><ul><li>⚙️ <strong>The “What” and “Why” of UI Testing in Flutter</strong></li><li>📱 <strong>Introducing Patrol:</strong> Our Framework of Choice</li><li>🏗️ <strong>Case Study:</strong> Building Tests for the “Hatayı Yaşat” Project</li><li>📐 <strong>Designing a Scalable Test Architecture</strong></li><li>🎥 <strong>Live Demo:</strong> Seeing It All in Action</li><li>🚀 <strong>CI/CD Deployment:</strong> Automating Tests with Firebase Test Lab &amp; GitHub Actions</li></ul><h3>⚙️ <strong>The “What” and “Why” of UI Testing in Flutter</strong></h3><p>With the recent advancements in AI, application development is increasing every day. Many tools help developers create new apps, but the testing phase is often overlooked. UI testing helps us find problems before they affect real users, clients, or customers. For that reason, it is very important.</p><p>The mobile industry has a couple of ways to test applications:</p><ul><li><strong>Component Test:</strong> Testing individual widgets in isolation (e.g., a single button or text field).</li><li><strong>Integration Test:</strong> Testing a complete feature or a large part of the app to see how different components work together.</li></ul><p>My aim in this article is to talk about and write integration tests. This type of testing helps us find problems before a new release or before making changes to a big feature’s core.</p><p>Before using integration tests, your team is probably performing manual tests. Manual test cases are important, but it becomes harder to test every feature and change for each release. A one-time manual test before publishing an app is good, but repeatedly testing everything manually is not efficient. Manual testing has several problems: it is time-consuming, it’s hard to catch UI regressions, and it has scalability issues.</p><p>That means:</p><blockquote><em>“More screens = more test cases = more effort without automation.”</em></blockquote><p>The Flutter framework directly supports integration tests without any extra requirements. It can be used directly in any Flutter project. This testing framework can find elements on the screen and perform interactions like taps, scrolls, etc.</p><p>Here is an example of Flutter’s UI testing code:</p><pre>testWidgets(&#39;Onboarding screen shows logo and page indicator&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MyApp()); <br>  await tester.pumpAndSettle();<br><br>  expect(find.byType(Image), findsOneWidget);<br><br>  expect(find.text(&quot;HATAY&#39;I YAŞAT&quot;), findsOneWidget);<br><br>  expect(find.byType(Icon), findsNWidgets(3)); m<br>});</pre><p>You can find more details on the official website:</p><p><a href="https://docs.flutter.dev/testing/overview#integration-tests">Testing Flutter apps</a></p><p>While Flutter’s standard testing framework is powerful for interacting with UI elements, it has limitations. Sometimes, our tests need to go beyond the app’s UI and interact with the device’s native functionality. This includes actions like:</p><ul><li>Going to the home screen</li><li>Taking a screenshot</li><li>Opening the device’s settings</li><li>Handling native permission dialogs</li></ul><p>These are tasks that Flutter’s default tools don’t support out-of-the-box. This is where Patrol comes in. So, let’s dive in and implement Patrol in our project!</p><h3><strong>⚙️ Patrol</strong></h3><p>A UI framework called Patrol helps Flutter developers test their UIs more effectively. The framework helps us with three main things: finding elements easily, controlling native device behavior, and providing powerful CLI support.</p><p>Btw, here’s how the LeanCode team describes Patrol’s efficiency:</p><blockquote>Patrol is a powerful, open-source UI testing framework designed specifically for Flutter apps and released in September 2022. Developed and maintained by <a href="https://leancode.co/"><strong>LeanCode</strong></a>, one of the world’s leading Flutter development consultancies, Patrol builds upon Flutter’s core testing tools to enable developers to do things that were previously impossible.</blockquote><p>There are three key advantages to selecting Patrol for your UI testing:</p><ul><li><strong>Full Native Support:</strong> Go beyond the app’s UI to control the whole device.</li><li><strong>Powerful CLI Tool:</strong> Easily handle building, running, and publishing your tests.</li><li><strong>Hot Restart &amp; Debugging:</strong> Enjoy a fast and efficient development workflow.</li></ul><p>These features will help you rapidly test your Flutter projects. To get you started, here is a cheat sheet that clarifies the basics of how to implement and use Patrol commands in your project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acd35770f2f6733e690ac24653e1838c/href">https://medium.com/media/acd35770f2f6733e690ac24653e1838c/href</a></iframe><p>For more details about the Patrol framework, check out the official website.</p><p><a href="https://patrol.leancode.co/">Patrol</a></p><p>Before moving to the next session, make sure to check the native installation guide on their website. Now, let’s start structuring our project and make a demo.</p><h3><strong>📱 Case Study: “Hatayı Yaşat” Project</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpZmroYduqKIk2qZmPTTew.png" /><figcaption><a href="https://www.hatayiyasat.com/">https://www.hatayiyasat.com/</a></figcaption></figure><p>This is a project I’m very proud of. My team and I started this project two years ago after two major earthquakes occurred in Turkey. The first was a 7.8 magnitude, and the second was a 7.6. It was a very bad time for us. After the earthquakes, everyone tried to help the affected cities. During this time, we voluntarily created this project to help Hatay and the other affected regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTjyPs81E5_4k6dK30wjZg.png" /><figcaption>From the App Store: <a href="https://apps.apple.com/us/app/hatay%C4%B1-ya%C5%9Fat/id6465691080?platform=iphone">https://apps.apple.com/us/app/hatay%C4%B1-ya%C5%9Fat/id6465691080?platform=iphone</a></figcaption></figure><p>Our project helps newly opened companies by showing these places with detailed information. Another feature is that my teammates share activities, job advertisements, etc. I want to thank my team again for their work on this project!</p><p>Today, I’ll show the testing solution I implemented for this project. The tests will cover:</p><ul><li>The splash screen flow, including checking the Lottie animation.</li><li>The onboard screen flow, verifying that it is shown only on the first launch.</li><li>The home screen, to validate categories, list items, and more.</li></ul><h3><strong>🏗️ Test Architecture Design</strong></h3><p>Now, let’s dive into the core of this article: the test architecture. My approach is inspired by the “Chain of Responsibility” design pattern, which allows us to create a seamless, sequential flow for our feature tests.</p><p>Think about a standard user journey in your application. It often starts with a splash screen, moves to a login page, and finally lands on the home page. We can visualize this journey as a simple chain:</p><p>Splash -&gt; Login -&gt; Home</p><p>The architecture I designed allows us to build exactly this kind of chain. With a single command, we can trigger the first test in the sequence, and the rest will execute automatically, one after another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXqonaffHtT9iUx1ykXDTQ.png" /></figure><h4><strong>Architecture: Keys</strong></h4><p>The adventure begins with Keys. While the Patrol framework supports a couple of ways to find elements (like by class name or object type), I prefer to find them using Key variables.</p><pre><br>part &#39;items/general_keys.dart&#39;;<br>part &#39;items/home_keys.dart&#39;;<br>part &#39;items/onboard_keys.dart&#39;;<br>part &#39;items/splash_keys.dart&#39;;<br><br>final class ApplicationKeys {<br>  const ApplicationKeys._();<br><br>  static final splashKeys = _SplashKeys._();<br>  static final onboardKeys = _OnboardKeys._();<br>  static final homeKeys = _HomeKeys._();<br>  static final generalKeys = _GeneralKeys._();<br>}</pre><p>To manage our keys effectively, we use a single ApplicationKeys class. This class acts as a central hub for all test keys in the application. However, instead of putting every key into one giant file, we organize them by feature using Dart&#39;s part and part of directives.</p><p>Here’s how it works:</p><ol><li>Each feature has its own _keys.dart file (e.g., _login_keys.dart).</li><li>The main application_keys.dart file uses the part directive to include these smaller files.</li></ol><p>This structure gives us the best of both worlds: a single, easy-to-use ApplicationKeys class to access any key, while keeping our code clean and organized by feature.</p><pre>typedef K = ApplicationKeys;<br>/// Usage: K.splashKeys.view</pre><p><em>This is another useful way to organize your Keys class for easy use.</em></p><h4>Architecture: View</h4><p>Now, let’s add our keys to the view components. Every Flutter widget has a key parameter, so we will assign our predefined keys to their corresponding widgets. Let&#39;s look at the Onboarding View as an example of this usage.</p><p>Here are the keys for our view:</p><pre>final class _OnboardKeys {<br>  _OnboardKeys._();<br><br>  final Key fullImage = const Key(&#39;full_image&#39;);<br>  final Key skipButton = const Key(&#39;skip_button&#39;);<br>  final Key view = const Key(&#39;onboard_view&#39;);<br>}</pre><p>Now, let’s implement these keys in our view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2050fddc818dd3b5eb0da094830797/href">https://medium.com/media/2b2050fddc818dd3b5eb0da094830797/href</a></iframe><p>As you can see, this usage is very easy. I just assign the key to the widget’s key parameter. That&#39;s it! The widget can now be found directly with this approach.</p><h4><strong>Architecture: Flow</strong></h4><p>Our application is almost ready to test. The keys are defined, and the widgets are ready. Now, we just need to create the “flow” for testing our application. Before we start, let’s implement our chain design.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8626efe47aaf1deef776d0537ba08d01/href">https://medium.com/media/8626efe47aaf1deef776d0537ba08d01/href</a></iframe><p>We will use a base class that helps with all of our test cases. This interface helps to create and continue the test flow. Let’s explain how this works.</p><ul><li><strong>PatrolIntegrationTester:</strong> This is the test driver (we&#39;ll call it $) that helps us interact with UI components.</li><li><strong>nextScenario:</strong> A property that holds the next test flow to run after the current one is complete.</li><li><strong>run():</strong> The main logic for the current test flow is executed here.</li><li><strong>waitAndCheckValid():</strong> Before a flow starts, this method checks if it can run. (For example, the onboard flow only works on the first-time app installation).</li><li><strong>startFlow():</strong> This method starts and logs the current flow.</li></ul><p>Every test flow must extend this base class and implement its methods. Now, let’s implement the Onboarding View test with this approach.</p><h4><strong>Onboarding Test: A Real-World Example</strong></h4><p>Now, it’s time to use our Flow architecture in a real example. We will start with the Onboarding page test, which is the first entry point of the application.</p><p>The main message of this page is: “Welcome and Do not forget your history.” The UI is simple: it has an image and a close button.</p><p>Here is the test flow that helps us test this page:</p><pre><br>final class OnboardTest extends BaseTestScenario {<br>  OnboardTest(super.$, {required super.next});<br><br>  @override<br>  Future&lt;bool&gt; run() async {<br>    await $.pumpAndSettle();<br>    final isFullImageVisible = $(K.onboardKeys.fullImage).exists;<br>    expect(isFullImageVisible, isTrue, reason: &#39;full image is not visible&#39;);<br><br>    final isSkipButtonVisible = $(K.onboardKeys.skipButton).exists;<br>    expect(isSkipButtonVisible, isTrue, reason: &#39;skip button is not visible&#39;);<br>    await $(K.onboardKeys.skipButton).tap(<br>      settleTimeout: const Duration(milliseconds: 100),<br>      settlePolicy: SettlePolicy.noSettle,<br>      visibleTimeout: const Duration(milliseconds: 100),<br>    );<br>    return true;<br>  }<br><br>  @override<br>  Future&lt;bool&gt; waitAndCheckValid() async {<br>    if (AppHelper.isOnboardCompleted()) {<br>      return false;<br>    }<br>    await $(K.onboardKeys.view).waitUntilVisible();<br>    return $(K.onboardKeys.view).exists;<br>  }<br>}</pre><p><strong>Explaining the Flow Logic</strong></p><p>The flow starts after the waitAndCheckValid() method works. This method decides if the flow should continue or not. If it returns false, it means the flow does not need to run, and the test runner can move to the next flow or finish.</p><p>In our case, the Onboarding page is only shown once in the application, so its test flow should also run only once. The waitAndCheckValid() method checks this condition and makes the decision.</p><p>If waitAndCheckValid() returns true, the main flow starts with the run() method. My validation checklist for this method is:</p><ul><li>Check if the full-screen image is visible.</li><li>Check if the close button is visible.</li><li>Tap the “skip” button to continue to the next step.</li></ul><p><strong>Linking the Flows Together</strong></p><p>Now it’s time to link the flows together. I have two more scenarios ready: a HomeScenario and a SplashScenario. As we talked about at the top of this article, we will create a chain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1ae1e218c3bdc6c647be3cea631a414/href">https://medium.com/media/e1ae1e218c3bdc6c647be3cea631a414/href</a></iframe><p>The chain is now ready. The test will begin when we call the startFlow() method on the <em>first</em> scenario in our chain. Here is how the logic will work:</p><ol><li><strong>It starts with the </strong><strong>OnboardingScenario.</strong> The test runner checks: Is the Onboarding flow valid?</li></ol><ul><li><strong>Yes:</strong> It runs the Onboarding test. When finished, it moves to the next flow.</li><li><strong>No:</strong> It skips the Onboarding test and immediately moves to the next flow.</li></ul><p>2<strong>. Next is the </strong><strong>SplashScenario.</strong> The runner checks: Is the Splash flow valid? (e.g., is the Lottie animation visible?).</p><ul><li><strong>Yes:</strong> It runs the Splash test.</li><li><strong>No:</strong> It skips and moves on.</li></ul><p>3.<strong> Finally, the </strong><strong>HomeScenario.</strong> The runner checks: Is the Home flow valid?</p><ul><li><strong>Yes:</strong> It runs the Home test.</li><li><strong>No:</strong> The test finishes.</li></ul><p>After the entire flow starts and runs until it’s complete, here are my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxURdcVk9U_ZQkGRRNMYgw.png" /><figcaption>There is result of the my test flow</figcaption></figure><h4><strong>Extra Scripts for Easier Local Testing</strong></h4><p>When you run the patrol test command, it can sometimes be confusing if you have multiple devices connected (e.g., a real device, an emulator, an iPad).</p><p>I often want to run tests only on my Android emulator. This script helps to find the running emulator and executes the tests on it directly.</p><p><strong>Script for IOS Emulator:</strong></p><pre>#!/bin/bash<br><br># Get device ID from iPhone line in patrol devices output<br>booted_device_id=$(patrol devices | grep -i &#39;iPhone&#39; | grep -oE &#39;[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}&#39;)<br><br># If no device is found, exit with error<br>if [ -z &quot;$booted_device_id&quot; ]; then<br>  echo &quot;iPhone emulator bulunamadı. Lütfen bir iOS emulator başlatın.&quot;<br>  exit 1<br>fi<br><br>echo &quot;iPhone emulator bulundu: $booted_device_id&quot;<br><br># Run patrol command<br>patrol develop --target integration_test/start_test.dart --device &quot;$booted_device_id&quot; --flavor development</pre><p><strong>Script for Android Emulator:</strong></p><pre>#!/bin/bash<br><br># Get device ID from emulator line in patrol devices output<br>booted_device_id=$(patrol devices | grep -i &#39;emulator&#39; | awk &#39;{print $NF}&#39; | tr -d &#39;()&#39;)<br><br># If no device is found, exit with error<br>if [ -z &quot;$booted_device_id&quot; ]; then<br>  echo &quot;Android emulator bulunamadı. Lütfen bir Android emulator başlatın.&quot;<br>  exit 1<br>fi<br><br>echo &quot;Android emulator bulundu: $booted_device_id&quot;<br><br># Run patrol command<br>patrol develop --target integration_test/start_test.dart --device &quot;$booted_device_id&quot; --flavor development</pre><h4><strong>Let’s Test a Native Feature</strong></h4><p>Our application shows a native notification permission dialog on the home page. Our test needs to tap the “Approve” or “Deny” buttons on this dialog. Patrol can handle this easily.</p><pre> final isPermissionDialogVisible =<br>        await tester.native.isPermissionDialogVisible();<br>    if (isPermissionDialogVisible) {<br>      await tester.native.denyPermission();<br>      await tester.pumpAndSettle(duration: const Duration(seconds: 1));<br>    }</pre><p>This feature is very useful for my application, and I can handle many things with it. You can find other native features in the Patrol documentation.</p><pre>/// https://patrol.leancode.co/~2372/native/overview<br>void main() {<br>  patrolTest(&#39;demo&#39;, (PatrolIntegrationTester $) async {<br>    await $.pumpWidgetAndSettle(AwesomeApp());<br>    // prepare network conditions<br>    await $.native.enableCellular();<br>    await $.native.disableWifi();<br><br>    // toggle system theme<br>    await $.native.enableDarkMode();<br><br>    // handle native location permission request dialog<br>    await $.native.selectFineLocation();<br>    await $.native.grantPermissionWhenInUse();<br><br>    // tap on the first notification<br>    await $.native.openNotifications();<br>    await $.native.tapOnNotificationByIndex(0);<br>  });<br>}</pre><p>That’s all for the coding part. The flow we created will work on your local environment directly. But what about running tests in a cloud environment? That can also be done easily with Patrol commands.</p><h4><strong>Cloud Testing with Firebase Test Lab &amp; GitHub Actions</strong></h4><p>Our test flows need to be tested on many different devices. Firebase Test Lab offers a free tier for testing on several devices directly. I prefer to implement this workflow using the command-line interface (CLI).</p><p>For more details, you can check the official documentation</p><p><a href="https://firebase.google.com/docs/test-lab">Firebase Test Lab</a></p><p>Before using Test Lab with our Patrol test flow, we need to call the build command.</p><pre>patrol build android --target integration_test/start_test.dart  --flavor development</pre><p>This creates the necessary APKs for uploading to the server. The following script can be used for building the APKs and sending them to Test Lab.</p><pre>#!/bin/bash<br><br>gcloud firebase test android run \<br>  --type instrumentation \<br>  --use-orchestrator \<br>  --app build/app/outputs/apk/development/debug/app-development-debug.apk \<br>  --test build/app/outputs/apk/androidTest/development/debug/app-development-debug-androidTest.apk \<br>  --timeout 1m \<br>  --device model=MediumPhone.arm,version=34,locale=en,orientation=portrait \<br>  --record-video \<br>  --environment-variables=clearPackageData=true,IS_TEST_LAB=true \<br>  --project YOUR-PROJECT-NAME \<br>  --results-dir=test_results \<br>  --results-history-name=instrumentation_tests</pre><p><strong>Here’s what it does step-by-step:</strong></p><ul><li>gcloud firebase test android run: Tells Google to run your Android tests on Firebase.</li><li>--app ... &amp; --test ...: It uploads your application&#39;s APK and the test APK that contains your test code.</li><li>--type instrumentation: Specifies that you are running standard UI tests (like Espresso).</li><li>--use-orchestrator: Runs each test in isolation to prevent them from affecting each other, ensuring clean results.</li><li>--device ...: Defines the exact virtual device for the test: a medium-sized phone with Android 14, set to English.</li><li>--timeout 1m: Sets a 1-minute time limit for the entire test run. If it takes longer, it will be canceled.</li><li>--record-video: Records a video of the screen during the test, which is very helpful for debugging failed tests.</li><li>--project ... &amp; --results-dir ...: Saves all the test results (like logs and the video) into a specific folder (test_results) in your Google Cloud project.</li><li>--results-history-name ...: Groups the results under the name instrumentation_tests in the Firebase console, making it easy to see the test history over time.</li></ul><p>The result looks like this from the website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weAtq4VIkD8mHuZt0ibHdw.png" /><figcaption>There is result my other apps.</figcaption></figure><p>Here is the complete workflow file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa6763ff25797d6bef3907e72a6770d7/href">https://medium.com/media/aa6763ff25797d6bef3907e72a6770d7/href</a></iframe><h4><strong>Final Thoughts</strong></h4><p>Phew, that was quite a journey! This architecture, Patrol, and of course, UI testing in general, have become very important in recent years. I hope you can implement these techniques in your own projects and relax a little more before every release :)</p><p>I also have a similar video in Turkish on my YouTube channel:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyOFbRwbVabE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyOFbRwbVabE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyOFbRwbVabE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/491b3d28993ac088b791d4205a69c4c8/href">https://medium.com/media/491b3d28993ac088b791d4205a69c4c8/href</a></iframe><p>Thank you for reading! <br><strong>See you in the next article!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e92923cfa49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide: Flutter Architecture Template — II]]></title>
            <link>https://medium.com/flutter-community/the-ultimate-guide-flutter-architecture-template-ii-f86f9aa222e6?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86f9aa222e6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dart-language]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 09:47:05 GMT</pubDate>
            <atom:updated>2025-02-10T15:17:47.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ultimate Guide: Flutter Architecture Template — II</h3><p>Many years ago, I created an end-to-end application development template using Flutter as <a href="https://vb10.dev/#/en-us/">Flutter Architecture Template</a>. Currently, I’m publishing a new series with better ideas and implementations. Let’s learn together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEZEGyBJ9bRWLOGFctT8Ow.png" /></figure><p>This article helps you understand how to build a custom business application. It is important to consider an important point when working on a large project or enterprise. I can actually discuss this topic in more detail, but for now I’d like to build this architecture from zero to hero. Come on, let’s do this!</p><h4>Architecture template..</h4><p>Yes, that’s my main goal. Actually, I have two goals. The first is to advance my coding skills (more structural); the second is to create a template. Architecture coding provides a better coding environment, solution, testing, modularization, etc. Additionally, templates will encourage team collaboration, differentiation, and many more things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBJHzSdsRCHK8WTclObuQw.png" /><figcaption><a href="https://vb10.dev/#/en-us/">https://vb10.dev/#/en-us/</a></figcaption></figure><p>That sounds good, right?</p><p>-Yes, but remember this is not suitable for only one person or a side project. Teamwork is better for understanding and implementing this.</p><p>How many components are in this article?</p><p>In this project, core ideas have been created for an advanced mobile project. The following are included:</p><p>1.Create Project with Structure Folders<br>2.Vscode extensions with Pubspec Details<br>3.Localization support<br>4.Project requirements while app staring and Environment management<br>5.Theme &amp; Code Generation<br>6.Navigation structure, Scripts for development, <a href="http://3.party/">3.party</a> package effective usage<br>7.Kartal package, Responsive design, Custom widget design<br>8.Stateless widget, Stateful widget and Mixin Usage<br> 9.Network Manager with Vexana and GetIt Manager (dependency injection)<br>10.State Management with BLoC Package<br>11.Cache Operation with Hive<br>12.Unit test, Integration test, Widget test<br>13.Pigeon, Fastlane, App Screen generator.</p><p>As you can see, we are waiting for a difficult time today, but after reading this article you will be ready to make a good architecture approach, think, and code with confidence. Let’s get started.</p><blockquote>I have created a video about this article. Check out my video</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMyJbJCdwWp0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMyJbJCdwWp0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMyJbJCdwWp0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d56e2139be9316d960fcd92cfba3389/href">https://medium.com/media/0d56e2139be9316d960fcd92cfba3389/href</a></iframe><h3>1. Project Structure</h3><p>When developing an architecture, this is the main idea. It provides a place to write code. This will help organize the code base in the project. When new feature requests come, keep the related files in the same folder as you knew when they would be added to your project.</p><p>There can be more reasons, but the thought is quite important. So what is my solution?</p><p>A module-based solution based on feature-based development. There is a separate most important logic for example. Databases/networks, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Qo_G-M7l8dnSsxA" /><figcaption>Projet General Structre</figcaption></figure><p>You can find every request here or you can find a chance to upgrade. It is for this reason that there is a good structure. It is always possible to add more solutions.</p><p>Also you can check this structure from <a href="https://github.com/VB10/architecture_template_v2">my repository.</a></p><h3>2.Code Settings, Extension and Snippet</h3><p>I use many extensions for this architecture to help me code, debug, and develop quickly. I configure my VSCode settings for better coding on the other hand. You can find and install directly with this script:<br>- <strong>setup_extension.sh</strong> -&gt; <a href="https://gist.github.com/VB10/2050d098dbaae1e591dee35f13ffa3f5">https://gist.github.com/VB10/2050d098dbaae1e591dee35f13ffa3f5</a></p><p>After extension installed let’s config!<br>It helps with styling, fixing, and general maintenances. The following is my general settings json file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/657cfd1d6b261a62585c4baa1ab5b51b/href">https://medium.com/media/657cfd1d6b261a62585c4baa1ab5b51b/href</a></iframe><p>Last part is snippet. I create many snippet for speed up coding. For example I create “hwaFsm” it is mean “HardwareAndro Flutter statefull Model. The other snippets:</p><ul><li>Magic number (hwaMagicNumber)</li><li>Singleton Eager (hwaEager)</li><li>Base View Model (hwaBaseViewModel)</li><li>Base View (hwaBaseView)</li><li>Base Model (hwaBaseModel)</li><li>Base Test (hwaTest)</li><li>Hwa Extension (hwaExtension)</li><li>Flutter from json factory (hwaflutterFromJson)</li><li>Flutter change loading (fcl)</li><li>Flutter scaffold base (hwaFSM)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06093568d006de9ff7695b924a1e98c8/href">https://medium.com/media/06093568d006de9ff7695b924a1e98c8/href</a></iframe><p>Regarding pubspec.yaml, on the other hand. You need to add many packages while developing a project. In this case, it’s all about the “annotation”. After adding many pakages, it is hard to read what is point of usage. Annotation will help to sum of similar item.<br>For example:</p><pre>#firebase<br>firebase_messaging: 4.5.0<br>firebase_core: 3.1.0</pre><h3>3.<strong>Localization support</strong></h3><p>In the last year, localization has become very important for mobile apps. There’s localization in almost every application. So I’m going to show you how to add localization.</p><p>The language feature will be made by the localization manager. On the other hand, you have to generate the key for localization. I’m using the “<a href="https://pub.dev/packages/easy_localization">easy_localization</a>” package. This package has been very stable for me for a long time.</p><pre>{<br>  &quot;home&quot;: {<br>    &quot;title&quot;: &quot;Home Page&quot;<br>  },<br>  &quot;general&quot;: {<br>    &quot;button&quot;: {<br>      &quot;save&quot;: &quot;Save {}&quot;<br>    }<br>  }<br>}</pre><p>Here’s an example of localization. Defining your key and value in JSON is the first step. It’s all about the key. If you want a dynamic value, you can use an argument. You want the button to say “Save 10000.”. Use [count] with your key.</p><p>You can use this class to define your language support and change the language in the app. Make sure you add a translations folder and json file before using this class.</p><p>Translations: — <strong>asset/translations</strong></p><p>Finally, it is necessary to work with the build runner to generate the code. In the next section, I will explain how code is generated. This time just call this script before using value: (You can find this script in repository as a lang.sh)</p><pre>#!/bin/bash<br><br>dart run easy_localization:generate  -O lib/product/init/language -f keys -o locale_keys.g.dart --source-dir asset/translations</pre><blockquote>This package must be installed before it can be used. The first one is <a href="https://pub.dev/packages/build_runner">build_runner</a>, and the second is <a href="https://pub.dev/packages/easy_localization_generator">localization generator</a>.</blockquote><p>Localization is ready for use. Use LocaleKeys to call for example:</p><pre>Text(LocaleKeys.home_title.tr());</pre><p>Finally, we are almost ready to use our localization support, the last step is to manage multiple languages within our app. This class will help you with everything related to localization. The following are our needs:<br>-Path to the file<br>-Item support<br>-General update on the project</p><pre>final class ProductLocalization extends EasyLocalization {<br>  /// ProductLocalization need to [child] for a wrap locale item<br>  ProductLocalization({<br>    required super.child,<br>    super.key,<br>  }) : super(<br>          supportedLocales: _supportedItems,<br>          path: _translationPath,<br>          useOnlyLangCode: true,<br>        );<br><br>  static final List&lt;Locale&gt; _supportedItems = [<br>    Locales.tr.locale,<br>    Locales.en.locale,<br>  ];<br><br>  static const String _translationPath = &#39;asset/translations&#39;;<br><br>  /// Change project language by using [Locales]<br>  static Future&lt;void&gt; updateLanguage({<br>    required BuildContext context,<br>    required Locales value,<br>  }) =&gt;<br>      context.setLocale(value.locale);<br>}</pre><p>You can use this class for general usage localization. (Before use this solution do not forget the requirements for <a href="https://pub.dev/packages/easy_localization">easy localization</a> )</p><h3>4.Project requirements while app staring and Environment management</h3><p>Requirements are the starting point of the application. Before running the application, many things can be checked. The permission to access the internet, the permission to use a camera, the permission to connect to a database, etc.</p><p>Here’s how to handle this situation.</p><pre>final class ApplicationInitialize {<br>  /// project basic required initialize<br>  Future&lt;void&gt; make() async {<br>    WidgetsFlutterBinding.ensureInitialized();<br><br>    await runZonedGuarded&lt;Future&lt;void&gt;&gt;(<br>      _initialize,<br>      (error, stack) {<br>        Logger().e(error);<br>      },<br>    );<br>  }<br><br>  /// This method is used to initialize the application process<br>  Future&lt;void&gt; _initialize() async {<br>    await EasyLocalization.ensureInitialized();<br>    EasyLocalization.logger.enableLevels = [LevelMessages.error];<br>    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);<br>    // TODO: Splash<br>    await DeviceUtility.instance.initPackageInfo();<br><br>    FlutterError.onError = (details) {<br>      /// crashlytics log insert here<br>      /// custom service or custom logger insert here<br>      /// Todo: add custom logger<br>      Logger().e(details.exceptionAsString());<br>    };<br><br>    // Dependency initialize<br>    // envied<br><br>    _productEnvironmentWithContainer();<br><br>    await ProductStateItems.productCache.init();<br>  }<br><br>  /// DO NOT CHANGE THIS METHOD<br>  void _productEnvironmentWithContainer() {<br>    AppEnvironment.general();<br><br>    /// It must be call after [AppEnvironment.general()]<br>    ProductContainer.setup();<br>  }<br>}</pre><p>During app startup, this class manages all requirements. This manager is called in the main file as follows:</p><pre>Future&lt;void&gt; main() async {<br>  await ApplicationInitialize().make();<br>  runApp(ProductLocalization(child: const StateInitialize(child: _MyApp())));<br>}</pre><p>The management of the environment is very important for mobile applications. There are many possible values, such as changing the base URL, changing the API key, etc. It’s how to keep this in the project that’s the problem.</p><p>The Envied package is very useful in this situation. With obfuscate, you can manage environment variables. In this case, it isn’t very secure, but it’s very useful.Check the implementation when the application starts.</p><blockquote>The <strong>Envied</strong> Package can be found at <a href="https://pub.dev/packages/envied">https://pub.dev/packages/envied</a><br>&lt; Don’t forget to add envied generator for making a code from .env file &gt;</blockquote><p>This package should be implemented in this project:</p><ul><li>Add a .env file to .gitignore by creating a new file</li><li>Enter your base URL and API key.</li><li>Create a dev_env.dart for storing environment variables.</li><li>Declare your envied path for top of class and add your variable like “static const baseUrl = \_DevEnv.baseUrl;”</li><li>Run the builder to generate the code from the environment file.</li></ul><p>My envied file is look like this.</p><pre>BASE_URL=https://api.sample.com</pre><p>The other hand is dev_env.dart file.</p><pre>import &#39;package:envied/envied.dart&#39;;<br>part &#39;dev_env.g.dart&#39;;<br>@Envied(path: &#39;.env&#39;)<br>class DevEnv {<br>@EnviedField(varName: &#39;BASE_URL&#39;)<br>static const baseUrl = _DevEnv.baseUrl;<br>}</pre><p>That’s all I have to say. You can now use your env variable with secure for all your variables. As a reminder, you will learn to generate codes for best usage in the next section, so you can find the right code.</p><p>My general code generation is complete in another submodule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*63HZW5oBAG0_IvlkKGs2Ng.png" /></figure><h3>5.<strong>Theme &amp; Code Generation</strong></h3><blockquote>The project supports modular design. Create a flutter library project for managing modular designs.</blockquote><blockquote>flutter create --template=package your_package_name</blockquote><h4>1.Code generation</h4><p>The most important thing for a project is code generation. This helps to make a code easier, more readable, and easier to understand. The tool is very useful for projects. I am using many packages for code generation. An asset generator makes it easier to create an asset. For example, an image, a lottie, a json, a font, etc. Envied gen manages environments securely. We will manage this code generation algorithm from the new module within this article. Implementing and managing it is very simple.</p><p>“Gen” is the name of the new module, and it is very easy to implement and manage.</p><p>There are three submodules in this folder.</p><p>1- Asset Gen -&gt; <a href="https://pub.dev/packages/flutter_gen">https://pub.dev/packages/flutter_gen</a><br>2- Envied Gen -&gt; <a href="https://pub.dev/packages/envied_generator">https://pub.dev/packages/envied_generator</a><br>3- Model generation -&gt; <a href="https://pub.dev/packages/json_serializable">https://pub.dev/packages/json_serializable</a></p><h4>1.1- Asset Gen</h4><p>Asset generation will use lottie, svg, fonts, images, etc. Using the flutter_gen package, it works. It is very easy to use and very powerful. In pubspec.yaml, the package must be declared.</p><pre>flutter_gen:<br>  output: lib/src/asset/<br>  integrations:<br>    lottie: true<br>    flutter_svg: true<br><br>  colors:<br>    inputs:<br>      - assets/color/colors.xml</pre><p>After that you need to run build runner for generating a code.</p><pre>flutter pub run build_runner build</pre><p>Your asset generated. Just call Asset file with relative path.</p><pre>ColoredBox(color: Assets.color.black)<br>/// package: gen mean that find the asses in sub module<br>Assets.lottie.animZombieda.lottie(package:&quot;gen&quot;)<br>Assets.images.imageName.image(package:&quot;gen&quot;)</pre><h4>1.2- Envied Gen</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*fbxqdU1lUdlpW-S-NWEJKw.png" /></figure><p>Envied Gen is used for managing environments with security. This is covered in the previous section. You can find more details about this here. This is the module I just moved to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd069ff379106fb92851b96649d17f73/href">https://medium.com/media/fd069ff379106fb92851b96649d17f73/href</a></iframe><h4>1.3- Model Generation</h4><p>Model generation is for model. It is very useful for model. I’m using json_serializable package for this case. This package is very easy to use and it is very powerful. The package needs to declare in the pubspec.yaml file.</p><pre>@JsonSerializable()<br>class User extends INetworkModel&lt;User&gt; with EquatableMixin {<br>  User({this.userId, this.id, this.title, this.body});<br><br>  /// Get user from json<br>  factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$UserFromJson(json);<br>  final int? userId;<br>  final int? id;<br>  final String? title;<br>  final String? body;<br>..</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*8qzTeZTxtI0zMfZun6_QPQ.png" /></figure><p>The generation almost complete this project. This time project can access for generation module from index file.</p><pre>export &#39;asset/index.dart&#39;;<br>export &#39;environment/index.dart&#39;;<br>export &#39;model/index.dart&#39;;</pre><h4>2.Theme</h4><p>The theme of this article is the most important thing. I’ll create a theme with “Theme Manager”, which is very easy to use. You can use this to make a theme light or dark. Theme builder can be used from material. There is also a text theme class for helping text themes. I wrote a good article about this. You can check it out. The main idea of the theme is</p><p>How to make a color etc. from mainly” and “how to implement a new theme easily”.</p><p><a href="https://medium.com/flutter-community/flutter-build-theme-with-abstract-factory-method-e07df8f730e2">Flutter Build Theme with Abstract Factory Method</a></p><p>A CustomTheme is the main idea behind the theme structure. Making multiple schemes like light and dark is made easier with it.</p><pre>abstract class CustomTheme {<br>  ThemeData get themeData;<br><br>  FloatingActionButtonThemeData get floatingActionButtonThemeData;<br>}</pre><p>After that you can implement your theme like this.</p><pre>final class CustomLightTheme implements CustomTheme {<br>  @override<br>  ThemeData get themeData =&gt; ThemeData(<br>        useMaterial3: true,<br>        fontFamily: GoogleFonts.roboto().fontFamily,<br>        colorScheme: CustomColorScheme.lightColorScheme,<br>        floatingActionButtonTheme: floatingActionButtonThemeData,<br>      );<br><br>  @override<br>  FloatingActionButtonThemeData get floatingActionButtonThemeData =&gt;<br>      const FloatingActionButtonThemeData();<br>}</pre><p>Here is a file to help you make a theme based on font family, color scheme, etc. Alternatively, you can create a custom theme like FloatingActionButtonThemeData. It needs to be called from inside a MaterialApp.</p><pre> Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      routerConfig: _appRouter.config(),<br>      builder: CustomResponsive.build,<br>      theme: CustomLightTheme().themeData,<br>      darkTheme: CustomDarkTheme().themeData,<br>      themeMode: context.watch&lt;ProductViewModel&gt;().state.themeMode,<br>      localizationsDelegates: context.localizationDelegates,<br>      supportedLocales: context.supportedLocales,<br>      locale: context.locale,<br>    );<br>  }</pre><p>The following example shows how to use a color from colorScheme.</p><pre>context.general.colorScheme.primary (this estension coming from kartal package)</pre><p>During the writing of code, my package contains many extensions for simplifying the process. Check out my kartal package for more details:</p><p><a href="https://pub.dev/packages/kartal">kartal | Flutter package</a></p><h3><strong>6.Navigation structure, Scripts for helping development, 3.party package best usage</strong></h3><p>Using this module, you can create a general structure for your project and integrate it with 3rd-party scripts and other tools.</p><h4><strong>Scripts for helping development</strong></h4><p>While developing like this bigger project, I need to make a script for helping development. I’ll show you how to make a script for helping development. These scripts are very useful for development.</p><p>Making a script will be useful while developing such a big project. Here’s how to make a script to help development. It is very useful to have scripts like these for development purposes.</p><p>The first script is “<strong>full clean</strong>”. In most cases, it helps to clean up the entire project when a package needs to be updated, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c44e13f0b9ce98f9b8049068af499a56/href">https://medium.com/media/c44e13f0b9ce98f9b8049068af499a56/href</a></iframe><p>The other script is called “lang sh”. In addition, it helps create language classes after adding a new key.</p><pre>#!/bin/bash<br><br>flutter pub run easy_localization:generate  -O lib/product/init/language -f keys -o locale_keys.g.dart --source-dir asset/translations</pre><p>Here are a couple of ready-to-use scripts:</p><ul><li>build.sh =&gt; It’s run build runner</li><li>clean.sh =&gt; It’s clean your main project (flutter, ios clean)</li><li>icon_build.sh =&gt; It’s make a icon for android and ios</li><li>ios_clean.sh =&gt; It’s clean a ios build and pod file</li><li>android_build.sh =&gt; It will make apk or app bundle</li></ul><p>There are scripts in the root scripts folder. You can find it in the repository.</p><h4><strong>Navigation structure</strong></h4><p>Navigation is the main concept. Mobile applications require it very much. Let me show you how to make a navigation structure. For this case, I am using the <a href="https://pub.dev/packages/auto_route">auto_route</a> package. It is a very powerful and easy-to-use package. It is especially useful when managing a route with auto-generate. There are many navigation features in the Auto Router package. In this project, let’s implement this package.</p><p>First need to install the package to your project:</p><pre>dependencies:<br> auto_route: [latest-version]<br><br>dev_dependencies:<br> auto_route_generator: [latest-version]<br> build_runner:</pre><p>With the app router file, you can create a route with auto-generation. Depending on how many pages you have, you can add this flow:</p><p>First add ‘@RoutePage()’ annotain in your realated pages.</p><pre>// Home View<br>@RoutePage()<br>final class HomeView extends StatefulWidget {<br>  const HomeView({super.key});<br><br>  @override<br>  State&lt;HomeView&gt; createState() =&gt; _HomeViewState();<br>}<br><br>/// Home Detail View<br>@RoutePage()<br>final class HomeDetailView extends StatelessWidget {<br>  const HomeDetailView({required this.id, super.key});<br>  final String id;<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Home Detail View&#39;),<br>      ),<br>      body: Center(<br>        child: Text(&#39;Home Detail View $id&#39;),<br>      ),<br>    );<br>  }<br>}</pre><p>Add these pages to the app router. Your root navigation structure is created by it.</p><pre>part &#39;app_router.gr.dart&#39;;<br><br>@AutoRouterConfig(replaceInRouteName: AppRouter._replaceRouteName)<br><br>/// Project router information class<br>final class AppRouter extends RootStackRouter {<br>  static const _replaceRouteName = &#39;View,Route&#39;;<br>  @override<br>  List&lt;AutoRoute&gt; get routes =&gt; [<br>        AutoRoute(page: HomeRoute.page, initial: true),<br>        AutoRoute(page: HomeDetailRoute.page),<br>      ];<br>}</pre><p>After this configuration call your build runner, package will create auto route requirements for navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*q3iV44BwrFJWaXlfYDmd5g.png" /></figure><p>As a last point, the app router needs to be implemented in the material app. Once this is done, you can use auto router everywhere.</p><pre>final class _MyApp extends StatelessWidget {<br>  const _MyApp();<br>  static final _appRouter = AppRouter();<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      routerConfig: _appRouter.config(),<br>    );<br>  }<br>}</pre><p>The module is almost complete. As a result of this implementation, you can use it like this. You have many navigation options, such as push, pop, replace, etc., with context.router. More detail <a href="https://pub.dev/packages/auto_route#navigating-between-screens">https://pub.dev/packages/auto_route#navigating-between-screens</a></p><p>And it is sample usage from there:</p><pre> context.router.push(HomeDetailRoute(id: user.userId.toString()));</pre><h4>Bonus:</h4><p>Sometimes, code generation takes a long time for larger projects. It is possible to customize your build yaml for only a specific file. In this case, I only need to work on auto_route_gen for the view file. For generating page instances, there is only one view file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1ce19ffd1685afd06427359c9269291/href">https://medium.com/media/e1ce19ffd1685afd06427359c9269291/href</a></iframe><h4><strong>3.party package best usage</strong></h4><p>Many projects use third-party packages. Using this package in the future is very important. Here’s how to make the most of this package. I have been using <a href="https://pub.dev/packages/cached_network_image">Cached network</a> image package until now. It is very useful for loading images. For this package, let’s make an example.</p><p>You must add a dependency to pubspec.yaml before installing this package.</p><pre>cached_network_image: ^latest_version</pre><p>As a next step, I will create a new module as a common. This will make it easier to use this package in the project. To use this package, I would like to create a new widget. It does not require any configuration of the package to work.</p><p>It just depends on my primitive class. In addition, it can be changed or improved every time without affecting my main project. I know my new widget cannot read or reach my cached network image in the main project.</p><pre>/// It will provide to image caching and image loading from network<br>final class CustomNetworkImage extends StatelessWidget {<br>  /// The line `const CustomNetworkImage({super.key});` is defining a constructor<br>  /// for the `CustomNetworkImage` class.<br>  const CustomNetworkImage({<br>    super.key,<br>    this.imageUrl,<br>    this.emptyWidget,<br>    this.memCache = const CustomMemCache(height: 200, width: 200),<br>    this.boxFit = BoxFit.cover,<br>    this.loadingWidget,<br>    this.size,<br>  });<br>}</pre><p>It’s a very simple one. There is no need to configure the package. My primitive class is all it depends on. MemCache is a memory cache used in core packages. It requires no extra configuration and can be used anywhere in the project with parameters.</p><blockquote>The main idea is to not give out any package source code to anyone. It only depends on my primitive class. This will make it easier to improve or change in the future.</blockquote><h3><strong>7. Kartal package, Responsive design, Custom widget design</strong></h3><p>I am developing my hand with the kartal package. Coding with extensions is made easier with this tool. The package contains many extensions of primitive or advanced types. Coders will find it very useful.</p><p>For examples:</p><pre>context.general.colorScheme.primary<br>context.sized.low (0.1 percent of screen size)<br>GlobalKey.rendererBox<br>List.ext.nullOrEmpty<br>&#39;https://medium.com/@vbacik-10&#39;.ext.launchUrl </pre><p>Here is more detail about this package:</p><p><a href="https://pub.dev/packages/kartal">kartal | Flutter package</a></p><h4><strong>Responsive design</strong></h4><p>Flutter grew up on mobile, tablet and web. For a project, responsive design is pretty important. For this case, I’m using the Responsive package. It is very easy to use and very powerful. In pubspec.yaml, the package must be declared.</p><pre>responsive_framework: ^latest_version</pre><p>This package is very useful for responsive design. There are many breakpoints for responsive design. The details can be found on pub.dev. <a href="https://pub.dev/packages/responsive_framework">https://pub.dev/packages/responsive_framework</a></p><p>Creating responsive design breakpoints requires a custom responsive class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16de77cded2bbc8bbdda7fcc36e45d86/href">https://medium.com/media/16de77cded2bbc8bbdda7fcc36e45d86/href</a></iframe><p>This class allows you to declare your breakpoints. You can easily make your project responsive after implementing it. If you make your project a single design for example Iphone 14, then you don’t need to worry about other screen sizes. All screen sizes will be responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bB6gF8N1MBSiFT0v6ZzJfQ.gif" /><figcaption><a href="https://gallery.codelessly.com/flutterwebsites/minimal/">Using this package as an example</a></figcaption></figure><h4><strong>Custom widget design</strong></h4><p>You will probably create new widgets many times. It is important to make widgets that are basic, useful, and expandable. Therefore, I will show you how to make a dialog component. Success_dialog is the name of my dialog. This widget shows a success message in a very basic way.</p><pre>final class SuccessDialog extends StatelessWidget {<br>  /// Constructor for dialog<br>  const SuccessDialog({required this.title, super.key});<br><br>  /// Title for the dialog<br>  final String title;<br><br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AlertDialog.adaptive(<br>      title: Text(title),<br>      actions: [<br>        IconButton(<br>          onPressed: () {<br>            Navigator.of(context).pop(true);<br>          },<br>          icon: const Icon(Icons.check),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>That’s the basic widget for version one. To display this dialog, I have to call the “ShowDialog” code everywhere. It is not good for quality, usability, and maintainability. A new function will be added as a show function.</p><pre>  /// Show the dialog for success<br>  /// This will always return [true]<br>  static Future&lt;bool&gt; show({<br>    required String title,<br>    required BuildContext context,<br>  }) async {<br>    await DialogBase.show&lt;bool&gt;(<br>      context: context,<br>      builder: (context) =&gt; SuccessDialog(title: title),<br>    );<br>    return true;<br>  }</pre><p>This alert can be used very easily by my team. The “SuccessDialog.show” function is called.</p><blockquote>When you close your widget, add a private constructor, so anyone can’t directly call it.</blockquote><h4><strong>8. Stateless widget, Stateful widget and Mixin Usage</strong></h4><p>Every flutter project is related to this topic. This is valuable for understanding your coding life. Here is an example of how to use it. Actually, I didn’t explain the core concept of these widgets. I’ll try to demonstrate how these widgets can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*5P2d5VpRti5uN7oK.png" /></figure><p>Here is a basic overview of this topic:<br><a href="https://docs.flutter.dev/ui/interactivity#stateful-and-stateless-widgets">https://docs.flutter.dev/ui/interactivity#stateful-and-stateless-widgets</a></p><p>The first point is that inheritance can be used for some widgets. Padding is the most common usage. It is probably used in every project. The idea is to make a padding widget class for standardizing the project.</p><pre>final class ProjectPadding extends EdgeInsets {<br>  const ProjectPadding._() : super.all(0);<br><br>  /// All Padding<br>  ///<br><br>  /// [ProjectPadding.allSmall] is 8<br>  const ProjectPadding.allSmall() : super.all(8);<br><br>  /// [ProjectPadding.allMedium] is 16<br>  const ProjectPadding.allMedium() : super.all(16);<br><br>  /// [ProjectPadding.allNormal] is 20<br>  const ProjectPadding.allNormal() : super.all(20);<br><br>  /// [ProjectPadding.allLarge] is 32<br>  const ProjectPadding.allLarge() : super.all(32);<br><br>  /// Symmetric<br>  /// Only left,right,bottom<br>}</pre><p>The purpose of this is to make the component usable for the project. There is no need to add an extra stateless widget for padding. This class can be used for padding. An example:</p><pre>Padding(<br>  padding: const ProjectPadding.allSmall(),<br>   ...</pre><p>Another example is a <strong>stateless</strong> widget. I am creating a widget that is a NormalButton. This is a simple button with a radius border.</p><pre>/// radius is 20<br>final class NormalButton extends StatelessWidget {<br>  const NormalButton({required this.title, required this.onPressed, super.key});<br><br>  /// title text<br>  final String title;<br><br>  /// button on pressed<br>  final VoidCallback onPressed;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return InkWell(<br>      /// todo:<br>      radius: ProjectRadius.normal.value,<br>      onTap: onPressed,<br>      child: Text(title),<br>    );<br>  }<br>}</pre><p>There are two parameters in the class. The first title is for showing a text. The second one is onPressed for a callback. We are trying to create a stateless widget. This makes a widget more reusable.</p><p>This is how you can make your sub widget. Sub widgets are based on this concept. The ProjectRadius is used for border radiuses. Radius is a basic enum.</p><pre>enum ProjectRadius {<br>  /// 8.<br>  small(8),<br><br>  /// 16.<br>  medium(16),<br><br>  /// 20.<br>  normal(20),<br><br>  /// 32.<br>  large(32);<br><br>  final double value;<br>  const ProjectRadius(this.value);<br>}</pre><p>Another example is a <strong>stateful</strong> widget. My widget is a CustomLoginButton. The button shows a loading state without any extra configuration.</p><pre>final class CustomLoginButton extends StatefulWidget {<br>  const CustomLoginButton({required this.onOperation, super.key});<br>  final AsyncValueGetter&lt;bool&gt; onOperation;<br>  @override<br>  State&lt;CustomLoginButton&gt; createState() =&gt; _CustomLoginButtonState();<br>}<br><br>class _CustomLoginButtonState extends State&lt;CustomLoginButton&gt;<br>    with MountedMixin, _CustomLoginButtonMixin {<br>  @override<br>  Widget build(BuildContext context) {<br>    return ValueListenableBuilder&lt;bool&gt;(<br>      valueListenable: _isLoadingNotifier,<br>      builder: (BuildContext context, bool value, Widget? child) {<br>        if (value) return const SizedBox();<br>        return NormalButton(<br>          title: &#39;Login&#39;,<br>          onPressed: () async {<br>            await _onPressed(context);<br>          },<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>I’m getting an async value from the widget parameter. It helps manage loading state while sending a request. You can use stateful widgets to perform any operation related to the UI screen.</p><p>The last point is <strong>mixin</strong>. In widgets, mixins help manage states. This widget is very useful for stateful widgets. Stateful or stateless widgets just display design code. In view code, you do not write any operations like button presses or service requests. Mixins can be written in. Maintainability is improved by keeping clean code.</p><pre>mixin _CustomLoginButtonMixin<br>    on MountedMixin&lt;CustomLoginButton&gt;, State&lt;CustomLoginButton&gt; {<br>  final ValueNotifier&lt;bool&gt; _isLoadingNotifier = ValueNotifier&lt;bool&gt;(false);<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _isLoadingNotifier.value = false;<br>  }<br><br>  @override<br>  void dispose() {<br>    super.dispose();<br>  }<br><br>  Future&lt;void&gt; _onPressed(BuildContext context) async {<br>    _isLoadingNotifier.value = true;<br>    final response = await widget.onOperation.call();<br>    await safeOperation(() async {<br>      if (response) Navigator.of(context).pop();<br>      _isLoadingNotifier.value = false;<br>    });<br>  }<br>}</pre><p>This mixin is only used in CustomLoginButton. Due to the fact that this is dependent on the CustomLoginButton State object. In addition, I have closed operations, verifiables, etc. if they are not needed. It is very helpful to use mixins and state classes for managing basic state information.</p><p>Ui issues can only be found in view classes, logic issues can be found in mixins.</p><p>There are some mixins that depend only on the view, and there are others that depend on the state. You need to use mountain check before every UI update, for instance. In this case, MountedMixin can be used.</p><pre>mixin MountedMixin&lt;T extends StatefulWidget&gt; on State&lt;T&gt; {<br>  Future&lt;void&gt; safeOperation(AsyncCallback callback) async {<br>    if (!mounted) return;<br>    await callback.call();<br>  }<br>}</pre><h3><strong>9. Network Manager with Vexana and GetIt Manager (Dependency injection)</strong></h3><p>The Vexana mine package for the network. I wrote this package with dio. It adds extra features for business life. For more information, please visit my pub.dev page.</p><p><a href="https://pub.dev/packages/vexana">vexana | Flutter package</a></p><p>This package has the following capabilities:</p><ul><li>Model of generic response</li><li>Refresh token mechanism</li><li>The caching process</li><li>Manage without a network connection</li><li>And other features, you can check my package from pub.dev.</li></ul><p>This package is pretty useful for enterprise projects. You can give a hint, issue, or PR at any time. Let’s implement this package for our project.</p><p>For project configuration, we need a custom network manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b985867b180e977d08a41f94fc2c6b9/href">https://medium.com/media/1b985867b180e977d08a41f94fc2c6b9/href</a></iframe><p>Here is a code explanation.</p><ul><li>NetworkManager&lt;EmptyModel&gt; is used in this project as a generic model. The EmptyModel can be defined as an error model based on your custom definition. Most of the time, many projects have the same response for any error, so this usage makes it easier to assess error models directly.</li><li>This constructor is used to define your root network manager class. It is common for projects to have some urls that define this layer. (When you have different base urls, you need to find a network manager)</li><li>The option contains a few requirements about general usage. A header (e.g.)</li><li>Last point for handling error situations when something goes wrong.</li></ul><pre>/// [EmptyModel] is a model class that is used to<br>/// general model or primitive type.<br>final class EmptyModel extends INetworkModel&lt;EmptyModel&gt; with EquatableMixin {<br>  /// [EmptyModel] constructor is used to create a new [EmptyModel]<br>  const EmptyModel({this.name});<br><br>  /// [name] is a getter method that returns the name of the model.<br>  final String? name;<br><br>  @override<br>  Map&lt;String, Object&gt;? toJson() =&gt; null;<br><br>  @override<br>  EmptyModel fromJson(Map&lt;String, dynamic&gt;? json) {<br>    return EmptyModel(name: json?[&#39;name&#39;] as String? ?? &#39;&#39;);<br>  }<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [name];<br>}</pre><p>Example usage of this network manager.</p><pre>final class LoginService extends AuthenticationOperation {<br>  LoginService(INetworkManager&lt;EmptyModel&gt; networkManager)<br>      : _networkManager = networkManager;<br><br>  final INetworkManager&lt;EmptyModel&gt; _networkManager;<br><br>  @override<br>  Future&lt;List&lt;User&gt;&gt; users() async {<br>    final response = await _networkManager.send&lt;User, List&lt;User&gt;&gt;(<br>      ProductServicePath.posts.value,<br>      parseModel: User(),<br>      method: RequestType.GET,<br>    );<br><br>    return response.data ?? [];<br>  }<br>}</pre><p>Login page is used by this service. I just said two types of parameters with a send method. The first is the response model. The second one is what is the type of response. In addition, the send request needs to have a path, a parse model, and a type.</p><p>Users returns a List&lt;User&gt;. Finally, you can get the response data.</p><p>There are two parameters in the response object:</p><p>- data: response data (List&lt;User&gt;)</p><p>- error: error model (IErrorModel&lt;EmptyModel&gt;)</p><p>This error model can be returned to the UI screen. An error message is displayed to the user as a result of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Bz_YYDQWO7LzpsPoEiHYg.png" /></figure><p>There are many projects that require the same object to be used everywhere. We have a ProductNetworkManager, for example. It is used for product service. You must create the same object if you want to use this network manager in another service. It is very difficult to maintain. In this case, we can use the GetIt package.</p><h4>Dependency Injection with GetIt</h4><p>Most of the time, this package is used to design service locators. You can use watch_it solution to listen to every change, and it also helps with a couple of integrations.</p><pre>final class ProductContainer {<br>  const ProductContainer._();<br>  static final _getIt = GetIt.I;<br><br>  /// Product core required items<br>  static void setup() {<br>    _getIt<br>      ..registerSingleton(ProductCache(cacheManager: HiveCacheManager()))<br>      ..registerSingleton&lt;ProductNetworkManager&gt;(ProductNetworkManager.base())<br>      ..registerLazySingleton&lt;ProductViewModel&gt;(<br>        ProductViewModel.new,<br>      );<br>  }<br>}</pre><p>It is in my core manager file. It helps manage dependency injections. This file allows you to register your service. It is not my idea to give a git link directly to the client. I’ll only display the items. We will be able to determine how many services are implemented in our project with the help of this class.</p><pre> final class ProductStateItems {<br>  const ProductStateItems._();<br><br>  static ProductNetworkManager get productNetworkManager =&gt;<br>      ProductContainer.read&lt;ProductNetworkManager&gt;();<br><br>  static ProductViewModel get productViewModel =&gt;<br>      ProductContainer.read&lt;ProductViewModel&gt;();<br><br>  static ProductCache get productCache =&gt; ProductContainer.read&lt;ProductCache&gt;();<br>}</pre><p>These parameters can be called in any service or view model. It helps manage dependency injections. I need to start the network service when I start the home view, for example. This one is mine to call.</p><pre>  @override<br>  void initState() {<br>    super.initState();<br>    _productNetworkErrorManager = ProductNetworkErrorManager(context);<br>    ProductStateItems.productNetworkManager.listenErrorState(<br>      onErrorStatus: _productNetworkErrorManager.handleError,<br>    );<br><br>    _homeViewModel = HomeViewModel(<br>      operationService: LoginService(productNetworkManager),<br>      userCacheOperation: ProductStateItems.productCache.userCacheOperation,<br>    );<br>  }</pre><p>Any service or view model can call these parameters. Dependency injections can be managed with it. When I start the home view, for example, I need to start the network service. I’m the one who gets to call this one.</p><h3><strong>10. State Management with BLoC Package</strong></h3><p>We have reached the golden point. A project’s state management is its most important component. For this case, I am using the BLoC package. My goal is to separate my state items from my UI screen. In view — view model, it helps manage a state. I’ll add a section showing my best methods for managing state in a project. It is very popular for me to use blocs.</p><p><a href="https://pub.dev/packages/bloc">bloc | Dart package</a></p><p>As an example:</p><ul><li>A BlocListener listens for changes in state.</li><li>BlocBuilder — It helps build UI screens.</li><li>BlocConsumer — It listens for state changes and builds UI screens.</li><li>BlocSelector — Selects a state value for a block.</li></ul><p>It is also very easy to test and manage state. I will add a base class for utility. As opposed to “bloc” usage, I prefer “cubit” usage. It is very easy to use.</p><p>Let’s take this case as an example. For the home page, I am creating a home view model.</p><pre>final class HomeViewModel extends BaseCubit&lt;HomeState&gt; {<br>  /// [AuthenticationOperation] service<br>  HomeViewModel({<br>    required AuthenticationOperation operationService,<br>    required HiveCacheOperation&lt;UserCacheModel&gt; userCacheOperation,<br>  })  : _authenticationOperationService = operationService,<br>        _userCacheOperation = userCacheOperation,<br>        super(const HomeState(isLoading: false));<br><br>        .... others...<br><br>}</pre><p>This is the beginning of my project. I am creating a view-model class to manage state. I am getting some verifiable results from using the business function. Another point state class for notifying state changes.</p><pre>final class HomeState extends Equatable {<br>  const HomeState({required this.isLoading, this.users});<br><br>  final bool isLoading;<br>  final List&lt;User&gt;? users;<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [isLoading, users];<br><br>  HomeState copyWith({bool? isLoading, List&lt;User&gt;? users}) {<br>    return HomeState(<br>      isLoading: isLoading ?? this.isLoading,<br>      users: users ?? this.users,<br>    );<br>  }<br>}</pre><p>This state class has many methods. This is how I prefer to use it. I am making only one state class immutable. By using Equtable, only the changed state will be notified. By using the copyWith method, you can copy a state with a new value. The design is basic, but it is pretty enough for a screen.</p><p>The last point is the BaseCubit class. The base cubit uses it to manage a state. For the whole project, you can add your logic.</p><pre>abstract class BaseCubit&lt;T extends Object&gt; extends Cubit&lt;T&gt; {<br>  BaseCubit(super.initialState);<br><br>  @override<br>  void emit(T state) {<br>    if (isClosed) return;<br>    super.emit(state);<br>  }<br>}</pre><p>When your state tries to emit, but the page is closed, the state won’t be emitted. This class can be used to implement your logic.</p><p>With this home view model, let’s make an example.</p><pre>  /// Get users<br>  Future&lt;void&gt; fetchUsers() async {<br>    CustomLogger.showError&lt;User&gt;(usersFromCache);<br>    final response = await _authenticationOperationService.users();<br>    _saveItems(response);<br>    emit(state.copyWith(users: response));<br>  }</pre><p>Data will be fetched from the backend and a state will be updated. The /_saveItems method makes a cache and a log. Let’s look at the home view model and how it should be handled.</p><pre>       const Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Expanded(<br>              child: _UserBlocList(),<br>            ),<br>          ],<br>        ),</pre><p>My user bloc list is a constant widget, as you can see. Building a user interface screen is important. The point needs to be on every screen, which means you have to separate your UI screen from your widget screen.</p><p>Take a look at this widget:</p><pre>final class _UserBlocList extends StatelessWidget {<br>  const _UserBlocList();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocListener&lt;HomeViewModel, HomeState&gt;(<br>      listener: (context, state) {},<br>      child: BlocSelector&lt;HomeViewModel, HomeState, List&lt;User&gt;&gt;(<br>        selector: (state) {<br>          return state.users ?? [];<br>        },<br>        builder: (context, state) {<br>          if (state.isEmpty) return const SizedBox.shrink();<br><br>          return HomeUserList(users: state);<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>BlocSelector is used in this widget. It is very useful for using complex states. A UI screen can be built by selecting a state value.</p><p>This is a screen-by-screen example. You can also create a bigger object to call every screen. You can create a widget that initializes the state, for example.</p><pre>final class StateInitialize extends StatelessWidget {<br>  const StateInitialize({required this.child, super.key});<br>  final Widget child;<br>  @override<br>  Widget build(BuildContext context) {<br>    return MultiBlocProvider(<br>      providers: [<br>        BlocProvider&lt;ProductViewModel&gt;(<br>          create: (context) =&gt; ProductStateItems.productViewModel,<br>        ),<br>      ],<br>      child: child,<br>    );<br>  }<br>}</pre><p>Every screen can access this ProductViewModel object. This widget can be used to add logical operations. It helps manage a project’s state. I put it in my network manager, cache manager, and view model. Last but not least, I’m calling this widget in main.dart.</p><pre>Future&lt;void&gt; main() async {<br>  await ApplicationInitialize().make();<br>  runApp(ProductLocalization(child: const StateInitialize(child: _MyApp())));<br>}</pre><p>I think that’s all. Initiate the state for managing a global state in the project. For example, you can put a theme change operation for calling everywhere.</p><pre>   return MaterialApp.router(<br>      routerConfig: _appRouter.config(),<br>      builder: CustomResponsive.build,<br>      theme: CustomLightTheme().themeData,<br>      darkTheme: CustomDarkTheme().themeData,<br>      themeMode: context.watch&lt;ProductViewModel&gt;().state.themeMode,<br>      localizationsDelegates: context.localizationDelegates,<br>      supportedLocales: context.supportedLocales,<br>      locale: context.locale,<br>    );</pre><p>You can use like this (context.watch) or you can wrap with bloc builder etc.</p><h3><strong>11. Cache Operation with Hive</strong></h3><p>Cache operation is another important aspect. For this case, I’m using Hive. There are already a number of database solutions available for mobile devices. Sqflite, shared, realm, etc. As a business person, I prefer to use Hive with my experience. The system works quickly, safely, and is easy to use. I’m creating a cache manager in a submodule this time. If the dependency is not related to the main module, I always choose a submodule.</p><p><a href="https://pub.dev/packages/hive/versions/4.0.0-dev.2">hive 4.0.0-dev.2 | Dart package</a></p><p>I’m using the new version of Hive. It is more effective and easier to use. Isaar core is used for writing. There are many operations that work without async operations. There is no need to add an extra parameter to add a model. This project needs a manager.</p><p>I am working on implementing a strategy design for the cache manager. Using it will make it easier to operate a cache with different packages.</p><pre>abstract class CacheManager {<br>  const CacheManager({this.path});<br>  Future&lt;void&gt; init({required List&lt;CacheModel&gt; items});<br>  void remove();<br>  final String? path;<br>}</pre><p>With this base, let’s create a hive cache manager. Using my cache manager to initialize and remove hive databases.</p><p>I’m registering a hive adapter for my cache model while initializing a HIVE database. This operation requires cache model items.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0ef2d3d5cec279aa372ebf805a4bc1a/href">https://medium.com/media/e0ef2d3d5cec279aa372ebf805a4bc1a/href</a></iframe><p>Cache models extend BaseModel classes. It helps to create a cache model using JSON. While initializing a Hive database, you must add your core operation model. This class creates a cache for user models. In this class, I wrote my unit test.</p><pre>class UserCache with CacheModel {<br>  UserCache({required this.id, required this.name});<br>  UserCache.empty() : this(id: &#39;&#39;, name: &#39;&#39;);<br>  @override<br>  final String id;<br>  final String name;<br>  @override<br>  UserCache fromDynamicJson(dynamic json) {<br>    final itemMap = json as Map&lt;String, dynamic&gt;;<br>    return UserCache(<br>      id: itemMap[&#39;id&#39;] as String,<br>      name: itemMap[&#39;name&#39;] as String,<br>    );<br>  }</pre><p>Last but not least, cache operation is required. The logic will make it easier to keep data in general. Generally, every database package follows these steps.</p><ul><li>Add an item to the cache</li><li>Add all items to Cache</li><li>Remove an item from the cache</li><li>Get an item from the cache</li><li>As well as more…</li></ul><p>I am making a cache operation for each cache model. The logic is making a general cache operation logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/707321c35b07b2f0f550680420190475/href">https://medium.com/media/707321c35b07b2f0f550680420190475/href</a></iframe><p>I will create a hive cache operation after the core layer. Hive uses it to make a cache operation.</p><pre>class HiveCacheOperation&lt;T extends CacheModel&gt; extends CacheOperation&lt;T&gt; {<br>  /// Initialize hive box<br>  HiveCacheOperation() {<br>    _box = Hive.box&lt;T&gt;(name: T.toString());<br>  }<br>  late final Box&lt;T&gt; _box;<br>  @override<br>  void add(T item) {<br>    _box.put(item.id, item);<br>  }<br><br>  @override<br>  void addAll(List&lt;T&gt; items) {<br>    _box.putAll(Map.fromIterable(items));<br>  }<br><br>  @override<br>  void clear() {<br>    _box.clear();<br>  }<br><br>  @override<br>  T? get(String id) {<br>    return _box.get(id);<br>  }<br><br>  @override<br>  List&lt;T&gt; getAll() {<br>    return _box<br>        .getAll(_box.keys)<br>        .where((element) =&gt; element != null)<br>        .cast&lt;T&gt;()<br>        .toList();<br>  }<br><br>  @override<br>  void remove(String id) {<br>    _box.delete(id);<br>  }<br>}</pre><p>That’s all there is to cache operation. This is a very simple method. Any cache model can be used after implementation. Example: HiveCacheOperation&lt;UserCacheModel&gt;. The operations are as follows:</p><ul><li>HiveCacheOperation&lt;UserCacheModel&gt;().add(UserCacheModel(id: ‘1’, name: ‘John’));</li><li>HiveCacheOperation&lt;UserCacheModel&gt;().getAll();</li><li>HiveCacheOperation&lt;UserCacheModel&gt;().get(‘1’);</li><li>HiveCacheOperation&lt;UserCacheModel&gt;().remove(‘1’);</li><li>HiveCacheOperation&lt;UserCacheModel&gt;().clear();</li></ul><p>The core operation has been completed. Implementation time for the project. I have added this cache manager to my product container. Every service, view model, etc., can access it.</p><pre>static void setup() {<br>    _getIt<br>      ..registerSingleton(ProductCache(cacheManager: HiveCacheManager()))<br>      ..registerSingleton&lt;ProductNetworkManager&gt;(ProductNetworkManager.base())<br>      ..registerLazySingleton&lt;ProductViewModel&gt;(<br>        ProductViewModel.new,<br>      );<br>  }<br><br>  // application initialize call from main.<br>     await ProductStateItems.productCache.init();</pre><p>Let’s take a look at my product cache class. It is making an initialization with other required operations. Last but not least, I am adding my cache object to the product cache. With it, you will be able to use it anywhere.</p><pre>final class ProductCache {<br>  ProductCache({required CacheManager cacheManager})<br>      : _cacheManager = cacheManager;<br><br>  final CacheManager _cacheManager;<br><br>  Future&lt;void&gt; init() async {<br>    await _cacheManager.init(<br>      items: [<br>        UserCacheModel.empty(),<br>      ],<br>    );<br>  }<br><br>  late final HiveCacheOperation&lt;UserCacheModel&gt; userCacheOperation =<br>      HiveCacheOperation&lt;UserCacheModel&gt;();<br>}</pre><p>It is ready for use. In hive cache manager, you can add your cache model. Let’s use it in the home view. I make a cache operation when fetching a user list.</p><pre>  final HiveCacheOperation&lt;UserCacheModel&gt; _userCacheOperation;<br><br>  /// Save users to cache<br>  void _saveItems(List&lt;User&gt; user) {<br>    for (final element in user) {<br>      _userCacheOperation.add(UserCacheModel(user: element));<br>    }<br>  }<br><br>  /// Get users from cache<br>  List&lt;User&gt; get usersFromCache =&gt;<br>      _userCacheOperation.getAll().map((e) =&gt; e.user).toList();</pre><p>That’s all I have to say. This cache operation can be used with any cache model. You can also implement your own cache manager for other database packages.</p><h3>12. <strong>Unit test, Integration test, Widget test</strong></h3><p>Testing is a very important part of any project. There are generally three concepts. Here is the official documentation: <a href="https://docs.flutter.dev/testing/overview">https://docs.flutter.dev/testing/overview</a></p><ul><li>Tests of core logic — Unit tests</li><li>Full UI testing — Integration test</li><li>Atomic widget test — Widget test</li></ul><p>My project uses these tests because Flutter directly supports them. Let’s implement the first unit test point.</p><h4>Unit test</h4><p>Here is a unit test for the HomeViewModel. The main part of my project is shown below. Other parts will be used as examples.</p><p>There will be two main classes for cache and network in this view model. However, this is not relevant to unit tests. Just wondering if my method is working. Let’s create a mock login service and user cache.</p><pre>```dart<br>/// Normal usage<br>    _homeViewModel = HomeViewModel(<br>      operationService: LoginService(productNetworkManager),<br>      userCacheOperation: ProductStateItems.productCache.userCacheOperation,<br>    );<br>/// Mock usage<br>    _homeViewModel = HomeViewModel(<br>      operationService: LoginServiceMock(),<br>      userCacheOperation: UserCacheMock(),<br>    );<br>```</pre><p>By using mocks, you can test without relying on any extra dependencies. Unit tests benefit greatly from it. Let’s take a look at my mock class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f622bac29a69e66850eb5be3c486c564/href">https://medium.com/media/f622bac29a69e66850eb5be3c486c564/href</a></iframe><p>For mocking, I’m using mockito. I will only write some methods for using my main method. Direct mock data will be returned by the service layer. Caching only works in memory. There is no need for any additional requirements. This is required for package dependencies, etc.</p><p><a href="https://pub.dev/packages/mockito">mockito | Dart package</a></p><p>Finally, I created this project with Bloc. Bloc_test is included in the package. Unit tests benefit greatly from it. For unit testing, I use this package.</p><p><a href="https://pub.dev/packages/bloc_test">bloc_test | Dart package</a></p><p>The following is a sample of the same test from the file home_view_model_test.dart.</p><pre>group(&#39;Home View Model Test&#39;, () {<br>    test(&#39;inital state is loading&#39;, () {<br>      expect(homeViewModel.state.isLoading, false);<br>    });<br><br>    blocTest&lt;HomeViewModel, HomeState&gt;(<br>      &#39;fetch users&#39;,<br>      build: () =&gt; homeViewModel,<br>      act: (bloc) async =&gt; bloc.fetchUsers(),<br>      expect: () =&gt; [<br>        isA&lt;HomeState&gt;().having((state) =&gt; state.users, &#39;users&#39;, isNotEmpty),<br>      ],<br>    );</pre><p>The first test validates the loading state. In the second case, we validate to fetch users using a bloc test. For looking at this, you can write many more tests.</p><h4>Integration test</h4><p>This is the second step of the integration test. The UI is being validated. It is very useful for testing user interfaces. For the home page, I’m using integration test.</p><p><a href="https://pub.dev/packages/patrol">patrol | Flutter package</a></p><p>For integration tests, I prefer to use the patrol package. It simplifies the process of making UI tests. There are many useful features in this package, and it supports Flutter natively.</p><p>You can learn more about integration tests from [patrol](<a href="https://patrol.dev/docs/getting-started">https://patrol.dev/docs/getting-started</a>) with [flutter website.](<a href="https://docs.flutter.dev/cookbook/testing/integration/introduction">https://docs.flutter.dev/cookbook/testing/integration/introduction</a>)</p><p>My home screen looks like this. Here’s a test we can write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*uqOY1T2LT5ugdqRE3xDqeg.png" /></figure><p>My steps:</p><ul><li>Wait to load home page</li><li>Tap to button</li><li>Wait to load users</li><li>Check to users</li></ul><p>My test file for this case is as follows:</p><pre>patrolTest(<br>    &#39;Open home page and press button&#39;,<br>    ($) async {<br>      await app.main();<br>      await $.pumpAndSettle();<br>      await $(FloatingActionButton).tap();<br>      await $.pumpAndSettle();<br>      await $(&#39;1&#39;).waitUntilVisible();<br>      $(Scrollable).containing(Text);<br>      expect($(&#39;q&#39;), findsWidgets);<br>    },<br>  );</pre><p>It is easy to find the same widget for $() function in the patrol. For looking at this, you can write many more tests.</p><h4>Widget test</h4><p>This is an idea for testing minimal components. It is possible to find any problem directly related to the behavior of the UI component.</p><pre>   /// my user list for using widget test<br>        final users = [<br>      User(userId: 1, body: &#39;body 1&#39;),<br>      User(userId: 2, body: &#39;body 2&#39;),<br>      User(userId: 3, body: &#39;body 3&#39;),<br>    ];<br><br>  await tester.pumpWidget(<br>      MaterialApp(<br>        home: Scaffold(<br>          appBar: AppBar(<br>            actions: [<br>              Builder(<br>                builder: (context) {<br>                  return IconButton(<br>                    onPressed: () {<br>                      context.route<br>                          .navigateToPage(const HomeDetailView(id: &#39;id&#39;));<br>                    },<br>                    icon: const Icon(Icons.details),<br>                  );<br>                },<br>              ),<br>            ],<br>          ),<br>          body: HomeUserList(users: users),<br>        ),<br>      ),<br>    );<br><br><br>  /// test steps<br>    for (final item in users) {<br>        expect(find.text(item.userId.toString()), findsOneWidget);<br>    }<br><br>    await tester.tap(find.byType(IconButton));<br>    await tester.pumpAndSettle();<br>    expect(find.text(&#39;Home Detail View&#39;), findsOneWidget);</pre><h4><strong>13. Pigeon, Fastlane, App Screen generator.</strong></h4><p>We discussed many topics regarding this architecture approach at least. For this project, I’m going to show you another topic.</p><p><a href="https://pub.dev/packages/pigeon">pigeon | Dart package</a></p><ul><li>Pigeon — This makes native communication between Flutter and Native easier.</li><li>A <a href="https://fastlane.tools/">Fastlane </a>is a tool that helps to build and release iOS and Android apps.</li><li><a href="https://studio.app-mockup.com/">The App Screen generator</a> helps make a screen for iOS and Android apps.</li></ul><p>They are helping to fix some issues at any time. It is sometimes necessary to communicate with the native layer of iOS Swift and Android Kotlin. You will be able to solve your problem very easily with this package.</p><p>We are helping to make a build and release for iOS and Android. For releases, it is very useful.</p><p>The App Screen Generator helps you make an app screen for iOS and Android. Design professionals find it very useful.</p><h4>Pigeon: Generate native code more effective and easy</h4><p>First, let’s talk about pigeons.By looking at your dart code, this package writes to native code. You create logic in Dart and Pigeon will generate native Swift and Kotlin code for you. It is just a matter of putting it in your project and using it.</p><pre>enum Code { one, two }<br><br>class MessageData {<br>  MessageData({required this.code, required this.data});<br>  String? name;<br>  String? description;<br>  Code code;<br>  Map&lt;String, String&gt; data;<br>}<br><br>@HostApi()<br>abstract class ExampleHostApi {<br>  String getHostLanguage();<br><br>  // These annotations create more idiomatic naming of methods in Objc and Swift.<br>  @ObjCSelector(&#39;addNumber:toNumber:&#39;)<br>  @SwiftFunction(&#39;add(_:to:)&#39;)<br>  int add(int a, int b);<br><br>  @async<br>  bool sendMessage(MessageData message);<br>}</pre><p>Check out [pigeon](<a href="https://github.com/flutter/packages/tree/main/packages/pigeon/example">https://github.com/flutter/packages/tree/main/packages/pigeon/example</a>)</p><h4>Fastlane: Build your own delivery pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*Hrz2xkdZ0aVcVIwI.png" /></figure><p>Fastlane is an excellent tool for making CDs work locally or remotely. I have been involved with Fastlane for many years. You can use Fastlane packages or write your own scripts.</p><pre>VERSION_NUMBER = &quot;3.0.0&quot;<br><br>platform :ios do<br>  before_all do<br>  end<br>  desc &quot;Push a new beta build to TestFlight&quot;<br>  lane :beta do<br>  enable_automatic_code_signing<br><br>  increment_version_number(<br>    version_number: VERSION_NUMBER<br>  )<br><br>  increment_build_number({<br>      build_number: latest_testflight_build_number + 1<br>  })<br><br>    gym(scheme: &quot;Runner&quot;,<br>          xcargs: &quot;-allowProvisioningUpdates&quot;,<br>    )<br>    upload_to_testflight<br>  end<br>end</pre><p>This script is very simple, as you can see. The first thing I’m doing is incrementing the version number and build number. After that, I will build and upload to TestFlight.</p><h4>Store Screen Generator</h4><p>Making a screen for iOS and Android to access the play store and app store is the last topic. For making a screen, this website is very useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4Q7tw-oHHpUgO2ZIZJTpg.png" /><figcaption><a href="https://studio.app-mockup.com/">https://studio.app-mockup.com/</a></figcaption></figure><p>It offers a variety of free templates for creating app store screens. Making a screen is as simple as selecting a template.</p><h3>Conclusion</h3><p>This article will help you create your own path by exploring various technical ideas. After reading and understanding this article, along with reviewing the source code, you’ll gain several ideas for your new project. You can check out my source code and submit a pull request if needed.</p><p><a href="https://github.com/VB10/architecture_template_v2">GitHub - VB10/architecture_template_v2: &quot;Flutter Architecture Template v2&quot;</a></p><p>The repository includes a template option that you can use when starting a new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*yXVvtfgD_jH9dgbm_zHWxg.png" /></figure><p>Additionally, I’ve created a video series in Turkish, spanning over 9 hours, to complement this article. I’ve included the link to the video below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPL1k5oWAuBhgUAFNvxdF6wIuC9cfvN5PrZ&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPL1k5oWAuBhgUAFNvxdF6wIuC9cfvN5PrZ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzOG-4bkLeu0%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLCEp0m_XcWS7hK1PCi3j6caxy2Vmw%26days_since_epoch%3D20089&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ce50f8f454ed61a615f18159ddb342f/href">https://medium.com/media/4ce50f8f454ed61a615f18159ddb342f/href</a></iframe><p>Thank you for reading!<br>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86f9aa222e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/the-ultimate-guide-flutter-architecture-template-ii-f86f9aa222e6">The Ultimate Guide: Flutter Architecture Template — II</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[İlk Adımını At: Ekip Çalışmasıyla Proje Geliştirme Rehberi]]></title>
            <link>https://vbacik-10.medium.com/i%CC%87lk-ad%C4%B1m%C4%B1n%C4%B1-at-ekip-%C3%A7al%C4%B1%C5%9Fmas%C4%B1yla-proje-geli%C5%9Ftirme-rehberi-1a794972e724?source=rss-c21b865a34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a794972e724</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[first-project]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Veli Bacık]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 11:06:35 GMT</pubDate>
            <atom:updated>2024-12-11T12:03:00.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jilg5CZTwEex460Z" /></figure><p>Merhabalar merhabalar uzun zaman sonra sizinleyim. Özellikle bu yazıyı yazmak istedim. Gördüğüm sorunlar karşısında evinde odasında bir masada tek başına var olmak öne çıkmak isteyen emekçi arkadaşlara bir “<strong>OHHH</strong>” yada “<strong>İşte yapmamız gereken haydi takım olalım</strong>” dedirtmek için ve tabi teknik sıkkınlıktan kurtarmak için bu yazıyı hazırladım.</p><blockquote><strong>Teknik sıkkınlık</strong>: ne yapacağını bilememe, nereye gideceğini bilememe ama içinde çalışma aşkı hevesi bulundurma sonucu çıkan rahatsız edici durum</blockquote><p>Öncelikle yaşadığımız bu dönem ne yazık ki yüzlerce sorun barındırıyor. Ekonomik şartlar, sektörün toz pembe gözükmesi ve eğitim simsarları. Benim bu yazıda size göstereceğim yöntem ve yollar bu sorunları dünya perspektifinde çözmenizde yardımcı olacak. Evde otururken hayallerinize gitmenize yardımcı olmayı, sıkkınlık yaşamak yerine çok çalışmayı nasıl doğru yapacağınızı gösterdiğim bir yazı olacak.</p><p>Korkmayın çok çalışın doğru çalışın ve başarıya ulaşın. İlk işler veya son işler hiçbir şey kurtuluş değil hiçbir şey son değil. Devamlı öğrenme devamlı aç gözlü ama hırsımızla başkasının ekmeğine göz dikmeyecek kadar erdemli olacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgdEk9d8_YuB4-X74Bd_zw.png" /></figure><p>Uzattım biraz özlemişim :). Bu yazı 5 parçadan oluşacak</p><ul><li>İhtiyaçlar</li><li>Ekip</li><li>Backend</li><li>Mobile(front)</li><li>Tester(QA)</li><li>Project Yöneticisi (PM)</li></ul><p>Şimdiden teknik dolu fikir dolu bir yol bulacağınız bu yazıya hoşgeldiniz. Hayyyydiiii başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJk9B8P4xTNvy0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcartoon-scooby-do-Jk9B8P4xTNvy0&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOWM0bnIzYnNqdTQyaWdhMjE1NzNpaTQwMXd3a3FtNW0yeThqOHh0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FJk9B8P4xTNvy0%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="272" frameborder="0" scrolling="no"><a href="https://medium.com/media/76f1aaedd4eafd98926b8b8a81d70511/href">https://medium.com/media/76f1aaedd4eafd98926b8b8a81d70511/href</a></iframe><h3>İhtiyaçlar</h3><p>Bu tarz bir yolda tabi dünyamızın şuan bize verdiği güçleri kullanacağız. Bunları en efektif şekilde değerlendirip kendimizi geliştireceğiz. Gelin neler lazım bir bakalım:</p><ul><li><a href="https://mobbin.com/browse/ios/apps">Mobbin</a> pro üyeliği (üç dört kişi birleşip tek hesap alın, öğrencilere %50 indirimli)</li><li>herhangi bir ai tool ( cloudue tavsiyem github student package ile ücretsiz kullanılıyor)</li><li>en az 4 kişilik bir ekip.</li></ul><p>Mobbin neden işimize yarayacak ve pro neden alıyoruz diyor gibisiniz. Elbette burada ana sebebimiz basit. Mobbin içerisinde yüzlerce uygulamanın ekran görüntülerini barındırıyor. Misal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3n7I40bu3qBw5Lzzioav_g.png" /><figcaption><a href="https://mobbin.com/apps/uber-ios-51d7d6f1-1a92-4d18-bb0c-0958f4d14598/d3962942-f984-494a-91bc-1d31f6e974e9/flows">Uber 2024 Onboard</a></figcaption></figure><p>Uber uygulaması iyi bir örnek. Çok kullanılan bir uygulama ve dünyada bir çok emsali var. Bu uygulamaların görüntülerini sizde indirip tek tek gezerek bulabilirsiniz. Mobbin içinde olan flow özelliği ile aslında bize hangi sayfanın nasıl çalışıtğını resim ediyor. İşte bu özellik bizim ana noktamız olacak. Bu sayede hangi iş hangi sayfa ne yapıyor nereye gidiyor anlayacak ve kendi projemizi oluşturabileceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1x8V-gAcWWWsUZG50Aqkg.png" /></figure><p>Burada gördüğünüz şekilde bir çok özelliğin nasıl çalışacağını ve bağları çok rahat görebileceksiniz.</p><p>Ai tool ise tabiki bize en temel noktlarada yarayacak:</p><ul><li>Kod yazarken mimari üretmemizi sağlayacak</li><li>Ekranlarımız için işlerimizi planlarken buradan yararlanacağız</li><li>Test yaparken veya örnekler lazım olduğunda yine oraya gideceğiz.</li></ul><p>Son olarak en az 4 kişi neden derseniz:</p><p>Burada ekip olarak bir iş çıkarmamız gerekiyor. Günün sonunda o beni sevmiyor ben kafam dengi bulamıyor değil, bir fikire profesyonel ve sözünde duracak şekilde gidebilecek en az 4 arkadaş yeterli olacaktır.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FUoYqxidgzAGygqo1Q2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmoodman-UoYqxidgzAGygqo1Q2&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYTE4NzlyMHo3cmp6ODk5aXc3d2p1Zmh2dWFwYXh0cnZqaXpkemZkOSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FUoYqxidgzAGygqo1Q2%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="318" frameborder="0" scrolling="no"><a href="https://medium.com/media/811aa2324a9234360330aee7b8be3eab/href">https://medium.com/media/811aa2324a9234360330aee7b8be3eab/href</a></iframe><h3>Ekip</h3><p>Bu başlık belki en vurucu nokta şuan bu yazıda. Bireysel her ne kadar iyi geliştirici olsanız dahi günümüz çağında ekipler projeler büyüklüğüne göre birçok ekip arkadaşı barındırıyor. Bu ekiplerde kod yazmaktan ziyade o kodu ekipçe nasıl yazacağını bilmek bazen kod okumak bazen doğru yöntemleri kullanmak çok önemli. Ondan dolayı bu yolda bireysellikten ziyade ekip olmayı ve bu ekip olurken şunlara dikkat etmenizi istiyorum:</p><p>- Mobbin üzerinden daha çok ticaret, yemek veya güvenlik sıkıntısı yaratmayacak bir uygulama seçilir (bu banking app’ler sıkıntı yaratıyor, isterseniz webde gidebilirsiniz)</p><p>- mobbin’de solda seçtikten sonra flow göreceksiniz bu flow pro ile açılıyor bu flowu tek tek kayıt edeceksiniz.</p><p>- bu ekranları ve flow’u iyi öğrenecek anlayacaksınız</p><p>- <a href="https://stackshare.io/stacks">Stackshare</a> üzerinden bulabilirseniz şirketin kullandığı teknolojileri not düşeceksiniz (Linkedln den çalışanlardan bile bir çıktı yapılır)</p><ul><li>tüm girdiler hazır olduktan sonra ekibi 4 e böleceksiniz.</li><li>bir kişi projeyi yönetecek</li><li>bir kişi test yapacak test otomasyonu yazacak</li><li>bir kişi backend yazacak</li><li>bir kişi mobil yazacak(isteğe göre web)</li></ul><p>- yapılacak işler için tüm her şey ekipçe planlanacak ve bunlar github (Atlassian da olur aynı) board kısmında açılarak hazırlanacak (bu noktada en iyi dostunuz ai, soracaksın bana bir task oluşturur musun o halleder.)</p><p>- Tüm işler pr’lar üzerinden dönecek şekilde hazırlanacak</p><p>- İşler bittikten sonra testere testerden sonra pm atılacak ve task kapatılacak. haftalık plan sonrası tester regrasyon testlerine başlarken automation tarafına çalışacak</p><p>- Automation testler için mobilde <a href="https://maestro.mobile.dev/">Meastro</a> kullanabilir veya diğerleri</p><p>- Burada flowları iyi kullanarak mobbil’den backend mobil taskları yine ai kullanarak açılacak</p><p>- Ek olarak tasarım ve Devops kısmına ekleme olur ama öğrenci kafasında çok gerek yok zamanla onuda ekip kendi yönetir.</p><p>- Branch yönetimi için <a href="https://www.toptal.com/software/trunk-based-development-git-flow">trunk based</a> feature develop release şeklinde gidilir ya da kendi tarz veya <a href="https://www.toptal.com/software/trunk-based-development-git-flow">Gitflow</a> seçilir.</p><p>- İşler “<a href="https://www.atlassian.com/agile/project-management/definition-of-done">definition of done</a>” dediğimiz bitmesi için ne lazım eklenir (tester onaylar, code doc yazılır, pm onaylar, etc)</p><h3>Backend</h3><p>Geldik en sevdiğim ve her zaman herkese önerdiğim yere. Backend o kadar büyük bir yer ki burada bulacağınız gelişme tüm diğer dillere fw etki edecektir. Bu proje olarak amacımız alt yapıyı hazırlamak ve client yani front end uygulamıza bir servis hazırlamak. Özellikle bu çalışmalarda ihtiyaca göre ve yarınlara göre seris yapısı kurmayı, geliştirmeyi öğreneceğiz. Neler yapacağız bir bakalım:</p><ul><li>Hangi dil ya da framework kullanılacağı fark etmez; önerim Node.js yönünde olacaktır. Çünkü hızlıca yazılabildiği için ben genellikle Node.js kullanıyorum. Ancak istersen .NET Core, Go gibi alternatifleri de seçebilirsin.</li><li>Taskları aldıktan sonra, örneğin “Login işlemi için e-posta ve şifreyle giriş yapılacak” gibi bir taskı alıp Node.js için gerekli kodları yazdırabilirsin. Bu işlemi yaparken GitHub’da bir board oluşturup yapılacak işleri düzenlersin. Ne yapılacağına dair planlamayı proje yöneticisiyle (PM) konuşup onay aldıktan sonra geliştirme sürecine başlayabilirsin.</li><li>İlk etapta amacın ürünü ortaya çıkarmak. Bu süreçte backend geliştirme yaparken en önemli nokta güvenlik olacak. Endpoint’leri yazarken güvenlik standartlarına dikkat etmelisin.</li><li>Diyelim ki branch’lerinizi <strong>dev</strong> ortamına merge ettiniz; burada küçük bir script ile API’yi sürekli güncel tutabilir ve bu işlemleri otomatize edebilirsiniz. Böylece yapılan değişiklikleri anlık olarak görebilirsiniz.</li><li>API’yi AWS gibi bir platforma deploy ederek canlıya alacaksın.</li><li>Projenin teknik altyapısını oluştururken, daha önce gördüğün ve benzer bir yapıya sahip bir eğitim ya da dokümandan birebir esinlenebilirsin. Amaç, kullanılabilir bir fikirden yola çıkarak ilerlemek. Proje tamamlandıktan sonra test süreçleri eklenir. Bu noktada AI, dostun gibi davranarak işleri kolaylaştırır ve sakin bir yapı ortaya çıkarır.</li><li>Unutma, teknik seviyeni geliştirirken aynı zamanda bir iş ortaya koyuyorsun. Amacın daima task’ları iyi bir yapıda üretmek ve düzenli bir şekilde tamamlamak olmalı.</li></ul><h3>Mobile(front)</h3><p>Tabi benim en sevdiğim diğer alana geldik. Kendi alanlarım görünce ayrı mutlu oluyorum. Benim alanım ne derseniz kodun olduğu her yer. Ben kütüphane dil değil koda iyi koda inanıyorum daima isimlere takılmadan. Bu kısmı geçecek olursak mobile app ile amacımız android/ios olarak iki uygulama vererek backend den gelen servislerimizi en doğru şekilde bağlamak olacaktır. Bu yolda çıkacak crashleri yakalama, analatik kullanma ve tabiki kullanış en önemli noktamız olacak. Haydi bakalım neler var:</p><ul><li>Bir <strong>design sistemi</strong> oluşturup mimari bir yapı kurmalısın. Android ve iOS platformlarında geliştirme yapacağımız için <strong>Flutter</strong> kullanmanı öneririm. Ancak bu tamamen senin tercihin; iOS native, Android KMP veya başka bir framework kullanabilirsin. Hangi teknolojiye aşina veya hangisine daha çok ilgi duyuyorsan, onunla çalış.</li><li>Mobil veya backend geliştirme yaparken “Acaba bunu yazmasam daha iyi mi olur?” düşüncesine kapılmana gerek yok. Buradaki amaç yazmak ve öğrenmek. Bu yüzden her iki alanda da çekinmeden ilerle.</li><li>İşleri uygulamaya entegre et ve düzenli bir şekilde paketler çıkar. Tester’ını daima güncel tut ve her yayınladığın pakette hangi işler tamamladığını açıkça belirt.</li><li>Ekranlarını <strong>dark theme</strong> için tasarlamana gerek yok, ancak bu özelliğe hazır bir yapı oluştur. Tema ve benzeri özellikler projenin bir parçası olsun.</li><li><strong>Responsive</strong> geliştirmeyi unutmadan çalış. Web için olmasa bile, tablet gibi cihazlar için uyumluluğu mutlaka düşün.</li><li>Geliştirdiğin paketi <strong>Google Play</strong> ve <strong>App Store</strong> süreçlerine hazırlayıp yayınla. Bu süreçleri yönetmek için küçük bir <a href="https://fastlane.tools/"><strong>Fastlane</strong></a> yapılandırması kullanarak işleri kolaylaştırabilirsin.</li></ul><h3>Tester(Q.A)</h3><p>Hakkı en çok yenen üzerinde türlü sorumluluk olan en değerli parçamıza geldi sıra. Eğer tester arkadaşlar “automation” kodlarını yazmazsa ve her defa her şeyi baştan manuel test ederse çok ciddi sorunlar psikolojik yıpranmalar bekliyor olacak. Bu parçada hem test yapmayı öğrenirken hem kodlamayı öne çıkarmayı istiyorum. Bakalım neler var:</p><ul><li>Özellikle test ettiğin versiyonları <strong>GitHub board</strong> üzerinden takip et ve ilerlemeyen ticket’lerle gereksiz yere vakit kaybetme; bu noktada takım çalışmasının önemini unutma.</li><li>Ticket kapsamını ilk planlama aşamasında öğrensen dahi, yine de yapay zekâdan veya emsal uygulamalardan destek alarak “Bu nasıl çalışıyor?” sorusuna yanıt bulmaya çalış.</li><li>Anlamadığın işleri mutlaka geliştiriciye sor ve ne yapıldığını tam olarak öğrenmeye çalış.</li><li><strong>Regresyon dokümanı</strong> hazırlayıp uygulama yayınlandıktan sonra bu dokümanı belirli aralıklarla çalıştır.</li><li>Sağlıklı senaryolar için <strong>smoke test</strong> süreçlerini geliştir ve bu testleri haftalık veya belirli periyotlarla çalıştırmayı alışkanlık haline getir.</li><li>Boş zamanlarında test otomasyonuna başla ve temel seviyede kod yazma pratiği yap.</li><li>“Ben bulamadım” değil, “Biz bulamadık, hata bizimdir” yaklaşımını benimse. Test yaparken önce yapılan işlemi, ardından bunun etkileyebileceği diğer alanları düşün. İşte yazanların ötesinde bir planlama yapmayı ihmal etme.</li><li>Her zaman öncelikli amaç, canlı ortamda müşteriden önce olası hataları bulmak olmalıdır.</li></ul><h3>Proje Yöneticisi (PM)</h3><p>Teknik bir ekibin en en önemli parçası aslında. Kodlar işler yapılır elbette. Elbette yazılır. Fakat nasıl? Ne zaman? Ne şekilde? Ekibinin en efektif kullanımı nasıl? Teslim gelişim ve ekip huzuru. Tabi bunlar benim elbette kendi düşüncem bunun hepsini bulmanız da yapması da biraz zor oluyor. Ama gelin bu projede yapalım. Projeyi yönetecek arkadaş iş planlarını yapsın ekibi takip etsin ve ekibin gücünü sayısal olarak planlasın. Haydi bakalım neler var:</p><ul><li>Açılan task’lar konusunda tüm ekibin farkında olmasını mutlaka sağla.</li><li>Günlük <strong>daily meeting</strong>’ler düzenleyerek “Neler yaptık? Neredeyiz? Herhangi bir ihtiyacımız var mı?” sorularını sormak önemlidir. Ancak bu toplantılar bir baskı yaratmak için değil, işin durumunu anlamak için yapılmalıdır.</li><li>Dokümantasyonu düzenli olarak takip ederek ekip içindeki dengeyi korumaya özen göster.</li><li>Ekibe verilen task’lar ve yapılan işler ne kadar doğru ve eksiksiz tamamlanıyor, bunu analiz ederek çalışmalarını şekillendir.</li><li>Düzenli olarak rapor hazırlamaya başla. Örneğin, “Bu ekip iki haftada neler yaptı, bu işleri ne kadar sürede tamamladı?” gibi sorulara yanıt arayarak raporlarını oluştur.</li><li>Ekibin çalışma kapasitesini ve verimliliğini anlamaya çalış.</li><li>Belirli ritüeller düzenle. Örneğin, haftada bir oyun oynayarak veya farklı aktivitelerle ekibin bağını güçlendirebilirsin.</li><li>Ürünün geleceği için planlar yap ve rakiplerin durumunu analiz ederek hazırlıklar yapmalıdır.</li></ul><p>Veee hazırız gelin şimdi elimizde neler var son olarak nelere dikkat etmeliyiz bakalım:</p><ul><li>Projenizi tüm süreçleriyle dokümante edip LinkedIn ve benzeri platformlarda paylaşın.</li><li>Ekip çalışması sırasında yaşananlar, karşılaşılan zorluklar ve elde edilen başarılar detaylı şekilde anlatılmalı.</li><li>Yapılan clone uygulama, hangi şirkete aitse onlara bu çalışmaları göndererek fırsatlar yaratmaya çalışın.</li></ul><blockquote><strong>*Task:</strong> İş olarak düşünebilirsiniz, örneğin login sayfasının yapılması.</blockquote><p>Son olarak bu yazıyı hazırlarken evde emekçi bir ailenin evladını, kendi emeğine güvenen dimdik yüreyen arkadaşları, hayalleri olan ve bunları yaparken para tuzaklarına düşmek istemeyenleri düşündüm. Elimden geldiğince size gerçek hayatı resim edip buralara nasıl hazırlanmanız gerektğini anlattım. Umarım sana erişir senin arkadaşının, bu yolda çalışan birisinin o sıkıntılı zamanını unuturur yarınlara bir hedef koyabilirim.</p><p>Sizlere inanıyor sizler için çalışıyor Atatürk’ün bize bıraktığı vatana vatanın evlatlarına elimden geldiğince sahip çıkmaya çalışıyorum. Asla pes etmek yok çok çalışacak ve başaracaksınız.</p><p>Bir sonraki yazıda görüşmek üzere<br>Emeklerinizin karşılığını aldığınız güzel bir zaman olur umarım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7WICht89LQdQZa2A%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fscoobydoo-cartoon-scooby-doo-3o7WICht89LQdQZa2A&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExb3U1bHNrbHBhaXEzOTB6NG52c3N0NTgzZmdvcTRxYno1dXU5Zjl1ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7WICht89LQdQZa2A%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c365ebb7267372c5bb01210d53ddd7d/href">https://medium.com/media/5c365ebb7267372c5bb01210d53ddd7d/href</a></iframe><h4><strong>Linkler</strong></h4><p><a href="https://t.co/zaI51RiaNn">https://stackshare.io/stacks</a> <a href="https://t.co/1VPkNXJtBx">https://mobbin.com/browse/ios/apps</a> <a href="https://t.co/T2g8cvjBGd">https://toptal.com/software/trunk-based-development-git-flow…</a> <a href="https://t.co/oogiP2ormN">https://github.com/features/issues</a></p><p>Tek bir tweet’de özeltediğim yazıya da buradan erişebilirsiniz:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/10VBacik/status/1866135059394105375&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ac401da8c122daeefed6ba7d6af2cf/href">https://medium.com/media/02ac401da8c122daeefed6ba7d6af2cf/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a794972e724" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>