<?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 Tom on Medium]]></title>
        <description><![CDATA[Stories by Tom on Medium]]></description>
        <link>https://medium.com/@vogel_tom?source=rss-76d49330fd74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*scIMnWOvhjbnsaqzXl4G0A.png</url>
            <title>Stories by Tom on Medium</title>
            <link>https://medium.com/@vogel_tom?source=rss-76d49330fd74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:45:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vogel_tom/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[Building Lapse with Flutter’s New Desktop Windowing API]]></title>
            <link>https://medium.com/@vogel_tom/building-lapse-with-flutters-new-desktop-windowing-api-6c777b03a4e8?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c777b03a4e8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[desktop-app]]></category>
            <category><![CDATA[windows-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 07:57:25 GMT</pubDate>
            <atom:updated>2026-08-30T07:57:25.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I combined a persistent overlay, an on-demand dashboard, shared Riverpod state, and a small native Windows escape hatch</h3><p>Lapse is a Windows active-time tracker that is meant to stay visible without behaving like a conventional desktop app. Most of the time it is a small always-on-top timer. When I need more context, it expands into a task list. A separate dashboard shows history, application usage, and settings.</p><p>That distinction matters. The dashboard is not a route squeezed into the overlay, and the overlay is not a decorated corner of a large main window. They are two native windows with different sizes, lifetimes, and jobs.</p><p>Flutter’s new <a href="https://flutter.dev/blog/desktop-windowing-apis">Desktop Windowing API</a> made that structure possible without splitting Lapse into separate Flutter engines or inventing an application-level synchronization layer. Both windows remain in one widget tree and share the same Riverpod state, while each has its own controller and native lifecycle.</p><p>The API is still experimental. I built the current version of Lapse against Flutter 3.48.0-1.0.pre-515 from the main channel, and some of the types I use are internal. This is an account of a useful real application built on a moving API, not a recommendation to put the same code into every production app today.</p><figure><img alt="The Lapse timer and task overlay beside a larger analytics dashboard on a Windows desktop." src="https://cdn-images-1.medium.com/max/1024/1*ScAXQMYJfRF6TqFXrZ5ujQ.png" /><figcaption><em>Lapse uses a compact persistent overlay and a separate dashboard, both rendered by one Flutter application.</em></figcaption></figure><h3>The product shape dictated the window model</h3><p>Lapse has two deliberately different surfaces:</p><ul><li>The overlay is created when the app starts. It can collapse from 312 × 356 logical pixels to a 244 × 52 timer strip, stays above other windows when requested, and hides instead of terminating the app.</li><li>The dashboard is created only when it is opened. It has a minimum size of 760 × 520, can be minimized or maximized, remembers its bounds, and is destroyed when closed.</li></ul><p>That is more than a layout breakpoint. Each surface needs its own operating-system window and its own lifecycle policy.</p><p>The first change from a conventional Flutter app happens at startup. The windowing API expects the application to supply its views, so Lapse uses runWidget() instead of runApp():</p><pre>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  runWidget(const ProviderScope(child: LapseWindowHost()));<br>}</pre><p>Placing ProviderScope above the window host is the small architectural choice that makes the rest of the design pleasant. The overlay and dashboard render independently, but they read the same sessionControllerProvider. A timer tick, a completed task, or a settings change has one source of truth.</p><p>This matches one of the API’s most important design decisions: multiple native windows still belong to a single Flutter widget tree. For Lapse, multi-window did not have to mean multi-process or multi-engine.</p><h3>One permanent window, one registered on demand</h3><p>The overlay controller is owned for the lifetime of LapseWindowHost. Its size constraints and close behavior are declared where the native window is created:</p><pre>_overlayWindowController = WindowController(<br>  size: AppConstants.collapsedSize,<br>  constraints: const BoxConstraints(<br>    minWidth: 244,<br>    minHeight: 52,<br>    maxWidth: 312,<br>    maxHeight: 356,<br>  ),<br>  title: AppConstants.name,<br>  delegate: _CallbackWindowDelegate(() {<br>    unawaited(ref.read(sessionControllerProvider).hide());<br>  }),<br>);</pre><p>The close delegate does not destroy the overlay. It asks the session controller to persist current state and hide the native window. That leaves the tray menu and activity tracking available, which is the expected behavior for Lapse.</p><p>The controller is paired with a WindowEntry, and the host returns a WindowManager with that entry as its initial window:</p><pre>@override<br>Widget build(BuildContext context) =&gt;<br>    WindowManager(initialWindows: [_overlayEntry]);</pre><p>The dashboard follows a different path. When the user opens it, Lapse first checks whether a live dashboard controller already exists. If it does, the app activates that window instead of creating a duplicate. Otherwise it creates a controller and entry, then registers the entry with the surrounding WindowRegistry.</p><pre>final existing = _dashboardWindowController;<br>if (existing != null &amp;&amp; !existing.isDestroyed) {<br>  existing.activate();<br>  return;<br>}<br><br>final registry = WindowRegistry.of(registryContext);<br>late final WindowController windowController;<br>windowController = WindowController(<br>  size: Size(preferences.dashboardWidth, preferences.dashboardHeight),<br>  constraints: const BoxConstraints(minWidth: 760, minHeight: 520),<br>  title: &#39;${AppConstants.name} Dashboard&#39;,<br>  delegate: _CallbackWindowDelegate(() =&gt; unawaited(closeDashboard())),<br>);<br><br>registry.register(entry);</pre><p>This gives Lapse a single-instance dashboard without making it permanent. Its last page is held in a ValueNotifier, so a request to open Settings can also activate an existing dashboard and navigate it to the right place.</p><figure><img alt="Architecture diagram showing a ProviderScope and WindowManager branching into overlay and dashboard controllers that share one session controller and call a small Windows platform bridge." src="https://cdn-images-1.medium.com/max/1024/1*g8xmoT_IOIQa-7czwD5jnw.png" /><figcaption>Separate window controllers share one application state; Windows-specific behavior stays behind a narrow platform boundary.</figcaption></figure><h3>Window lifecycle is application logic</h3><p>Creating a second window is the easy part. Closing it correctly is where the API becomes part of the application architecture.</p><p>For the dashboard, Lapse performs four operations in order:</p><ol><li>Read and persist the current native window bounds.</li><li>Unregister the WindowEntry from the registry.</li><li>Clear the cached entry and controller references.</li><li>Destroy and dispose the WindowController.</li></ol><p>The close function also checks that it still owns the registered entry before doing any work. That guard matters because closing a native surface is asynchronous while the user can continue interacting with the app.</p><p>The overlay has the opposite lifecycle. It remains registered, and switching between expanded and collapsed modes updates the existing native window:</p><pre>final size = _state.preferences.overlayMode == OverlayMode.expanded<br>    ? AppConstants.expandedSize<br>    : AppConstants.collapsedSize;<br><br>final resize = _windowResizer;<br>if (resize != null) {<br>  resize(size);<br>} else {<br>  await _platform.resize(size.width, size.height);<br>}</pre><p>The UI transition and the operating-system window resize are separate concerns. AnimatedSwitcher handles the content change, while WindowController.setSize() changes the native surface. Keeping the resize callback on the session controller also leaves a platform fallback for environments where the experimental controller is unavailable.</p><h3>The native escape hatch is still part of the design</h3><p>The new API owns window creation, rendering, sizing, activation, and destruction in Lapse. It does not yet replace every Windows-specific behavior the app needs.</p><p>A small method-channel bridge still handles:</p><ul><li>Acrylic and rounded Windows chrome</li><li>The frameless overlay style</li><li>Always-on-top behavior</li><li>Native drag regions</li><li>Multi-monitor-safe position restoration</li><li>The system tray and autostart</li></ul><p>This is a useful boundary rather than an embarrassment. Flutter’s own windowing design explicitly leaves room for native customization when a cross-platform abstraction cannot express a platform-specific requirement.</p><p>The important part is deciding which side owns what. Dart owns application state and the two window lifecycles. The Windows runner applies operating-system behavior to the windows after Flutter creates them. Lapse currently locates those native handles by centrally defined window titles, which is practical but also a known limitation: title-based identification will need revisiting as the API matures or the app grows more window types.</p><h3>Testing an experimental API without loading the desktop embedder</h3><p>Lapse’s widget tests do not load the Windows embedder’s windowing symbols. The tests therefore disable Flutter’s internal windowing feature flag and render OverlayWindow and DashboardWindow inside fixed-size MaterialApp test harnesses.</p><p>That means the tests focus on what belongs to Flutter UI and application state: adding and editing tasks, collapsing the overlay, navigating dashboard pages, and triggering window-control callbacks. Native styling, Win32 dragging, and real window creation remain integration concerns.</p><p>It is a deliberate seam. The production host wires widgets to native controllers, while the feature widgets accept callbacks and state they can exercise without a desktop window manager.</p><h3>What I would carry into another multi-window Flutter app</h3><p>The most reusable lesson from Lapse is to model windows as owned resources, not as unusually large routes.</p><p>Give each native window one clear owner. Decide whether closing means hide or destroy. Keep shared application state above the window split. Make duplicate-window behavior explicit. Persist native geometry before destruction. And keep platform-specific chrome behind a boundary narrow enough that the rest of the app does not know about HWND or Win32 messages.</p><p>There is also a straightforward trade-off: building on Flutter’s main channel means accepting churn. Lapse imports package:flutter/src/widgets/_window.dart and uses narrow analyzer suppressions for implementation_imports and invalid_use_of_internal_member. Those suppressions are local to the two files that touch the API, not global exclusions. I expect SDK upgrades to require changes, and I would not hide that cost from a team choosing this approach.</p><p>For Lapse, the trade-off is worthwhile because multiple native windows are not an optional flourish. They are the product shape. The new API lets the app express that shape while preserving one Flutter state tree, and the remaining native code is focused on the Windows behavior that is genuinely platform-specific.</p><p>The source for Lapse is available on <a href="https://github.com/zTomz/lapse">GitHub</a>. If you are evaluating Flutter’s experimental desktop APIs, the official <a href="https://flutter.dev/blog/desktop-windowing-apis">windowing introduction</a> and <a href="https://github.com/flutter/flutter/tree/main/examples/multiple_windows">multiple-windows example</a> are the best places to start before looking at a more opinionated application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c777b03a4e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Meets Android Home Screen Widgets]]></title>
            <link>https://medium.com/@vogel_tom/flutter-meets-android-home-screen-widgets-6ae0dab0325b?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae0dab0325b</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 14:30:31 GMT</pubDate>
            <atom:updated>2026-08-21T14:30:31.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>A data boundary that survives app restarts</h3><p>An Android home screen widget looks like a small extension of an app. In a Flutter project, it is closer to a second client.</p><p>The widget can be visible while the Flutter UI is closed. Android may ask it to redraw when no Dart code is running. Its layout is hosted by the launcher, its interactions travel through PendingIntents, and collection widgets load their rows through Android&#39;s RemoteViews APIs.</p><p>That changed the question I had to answer while adding preset widgets to Loop, my Flutter interval timer. It wasn’t “How do I render a Flutter widget on the home screen?” It was:</p><blockquote><em>What is the smallest piece of app state Android needs to render and launch a preset correctly without depending on a live Flutter engine?</em></blockquote><p>The answer became a deliberately narrow data boundary. Flutter remains the owner of presets and categories. Whenever that state changes, it publishes a validated snapshot to Android. Android stores its own read model, renders the widgets from it, and hands only a stable preset ID back when the user taps.</p><p>That separation is what lets the widgets survive app restarts without creating two competing sources of truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0cjFjYap4BMsgVdcQWIQQ.png" /><figcaption><em>Android home screen showing a Loop single-preset timer widget and a Loop widget containing a list of presets.</em></figcaption></figure><h3>A home screen widget is not a Flutter widget</h3><p>Android describes app widgets as views embedded in another app, usually the launcher. The traditional implementation uses XML layouts and RemoteViews, which support only a limited set of views and operations. Collection widgets add another native component: a RemoteViewsService that supplies individual rows.</p><p>That model has practical consequences:</p><ul><li>I can’t build the home screen UI with the normal Flutter widget tree.</li><li>Android must be able to obtain display data without asking a visible Flutter screen.</li><li>Widget configuration belongs to individual Android widget IDs, not to the Flutter navigation stack.</li><li>A tap may cold-start the app, so the requested action must survive until Flutter is ready to consume it.</li></ul><p>The <a href="https://developer.android.com/develop/ui/views/appwidgets/overview">Android app widget documentation</a> is a useful starting point, and the <a href="https://developer.android.com/develop/ui/views/appwidgets/collections">collection widget guide</a> explains the extra RemoteViewsService path.</p><p>I could have treated the native side as another complete persistence layer. That would have meant duplicating the preset repository, its migrations, and its editing rules in Kotlin. I could also have tried to start Flutter whenever Android needed data, but that would make a small launcher surface depend on the lifecycle and startup cost of the full app.</p><p>Neither boundary fit the feature. The native widget code doesn’t need to edit a preset. It needs enough data to display one and enough identity to ask Flutter to start it.</p><h3>Flutter owns the model; Android owns a snapshot</h3><p>Loop’s Flutter state contains more than the launcher needs. The native read model contains only these fields:</p><pre>class PresetWidgetPreset {<br>  const PresetWidgetPreset({<br>    required this.presetId,<br>    required this.label,<br>    required this.iconCodePoint,<br>    required this.activeDurationSeconds,<br>    required this.restDurationSeconds,<br>    required this.sets,<br>    required this.isFavorite,<br>    required this.categoryId,<br>  });<br><br>  Map&lt;String, Object?&gt; toMap() =&gt; {<br>    &#39;presetId&#39;: presetId,<br>    &#39;label&#39;: label,<br>    &#39;iconCodePoint&#39;: iconCodePoint,<br>    &#39;activeDurationSeconds&#39;: activeDurationSeconds,<br>    &#39;restDurationSeconds&#39;: restDurationSeconds,<br>    &#39;sets&#39;: sets,<br>    &#39;isFavorite&#39;: isFavorite,<br>    &#39;categoryId&#39;: categoryId,<br>  };<br>}</pre><p>There are no presentation objects, Riverpod types, or Flutter widgets crossing the boundary. A category snapshot is smaller still: ID, label, and icon code point.</p><p>The platform service sends both lists in one method call:</p><pre>await _channel.invokeMethod&lt;void&gt;(&#39;synchronize&#39;, {<br>  &#39;presets&#39;: presets.map((preset) =&gt; preset.toMap()).toList(),<br>  &#39;categories&#39;: categories.map((category) =&gt; category.toMap()).toList(),<br>});</pre><p>Flutter’s <a href="https://docs.flutter.dev/platform-integration/platform-channels">platform channel documentation</a> makes an important limitation explicit: MethodChannel messages aren&#39;t type-safe. Matching channel names and vaguely similar maps are not a contract. Both sides still need to agree on every key, type, nullable value, and range.</p><p>For this small boundary, I accepted that trade-off and kept the contract visible. If it grew much further, generated bindings such as Pigeon would become more attractive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7T9lhvmjzIF-Q-ID9y4laA.png" /><figcaption><em>Architecture diagram showing Flutter publishing preset snapshots to Android widgets and Android returning a preset ID on tap.</em></figcaption></figure><h3>Synchronize at state boundaries, not on a timer</h3><p>The snapshot changes when a user adds, edits, reorders, categorizes, favorites, or deletes a preset. It doesn’t need periodic polling.</p><p>Loop’s Riverpod notifier synchronizes launcher surfaces after the latest state revision has been saved. It also forces a synchronization during initialization and when the app resumes. That covers the two useful cases: publish real changes immediately, and repair any native drift when Flutter becomes active again.</p><pre>Future&lt;void&gt; synchronizeWidgets({bool force = false}) async {<br>  final presets = presetWidgetPresets(state.presets);<br>  final categories = presetWidgetCategories(state.categories);<br><br>  if (!force &amp;&amp;<br>      listEquals(presets, _synchronizedWidgetPresets) &amp;&amp;<br>      listEquals(categories, _synchronizedWidgetCategories)) {<br>    return;<br>  }<br><br>  await ref.read(presetWidgetServiceProvider).synchronize(<br>    presets: presets,<br>    categories: categories,<br>  );<br><br>  _synchronizedWidgetPresets = presets;<br>  _synchronizedWidgetCategories = categories;<br>}</pre><p>The equality check avoids republishing an unchanged snapshot during the current Flutter process. Forced synchronization on initialization and resume is intentional: the in-memory cache is an optimization, not evidence that Android has the latest data.</p><p>Synchronization failure also shouldn’t make preset editing fail. The app reports the platform error, while the Flutter repository remains authoritative and can try again later. For this feature, stale launcher content is recoverable; losing the user’s edit is not.</p><h3>Validate again on the Android side</h3><p>The Kotlin receiver treats platform-channel input as untrusted structured data. It doesn’t cast the entire payload into a presumed model and hope for the best.</p><p>Each category and preset is parsed independently. Invalid entries are dropped. IDs must be non-empty. Icon values must be valid Unicode code points. Active and rest durations are checked against Loop’s supported range, and a finite set count must be between 1 and 99. Duplicate IDs are reduced to the first valid occurrence.</p><p>The order matters as well. Categories are validated first, producing a set of known category IDs. Presets that reference a missing custom category are moved to the native system:unassigned category.</p><pre>val categories = categoryValues<br>    .mapNotNull(::parseCategory)<br>    .distinctBy(CategoryWidgetData::categoryId)<br><br>val validCategoryIds = categories<br>    .mapTo(mutableSetOf(), CategoryWidgetData::categoryId)<br><br>val presets = presetValues<br>    .mapNotNull(::parsePreset)<br>    .distinctBy(PresetWidgetData::presetId)<br>    .map { preset -&gt;<br>        if (preset.categoryId in validCategoryIds ||<br>            preset.categoryId == FAVORITES_CATEGORY_ID ||<br>            preset.categoryId == UNASSIGNED_CATEGORY_ID<br>        ) preset else preset.copy(categoryId = UNASSIGNED_CATEGORY_ID)<br>    }</pre><p>This isn’t an attempt to recreate all Flutter domain validation. It protects the native store from malformed channel input and from relationships that became stale between versions.</p><p>After validation, Android serializes the snapshot to its own SharedPreferences. That storage is intentionally separate from Flutter&#39;s preset persistence. It is a projection, not a second editable database.</p><p>This gives the widget provider a synchronous, local read path when Android calls it later. No Flutter engine has to be available, and no asynchronous repository has to finish inside an AppWidgetProvider callback.</p><h3>Widget configuration has its own identity</h3><p>Android assigns an appWidgetId to every placed widget instance. That means two copies of the single-preset widget can point to different presets, and two collection widgets can display different categories.</p><p>The native store keeps those selections under keys derived from the widget ID:</p><pre>selection:&lt;appWidgetId&gt;          -&gt; &lt;presetId&gt;<br>category-selection:&lt;appWidgetId&gt; -&gt; &lt;categoryId&gt;</pre><p>The configuration activities are native Android activities. They read the current snapshot, let the user select a valid preset or category, save the ID for that widget instance, update it, and return the result Android expects.</p><p>That is another useful boundary. Configuration doesn’t modify a preset. It only binds a launcher-owned widget instance to an existing stable ID, so there is no reason to boot the Flutter UI for it.</p><p>Selections need maintenance, though. When a custom category disappears, the synchronization step repairs affected widget instances by moving their selection to system:unassigned. When a widget is removed from the home screen, onDeleted removes its selection key. When the selected preset itself no longer exists, the single-preset widget renders an unavailable state whose tap action reopens configuration.</p><p>These states are less exciting than the happy path, but they are what keep stale launcher state from becoming a broken shortcut.</p><h3>Rendering one item and rendering a collection are different paths</h3><p>Loop exposes two widget types.</p><p>The single-preset widget is straightforward. Its AppWidgetProvider loads the selected preset, fills a RemoteViews layout, assigns text and generated icon bitmaps, attaches a PendingIntent, and calls AppWidgetManager.updateAppWidget.</p><p>The category widget contains a list. Its provider configures a remote adapter, while a RemoteViewsFactory reloads the selected category from the native store and creates each row. When Flutter publishes new data, Android both updates the widget shell and calls notifyAppWidgetViewDataChanged, which triggers the factory&#39;s onDataSetChanged path. This matches the refresh model described in Android&#39;s <a href="https://developer.android.com/develop/ui/views/appwidgets/advanced">advanced widget documentation</a>.</p><p>The distinction is easy to miss if “the widget” is treated as one component. A full RemoteViews update refreshes the outer widget. A collection also needs its data source invalidated so its rows are fetched again.</p><p>There are visual constraints too. RemoteViews cannot host Loop&#39;s Flutter typography and icon widgets directly. The Android implementation loads the same bundled typefaces and renders unsupported text and icon treatments into bitmaps for day and night variants. That keeps the launcher surface recognizable without pretending it can reuse the Flutter widget tree.</p><h3>A tap must survive a cold start</h3><p>The data flow back into Flutter is intentionally much smaller than the flow out. A widget tap carries only the stable preset ID.</p><p>For a single-preset widget, Android creates an activity PendingIntent targeting MainActivity. The intent uses a dedicated action and includes the preset ID as an extra. The flags allow an existing activity to receive the request through onNewIntent, while the same intent can also create the activity after a cold start.</p><p>MainActivity captures that ID before Flutter asks for it:</p><pre>private fun capturePresetLaunch(intent: Intent?) {<br>    if (intent?.action != ACTION_START_PRESET) return<br>    pendingPresetId = intent<br>        .getStringExtra(EXTRA_PRESET_ID)<br>        ?.takeIf(String::isNotBlank)<br>}</pre><p>Once the Flutter app is mounted, it consumes the pending ID exactly once. It then checks onboarding state, verifies that the preset still exists, applies it to the quick-start state, and opens the timer route. If the ID is stale, Flutter does not try to reconstruct a deleted preset from Android’s snapshot.</p><p>This is the same ownership rule in reverse: Android can request an action, but Flutter decides whether that action is valid against current authoritative state.</p><p>Collection rows use Android’s pending-intent template and fill-in intent pattern, but they ultimately produce the same action and preset ID. The entry mechanics differ; the application contract does not.</p><h3>What the tests can prove</h3><p>The Flutter unit tests mock the platform channel and assert the complete serialized shape, including nullable sets, category IDs, icon code points, and durations. They also verify that unsupported platforms do not call Android.</p><p>Provider tests check that initialization maps every current preset and custom category into the widget read model. Other app tests cover consumption of a pending preset ID and selection of the matching Flutter preset.</p><p>Those tests are valuable, but they stop at the platform boundary. Android widget behavior still needs device-level verification:</p><ul><li>placing more than one instance and configuring each differently;</li><li>changing or deleting the selected preset or category;</li><li>tapping from a cold start and while the app is already open;</li><li>checking collection refreshes after Flutter edits;</li><li>resizing widgets across supported launcher grids;</li><li>verifying light and dark mode, localized strings, and accessibility descriptions;</li><li>confirming behavior after process death, device restart, and app update.</li></ul><p>Loop’s automated screenshot flow can seed and refresh widget content, but Android deliberately doesn’t let an app silently place widgets on the user’s home screen. Initial placement and launcher-specific behavior remain real device concerns.</p><h3>The trade-off: duplicated data, not duplicated ownership</h3><p>This architecture does duplicate data. The same preset exists in Flutter’s local repository and in an Android widget snapshot.</p><p>The important part is that it doesn’t duplicate authority.</p><p>Flutter can create, edit, migrate, and delete presets. Android can validate a projection, remember per-widget selections, and render it. Native configuration chooses an ID from the projection; it doesn’t rewrite the preset. A widget tap returns that ID; it doesn’t send an old copy of the timer configuration back into the app.</p><p>That narrow promise makes eventual consistency acceptable. If synchronization fails, a widget can briefly be stale. The next initialization, resume, or edit republishes the snapshot. The app’s actual data remains intact.</p><p>For Loop, this was a better fit than introducing a shared database or a larger cross-platform abstraction. The boundary is small enough to inspect, the native side can function when Flutter isn’t running, and both sides have one clear job.</p><p>The broader lesson applies beyond home screen widgets. App shortcuts, notifications, watch surfaces, and other platform-owned UI often don’t need access to an application’s complete architecture. They need a durable read model and a stable action contract.</p><p>Loop is available on <a href="https://play.google.com/store/apps/details?id=com.tomvogel.loop">Google Play</a> if you want to see the preset widgets in the context of the full timer app or you can check out it’s <a href="https://loop-timer.pages.dev/">website</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae0dab0325b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why My Flutter Timer Needed a Native Android Service]]></title>
            <link>https://medium.com/@vogel_tom/why-my-flutter-timer-needed-a-native-android-service-887133d5ab21?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/887133d5ab21</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-08-08T06:01:01.457Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How I combined a smooth Flutter UI with a Kotlin foreground service, monotonic time, and state snapshots.</blockquote><h3>The problem</h3><p>I started building Loop because I wanted a timer that stayed out of the way. Set an active interval, add a rest period, choose the number of rounds, and start.</p><p>The UI was the enjoyable part: animated progress, clear controls, and a timer that felt responsive. The difficult part only became obvious when I pressed the Home button.</p><p>A countdown that works while the app is open is easy. A countdown that remains accurate while Flutter is paused, the screen is off, or Android is busy doing something else is a different problem.</p><p>This article explains the approach I ended up using in Loop: Flutter owns the visible experience, while a native Android foreground service keeps track of the session in the background. When the app becomes active again, Flutter asks Android for a snapshot and restores its state from that.</p><p>For Loop, I only needed to solve one narrow case: keeping a user-started interval timer accurate while Flutter was paused.</p><figure><img alt="Loop timer screen beside an Android notification showing the same running interval." src="https://cdn-images-1.medium.com/max/1024/1*YieaZY6oAm_s8Tzg4BcJiQ.png" /><figcaption><em>Loop interval timer running alongside its Android foreground-service notification.</em></figcaption></figure><h3>Why a Dart timer was not enough</h3><p>My first instinct was the obvious one: update the countdown periodically in Dart and let the UI react to it.</p><p>That is fine while the Flutter engine is active. It is not a good foundation for background timing. Once the app moves into the background, execution can be throttled or paused. Even in the foreground, repeatedly subtracting a fixed duration introduces another problem: the callback does not necessarily run at the exact requested time.</p><p>If a callback scheduled every 50 milliseconds arrives late, subtracting another 50 milliseconds hides the delay instead of accounting for it. Small errors accumulate. An interval timer makes those errors especially visible because every active-to-rest transition depends on the previous one.</p><p>The rule I ended up relying on was simple:</p><blockquote><em>A timer should be derived from elapsed time, not from the number of ticks received.</em></blockquote><p>Flutter could still animate the interface smoothly. I just did not want that animation to be the only source of truth once the app was no longer active.</p><h3>Splitting the responsibilities</h3><p>Loop effectively has two cooperating timer implementations:</p><ul><li>Flutter manages the screen, controls, animations, navigation, and Riverpod state.</li><li>A Kotlin foreground service manages elapsed background time, phase transitions, sound, vibration, a partial wake lock, and the ongoing notification.</li></ul><p>Both start from the same configuration. User actions such as pause, resume, or adding ten seconds are sent to both sides. When Flutter resumes, it treats the native snapshot as authoritative and rebuilds the UI from it.</p><p>That boundary kept the platform-specific part relatively small. I did not move the whole feature into Kotlin; Android only owns the work that needs to survive Flutter being paused.</p><figure><img alt="Architecture diagram showing Flutter communicating with an Android foreground service through a MethodChannel." src="https://cdn-images-1.medium.com/max/1024/1*DkNE4tnmdn4JgrlhjUR4BQ.png" /><figcaption><em>Flutter owns the experience; the Android service owns background timing.</em></figcaption></figure><h3>Keeping the Flutter boundary boring</h3><p>I wanted the Flutter side to know as little as possible about Android. The interface contains only the operations the timer screen actually needs:</p><pre>abstract interface class TimerBackgroundService {<br>  Future&lt;void&gt; start(TimerBackgroundConfiguration configuration);<br>  Future&lt;void&gt; pause();<br>  Future&lt;void&gt; resume();<br>  Future&lt;void&gt; adjust(Duration amount);<br>  Future&lt;TimerBackgroundSnapshot?&gt; getSnapshot();<br>  Future&lt;void&gt; stop();<br>}</pre><p>The Android implementation uses one MethodChannel:</p><pre>class AndroidTimerBackgroundService implements TimerBackgroundService {<br>  static const _channel = MethodChannel(<br>    &#39;com.tomvogel.loop/timer_background_service&#39;,<br>  );<br><br>  @override<br>  Future&lt;void&gt; adjust(Duration amount) async {<br>    if (Platform.isAndroid) {<br>      await _channel.invokeMethod&lt;void&gt;(&#39;adjust&#39;, {<br>        &#39;durationMs&#39;: amount.inMilliseconds,<br>      });<br>    }<br>  }<br><br>  @override<br>  Future&lt;TimerBackgroundSnapshot?&gt; getSnapshot() async {<br>    if (!Platform.isAndroid) return null;<br><br>    final snapshot = await _channel.invokeMethod&lt;Map&lt;Object?, Object?&gt;&gt;(<br>      &#39;getSnapshot&#39;,<br>    );<br>    return snapshot == null<br>        ? null<br>        : TimerBackgroundSnapshot.fromMap(snapshot);<br>  }<br>}</pre><p>I provide this implementation through Riverpod. That is useful for more than dependency injection aesthetics: widget tests can replace the native service with a small fake and verify that tapping pause, resume, or the adjustment controls sends the expected command.</p><p>On the Android side, MainActivity translates those method calls into service intents:</p><pre>when (call.method) {<br>    &quot;start&quot; -&gt; startTimerService(<br>        LoopTimerService.startIntent(<br>            context = this,<br>            activeDurationMs = call.argument&lt;Number&gt;(&quot;activeDurationMs&quot;)!!.toLong(),<br>            restDurationMs = call.argument&lt;Number&gt;(&quot;restDurationMs&quot;)!!.toLong(),<br>            totalSets = call.argument&lt;Number&gt;(&quot;totalSets&quot;)!!.toInt(),<br>            hapticsEnabled = call.argument&lt;Boolean&gt;(&quot;hapticsEnabled&quot;) == true,<br>            soundEnabled = call.argument&lt;Boolean&gt;(&quot;soundEnabled&quot;) == true,<br>        ),<br>    )<br>    &quot;pause&quot; -&gt; sendTimerAction(LoopTimerService.ACTION_PAUSE, result)<br>    &quot;resume&quot; -&gt; sendTimerAction(LoopTimerService.ACTION_RESUME, result)<br>    &quot;getSnapshot&quot; -&gt; result.success(LoopTimerService.currentSnapshot())<br>}</pre><p>There is no continuous stream of timer ticks crossing the channel. That would add unnecessary traffic and create awkward ownership questions. Flutter renders its own progress while visible; the channel is used for commands and reconciliation.</p><h3>The part that prevents drift</h3><p>The Android service runs a Handler callback every 50 milliseconds, but the callback interval is not used to calculate the remaining time. It only determines how often the service checks the clock.</p><p>For the actual timing, I use Android’s monotonic SystemClock.elapsedRealtime() and store a deadline:</p><pre>val now = SystemClock.elapsedRealtime()<br>lastAccountingMs = now<br>deadlineMs = now + remainingMs</pre><p>Using a monotonic clock matters. Wall-clock time can jump when the user changes the time, the network corrects it, or the timezone changes. An interval timer should not gain five minutes because the device clock was adjusted.</p><p>Each update accounts for the real elapsed time:</p><pre>private fun accountUntil(now: Long) {<br>    while (isRunning &amp;&amp; !isComplete &amp;&amp; now &gt;= deadlineMs) {<br>        addElapsed(max(0L, deadlineMs - lastAccountingMs))<br>        remainingMs = 0L<br>        val boundary = deadlineMs<br>        transitionAt(boundary)<br>        lastAccountingMs = boundary<br>    }<br>    if (isRunning &amp;&amp; !isComplete) {<br>        addElapsed(max(0L, now - lastAccountingMs))<br>        remainingMs = max(0L, deadlineMs - now)<br>        lastAccountingMs = now<br>    }<br>}</pre><p>The while loop is the important detail. Imagine Android does not run the callback for several seconds. That delay might span not only the end of the active interval, but also an entire short rest period. Handling a single transition would leave the timer in the wrong phase.</p><p>By advancing at the stored boundary and continuing until now is inside the current phase, the timer can catch up across multiple transitions. The next deadline is based on the previous boundary, not on the delayed callback, so one late update does not shift every interval that follows.</p><p>This was the difference between a UI that counts down and a timer I could actually trust.</p><figure><img alt="Timeline showing a delayed callback processing the missed boundaries at 10 and 15 seconds." src="https://cdn-images-1.medium.com/max/1024/1*wrtMl8rJ9kYmlWVRBknZIg.png" /><figcaption><em>A delayed callback can cross more than one phase boundary.</em></figcaption></figure><h3>The timer is a state machine</h3><p>Once background timing was involved, treating the feature as a single countdown stopped making sense. Loop tracks:</p><ul><li>the current phase (ACTIVE or REST),</li><li>the current set,</li><li>completed active intervals,</li><li>remaining time,</li><li>separately accumulated active and rest time,</li><li>running and completed states.</li></ul><p>The transition code also handles two product-specific edge cases: a rest duration of zero skips directly to the next active set, and zero total sets means the timer continues indefinitely.</p><p>In simplified form, the transition looks like this:</p><pre>private fun transitionAt(boundaryMs: Long) {<br>    if (phase == Phase.ACTIVE) {<br>        completedIntervals++<br>        if (totalSets &gt; 0 &amp;&amp; currentSet &gt;= totalSets) {<br>            completeTimer()<br>            return<br>        }<br>        if (restDurationMs == 0L) {<br>            currentSet++<br>        } else {<br>            phase = Phase.REST<br>        }<br>    } else {<br>        phase = Phase.ACTIVE<br>        currentSet++<br>    }<br>    remainingMs = currentPhaseDurationMs()<br>    deadlineMs = boundaryMs + remainingMs<br>}</pre><p>Calling it a state machine may sound grand for a small timer, but it made the edge cases easier to name and test. “What happens after the last active phase?” is much clearer than trying to infer everything from one decreasing integer.</p><h3>Running as a foreground service</h3><p>Android requires visible, user-meaningful work to be represented appropriately. Loop starts a foreground service when the user starts a timer and shows an ongoing notification containing the phase, remaining time, and current set.</p><p>The service updates internally every 50 milliseconds for timely phase transitions and countdown cues. Updating an Android notification that often would be wasteful, so I only rebuild it when the displayed second changes:</p><pre>private fun updateNotification(force: Boolean) {<br>    val second = ceil(remainingMs / 1000.0).toLong()<br>    if (!force &amp;&amp; second == lastNotificationSecond) return<br>    lastNotificationSecond = second<br>    getSystemService(NotificationManager::class.java)<br>        .notify(NOTIFICATION_ID, buildNotification())<br>}</pre><p>That separation is small but useful: timing precision and presentation frequency are two different concerns.</p><p>The service also acquires a partial wake lock while the timer is running. It releases it when paused, completed, stopped, or destroyed. Sound and vibration cues live in the native service as well, otherwise those cues could disappear at exactly the moment the user puts the phone down and leaves the app.</p><p>Loop declares the service as a specialUse foreground service because it is a user-started interval timer with audible and haptic phase cues. The manifest includes the foreground-service, notification, vibration, and wake-lock permissions required by that implementation.</p><p>One boundary is intentional: the service uses START_NOT_STICKY, and removing Loop from the recent-apps screen stops the timer and clears its in-memory snapshot. This implementation is designed for normal background use, not for resurrecting a session after the user has explicitly closed the app or after process death.</p><h3>Handing state back to Flutter</h3><p>While Loop is open, Flutter uses an AnimationController to keep the progress display smooth. At the same time, the native service maintains its own timer state. This duplication is manageable because there is a clear reconciliation point: when the app returns to the foreground.</p><p>The service publishes a compact snapshot:</p><pre>private fun publishSnapshot() {<br>    setSnapshot(<br>        hashMapOf(<br>            &quot;phase&quot; to phase.name.lowercase(Locale.ROOT),<br>            &quot;remainingMs&quot; to remainingMs,<br>            &quot;currentSet&quot; to currentSet,<br>            &quot;isRunning&quot; to isRunning,<br>            &quot;isComplete&quot; to isComplete,<br>            &quot;completedIntervals&quot; to completedIntervals,<br>            &quot;activeElapsedMs&quot; to activeElapsedMs,<br>            &quot;restElapsedMs&quot; to restElapsedMs,<br>        ),<br>    )<br>}</pre><p>Flutter requests that snapshot when the app lifecycle changes back to resumed:</p><pre>useOnAppLifecycleStateChange((previous, current) {<br>  if (current != AppLifecycleState.resumed ||<br>      previous == null ||<br>      previous == AppLifecycleState.resumed) {<br>    return;<br>  }<br>  unawaited(() async {<br>    final snapshot = await backgroundService.getSnapshot();<br>    if (snapshot == null || !context.mounted) return;<br>    timerNotifier.restore(snapshot);<br>    timerController.stop();<br>    final timer = ref.read(timerProvider);<br>    timerController.duration = timer.phaseDuration;<br>    timerController.value = timer.phaseDuration == Duration.zero<br>        ? 0<br>        : 1 - snapshot.remaining.inMicroseconds /<br>            timer.phaseDuration.inMicroseconds;<br>    if (snapshot.isRunning) timerController.forward();<br>  }());<br>});</pre><p>The Riverpod notifier restores the logical phase, set, running state, completed intervals, and accumulated durations. The animation controller then resumes from the corresponding visual progress.</p><p>This means Flutter does not need to replay every missed tick or guess how long it was suspended. It just asks: “Where is the timer now?”</p><h3>Small decisions that prevented larger bugs</h3><p>A few implementation details turned out to carry a surprising amount of weight.</p><h3>Pause means pausing everything</h3><p>Pausing stops the handler callbacks, accounts for time up to the pause instant, releases the wake lock, publishes a snapshot, and updates the notification immediately. Resuming creates a new deadline from the stored remaining duration.</p><h3>Adjustments are clamped</h3><p>Adding or subtracting ten seconds cannot push the remaining time below zero or above the duration of the current phase. Reaching zero triggers the same transition path as a natural deadline, rather than creating a second set of transition rules.</p><h3>Completion is allowed to finish its feedback</h3><p>The service releases the wake lock and marks the timer complete immediately, but waits 1.2 seconds before removing the foreground notification and stopping itself. That small grace period gives the final sound time to play.</p><h3>Stop is idempotent on the Flutter side</h3><p>Navigation, disposal, and a deliberate swipe-to-end action can all attempt to stop the service. Loop guards that call so the native stop command is only sent once.</p><h3>The contract is testable without Android</h3><p>Because the platform service sits behind an interface and a Riverpod provider, Flutter widget tests use a fake implementation. The state notifier separately tests finite sets, endless mode, zero-length rests, and restoring elapsed durations from a native snapshot.</p><p>Those are not glamorous details, but timer bugs tend to hide in transitions rather than in the happy-path countdown.</p><h3>What I learned</h3><p>The most useful lesson was not “use a foreground service.” It was learning to separate three things I initially treated as one:</p><ol><li><strong>Timekeeping</strong> — based on a monotonic clock and explicit deadlines.</li><li><strong>Product state</strong> — active/rest phases, rounds, pause, completion, and accumulated durations.</li><li><strong>Presentation</strong> — Flutter animations and a notification that only needs second-level updates.</li></ol><p>Once those responsibilities were separate, the platform boundary became much easier to reason about.</p><p>If I were building a clock that had to survive process death, device restarts, or scheduled execution hours later, this in-memory snapshot would not be enough. I would persist the configuration and timestamps, then define explicit recovery behavior. Loop does not need that contract: it runs a timer the user has just started and stops when they explicitly remove the app.</p><p>That narrower promise is part of the design. Reliability is easier to achieve when “reliable” has a precise meaning.</p><h3>The result</h3><p>Loop can continue an active interval when the user switches apps or turns off the display. The Android notification stays useful, sound and haptic cues still arrive, and the Flutter UI catches up when the user returns.</p><p>From the outside, it feels like a timer doing what timers are supposed to do. Underneath, it is a Flutter interface and a small native state machine agreeing on who owns what.</p><p>I built this for <strong>Loop</strong>, my customizable interval timer for workouts, focus sessions, studying, stretching, and everyday routines.</p><p><a href="https://play.google.com/store/apps/details?id=com.tomvogel.loop">Try Loop on Google Play</a> or <a href="https://loop-timer.pages.dev/">explore the Loop website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=887133d5ab21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dart Speed]]></title>
            <link>https://medium.com/@vogel_tom/the-dart-speed-035272e9d46d?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/035272e9d46d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 18:34:54 GMT</pubDate>
            <atom:updated>2024-04-02T08:44:59.481Z</atom:updated>
            <content:encoded><![CDATA[<p>The speed of a programming language is important, even if I rarely need it. I’m happy if the language I use is fast. Although Dart is not the fastest language on the market, I appreciate its cool and clean syntax. I have therefore compared the speed of <a href="https://dart.dev/">Dart</a>, <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript </a>and <a href="https://www.rust-lang.org/">Rust</a>.</p><figure><img alt="Cover image" src="https://cdn-images-1.medium.com/max/1024/1*O-MlfflhFZ1JoIId7OJG2w.png" /></figure><p>I think everyone knows that Rust will be the fastest. But in my speed test, the results really blew me away. So this article is not only for Dart developers, but also for Rust and JavaScript developers.</p><h3>Benchmark</h3><p>Thebenchmark evaluates the performance of a Fibonacci function. The function is run 100 times with an input of 35 in each script. Due to hardware limitations, higher input values cannot be tested on my laptop. The JavaScript code was executed with <a href="https://deno.com/">Deno</a>. Now I will show you the Dart, JavaScript and Rust implementation.</p><h4>How the benchmark was run:</h4><p>I coded a small PowerShell script to run each program 10 times and give me the time for each execution, also calculating the average execution time. I tried to keep the environment relatively similar on each benchmark and also ran the benchmark 3 times to make sure the numbers were similar and there were no big gaps.</p><p><strong>System Hardware:</strong><br><strong><em>Processor:</em></strong> AMD Ryzen 7 4800H with Radeon Graphics 2.90 GHz<br><strong><em>Installed RAM:</em></strong> 16,0 GB (15,4 GB usable)<br><strong><em>System:</em></strong> Type 64-bit operating system, x64-based processor<br><strong>Windows: </strong>Windows 11 Home, Version 23H2</p><blockquote>DISCLAIMER: THIS IS NOT A PROFESSIONAL BENCHMARK, IT IS ONLY TO GIVE AN INDICATION OF THE SPEED.</blockquote><p>This is the PowerShell script:</p><pre># Prompting the user for the command to execute<br>$command = Read-Host &quot;Enter the command to execute (e.g., &#39;py main.py&#39;)&quot;<br><br># Initializing total time variable<br>$totalTime = 0<br><br># Running the command 10 times and calculating the total time<br>for ($i = 1; $i -lt 11; $i++) {<br>    $executionTime = Measure-Command { Invoke-Expression &quot;&amp; $command&quot; }<br>    $totalTime += $executionTime.TotalMilliseconds<br>    Write-Host &quot;Execution $i Time: $($executionTime.TotalMilliseconds) milliseconds&quot;<br>}<br><br># Calculating average time<br>$averageTime = $totalTime / 10<br>Write-Host &quot;Average Execution Time: $averageTime milliseconds&quot;</pre><h4>Dart</h4><figure><img alt="Dart code" src="https://cdn-images-1.medium.com/max/1024/1*kk3kNCHt8pLaGpnfZcUWpA.png" /></figure><h4>JavaScript</h4><figure><img alt="JavaScript code" src="https://cdn-images-1.medium.com/max/1024/1*giXOP58Iujdopl4PW-S7Ew.png" /></figure><h4>Rust</h4><figure><img alt="Rust code" src="https://cdn-images-1.medium.com/max/1024/1*gaaIDIqk4wLzq1FBqKhzXw.png" /></figure><p>As you can see, it is the same code, just translated between languages.</p><h3>Results</h3><figure><img alt="JavaScript Benchmark Result" src="https://cdn-images-1.medium.com/max/1024/1*vtEGP36SMBi0AwJtdx4PQg.png" /></figure><p>Average: 9940.12497 ms<br>Compared to Dart: 159 % slower<br>Compared to Rust: 138.67 % slower</p><figure><img alt="Dart Benchmark Result" src="https://cdn-images-1.medium.com/max/1024/1*hqb--9-O-Wk6hPO5KtO4vw.png" /></figure><p>Average: 6221.07265 ms<br>Compared to JavaScript: 159 % faster<br>Compared to Rust: 86.79 % slower</p><figure><img alt="Rust Benchmark Result" src="https://cdn-images-1.medium.com/max/1024/1*nhed8cpu4x1lrzXE6LzQsA.png" /></figure><p>Average: 71.67717 ms<br>Compared to JavaScript: 138.67 % faster<br>Compared to Dart: 86.79 % faster</p><h3>Conclusion</h3><p>If you just look at JavaScript and Dart, Dart looks like a fast language. Add Rust to the mix and you can see just how fast it can be. As a little motivation to all JavaScript developers, I could not include Python in this benchmark because the run never finished.</p><p>So, if you want to know how important Dart’s speed is in real app development, I will write an article about it in the near future. If you have any questions or improvements, please let me know 😊.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=035272e9d46d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to publish a Flutter Windows application outside the Microsoft Store ]]></title>
            <link>https://medium.com/@vogel_tom/how-to-publish-a-flutter-windows-application-outside-the-microsoft-store-49bb9d25555c?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/49bb9d25555c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 21:07:47 GMT</pubDate>
            <atom:updated>2023-10-12T21:07:47.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfha2IET_XiYK-s_VrW75g.png" /></figure><p>I was building my open source application <a href="https://github.com/zTomz/OpenScribe/tree/main">OpenScribe</a>. When I released it, the first thing I had to do was provide an <a href="https://learn.microsoft.com/de-de/windows/msix/">.msix installer</a>. I thought that should be easy, right? But I spent about 6 hours working on this problem.</p><p><a href="https://github.com/zTomz/OpenScribe">GitHub - zTomz/OpenScribe: OpenScribe is an open source editor app that aims to replace the standard Windows editor with advanced features.</a></p><p>My first attempt was to use the <a href="https://pub.dev/packages/msix">msix package</a> from <a href="https://pub.dev/">pub.dev</a>. But now, after a bit of research, I can tell you that you should only use .msix for the Microsoft Store. If, like me, you want to publish your application with a nice installer under GitHub releases, you should follow this article.</p><p>When I was working with msix, my main problem was the certificate. The msix package comes with a test certificate, but when you run the installer, you cannot install your application because the certificate is not registered. I tried to create my own certificate using OpenSSL, but that did not work either. After 2.5 hours of trying to solve the problem, I knew this was not the way to make it work.</p><p>The <a href="https://github.com/alexrintt">GitHub user</a> who posted the problem told me about a tool called <a href="https://wixtoolset.org/">WiX Toolset</a>. I haven’t tried it yet, but it didn’t seem to work for me either. But after a bit of research, I found the tool that solved my problem:</p><p><a href="https://jrsoftware.org/isinfo.php">Inno Setup</a></p><p>With this tool you can create a nice installation setup that supports multiple languages and offers many nice features like creating a desktop shortcut, launching the application when it is installed and much more.</p><h3>How to install and use Inno Setup</h3><p>Visit <a href="https://jrsoftware.org/isdl.php">https://jrsoftware.org/isdl.php</a> and click on the “US” text button under “Download Sites”.</p><figure><img alt="Screenshot, where to find installation" src="https://cdn-images-1.medium.com/max/1024/1*0xV5LbMWYZ48ZuLy_VMSBw.png" /></figure><p>Now you can go through the installer and use the default settings. Once installed, open it. In the pop-up dialog, click “Create a new script file using the Setup Wizard”.</p><figure><img alt="Helper screenshot" src="https://cdn-images-1.medium.com/max/1024/1*8wa5OqbJ7oUtXj44h-j3Kg.png" /></figure><p>Then click “OK”, and on the next screen, click “Next”. Now you can fill in the fields with your information. Then click “Next”. On the following screen (Application Folder) you can accept the default settings and click “Next” again. Now you need to specify your main executable. To get your main executable you have to run:</p><pre>flutter build windows</pre><p>inside your Flutter project from the command line. This will build your application and take about 60 seconds. Now you can specify your main executable in the following path:</p><pre>C:\Path\To\Your\Flutter\Project\build\windows\runner\Release\your_app_name.exe</pre><p>Now go to “Other application files” and click “Add file(s)”. In the File Explorer dialog, click on each file in the same folder as your executable. Now click “Add Folder” under “Add File(s)” button. In the File Explorer dialog, browse to the path of your executable and click on the folder called “data” in the same folder as your executable. This is the folder that contains your assets, fonts, and whatever else you have included in your Flutter application. Once you have added the “data” folder, a dialog will appear. It asks if you want to include files from the subfolders. Click “Yes” and the folder will be added to the list. Now click on the folder entry in the list view (the path must end with “…\data\*”) and click on “Edit”. In the dialog under “Destination subfolder” you have to enter “data” in the text field and click “OK”. You have successfully added all the necessary files and folders to your setup.</p><figure><img alt="Helper image" src="https://cdn-images-1.medium.com/max/651/1*4GZCHLGNbt6IB4ckuwgYEQ.png" /></figure><p>On the next screen you can specify if you want to associate a file extension with your application, the file will have the icon of your application and it will be opened with your application. For example, in my application <a href="https://github.com/zTomz/OpenScribe">OpenScribe</a>, I have the file format .odoc. Which I added to the setup. But you can disable it. On the next screen you can specify whatever you want, I will go with the default settings. On the next screen you can choose a license file. I will use the license file from my GitHub repo. In the file explorer, my license file did not show up, you probably need to change in the lower right corner to show all file extensions. The next window should be self-explanatory. Then you can select the languages you want the installer to support. I recommend clicking the “Select all” button on the top right. Now you are almost done, on this screen you can fill in the fields as you like. It’s also self-explanatory. When you have filled the fields according to your needs, you can click on “Next”, “Next” and “Finish”. The program will ask you if you want to compile the script directly, I recommend reading this article to the end because there is still one problem to solve. Your installer is now working, but only for users who have the Visual Studio build tools and Flutter installed. I’ll explain how to fix this in the next chapter.</p><h3>Make your app available to everyone</h3><p>To make your application available to everyone, you need to add the following three files to the installer script. The required filenames are:</p><ul><li>msvcp140.dll</li></ul><blockquote>C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\msvcp140.dll</blockquote><ul><li>vcruntime140.dll:</li></ul><blockquote>C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\vcruntime140.dll</blockquote><ul><li>vcruntime140_1.dll</li></ul><blockquote>C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\vcruntime140_1.dll</blockquote><p>I have included the path to the files, but I am not sure if the paths are the same on your machine. If you cannot find the files, you will need to go to your Visual Studio installation, which should be under “C:\Program Files (x86)\Microsoft Visual Studio\2019\” and use File Explorer to locate the files.</p><p>Now in the “Inno Setup” application you have to make a small change to the script. Under [Files] you have to add the following lines:</p><pre>Source: &quot;C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\msvcp140.dll&quot;; DestDir: &quot;{app}&quot;; Flags: ignoreversion<br>Source: &quot;C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\vcruntime140.dll&quot;; DestDir: &quot;{app}&quot;; Flags: ignoreversion<br>Source: &quot;C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x86\vcruntime140_1.dll&quot;; DestDir: &quot;{app}&quot;; Flags: ignoreversion</pre><p>When you run the script now, it should create the installer in the output directory you specified. You can easily add the installer to your GitHub repository or to your website. I think this is the easiest and best way to distribute your Flutter Windows application.</p><p>Thanks for reading to the end, creating an installer was a nightmare for me and I hope this article can fix that for other people. ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49bb9d25555c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Material 3 To Do App with Flutter]]></title>
            <link>https://medium.com/@vogel_tom/creating-a-material-3-to-do-app-with-flutter-aa07bb888395?source=rss-76d49330fd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa07bb888395</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Tom]]></dc:creator>
            <pubDate>Sun, 21 May 2023 14:35:23 GMT</pubDate>
            <atom:updated>2023-05-22T16:46:43.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkAC8NUJv628Wgxy_Xs6mg.png" /></figure><p><a href="https://github.com/zTomz/ToDo-s">Complete source-code.</a></p><p><a href="https://tommyyy.gumroad.com/l/todos?_gl=1*1kik0yg*_ga*NDkxMTcyMjU2LjE2ODQ2Njc2NjE.*_ga_6LJN6D94N6*MTY4NDc3MzQ4Mi41LjEuMTY4NDc3MzU3MS4wLjAuMA..">App on Gumroad.</a></p><p>First you need to create your project, I only create it for android, but you can also specify windows, web and ios.</p><pre>flutter create --platforms=android todoapp</pre><p>Next insert the following code into your main.dart.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:todoapp/pages/home_page.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;To Do App&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const HomePage(),<br>    );<br>  }<br>}</pre><p>In your main method you only run your app, in my app you define a meterial app with title “To Do App” and in your theme you have your seed color to deepPurple, change this to whatever you want. Important is you have set the “useMaterial3: true” flag.</p><p>Your home is HomePage, under lib/pages/home_page.dart, which you can see in this code:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold();<br>  }<br>}</pre><p>This is simple a StatefulWidget with in this case the name HomePage.</p><h3>Adding dynamic color</h3><p>To add dynamic color to your app, you need to add the <a href="https://pub.dev/packages/dynamic_color">dynamic_color</a>:</p><pre>flutter pub add dynamic_color</pre><p>Next, you need to update your MyApp class to this:</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  static final defaultLightColorScheme = ColorScheme.fromSwatch(<br>    primarySwatch: Colors.blue,<br>  );<br><br>  static final defaultDarkColorScheme = ColorScheme.fromSwatch(<br>    primarySwatch: Colors.blue,<br>    brightness: Brightness.dark,<br>  );<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return DynamicColorBuilder(<br>      builder: (lightColorScheme, darkColorScheme) {<br>        return MaterialApp(<br>          title: &#39;Flutter Demo&#39;,<br>          theme: ThemeData(<br>            colorScheme: lightColorScheme ?? defaultLightColorScheme,<br>            useMaterial3: true,<br>          ),<br>          darkTheme: ThemeData(<br>            colorScheme: darkColorScheme ?? defaultDarkColorScheme,<br>            useMaterial3: true,<br>          ),<br>          themeMode: ThemeMode.dark,<br>          home: const HomePage(),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>Exit the debug mode and run the app again to see the changes.</p><h3>Building the app</h3><p>In your home_page.dart under Scaffold create an app bar like this:</p><pre>appBar: AppBar(<br>   title: const Text(&quot;To Do App&quot;),<br>),</pre><p>Next, add a floating action button to the Scaffold, the logic will be implemented later on:</p><pre>floatingActionButton: FloatingActionButton.extended(<br>    onPressed: () {},<br>   label: const Text(&quot;Add Todo&quot;),<br>   icon: const Icon(Icons.add_rounded),<br>),</pre><p>In the Scaffold’s body add a padding and a list view sepperated:</p><pre>body: Padding(<br>    padding: const EdgeInsets.symmetric(<br>       horizontal: 16,<br>    ),<br>    child: ListView.separated(itemBuilder: itemBuilder, separatorBuilder: separatorBuilder, itemCount: itemCount),<br>),</pre><p>Now create a file under lib/models/todo.dart with the following content, this will later define our todo.</p><pre>class ToDo {<br>  final String title;<br>  final String content;<br>  final bool completed;<br>  final DateTime from;<br><br>  ToDo({<br>    required this.title,<br>    required this.content,<br>    required this.completed,<br>    required this.from,<br>  });<br>}</pre><p>In the item builder in the list view seperated, add the following code:</p><pre>(context, index) =&gt; ListTile(<br>              title: Text(todos[index].title),<br>              subtitle: Text(todos[index].content),<br>              trailing: IconButton(<br>                onPressed: () {<br>                  final todo = todos[index];<br>                  setState(() {<br>                    todos[index] = ToDo(<br>                      title: todo.title,<br>                      content: todo.content,<br>                      completed: !todo.completed,<br>                      from: todo.from,<br>                    );<br>                  });<br>                },<br>                icon: Icon(<br>                  todos[index].completed<br>                      ? Icons.check_circle_rounded<br>                      : Icons.radio_button_unchecked_rounded,<br>                ),<br>              ),<br>              tileColor: Theme.of(context).colorScheme.primaryContainer,<br>              shape: RoundedRectangleBorder(<br>                borderRadius: BorderRadius.circular(10),<br>              ),<br>            ),</pre><p>Here you define a list tile with title and subtitle. In the trailing, the onPressed method, toggles the completed status of the todo. The icon, is displayed differently, if the todo is completed or not. Than is the tile color defined, and a little border radius, wich looks better.</p><p>As the sepperator builder you only define a SizedBox with height 10, this adds a little space between the elements.</p><pre>(context, index) =&gt; const SizedBox(<br>            height: 10,<br>          ),</pre><p>At this point, you have to create a list of type todo at the top of your class</p><pre>class _HomePageState extends State&lt;HomePage&gt; {<br>  List&lt;ToDo&gt; todos = [];<br>  ...</pre><p>Now you can as the item count in your sepperated list view the todos.lenght:</p><pre>itemCount: itodos.length</pre><p>The problem is you have now a todo list, but no todos. Create two TextEditingController’s and a dialog, shown in the following code.</p><pre>late TextEditingController newTodoTitleController;<br>late TextEditingController newTodoContentController;<br><br>@override<br>void initState() {<br>  super.initState();<br><br>  newTodoTitleController = TextEditingController();<br>  newTodoContentController = TextEditingController();<br>}<br><br>@override<br>void dispose() {<br>  newTodoTitleController.dispose();<br>  newTodoContentController.dispose();<br><br>  super.Dispose();<br>}</pre><p>The following code is in the onPressed of your floatingActionButton:</p><pre>showDialog(<br>            context: context,<br>            builder: (context) =&gt; SimpleDialog(<br>              title: const Text(&quot;Add new Todo&quot;),<br>              contentPadding: const EdgeInsets.all(15),<br>              children: [<br>                TextField(<br>                  controller: newTodoTitleController,<br>                  decoration: const InputDecoration(<br>                    border: OutlineInputBorder(),<br>                    hintText: &quot;Title&quot;,<br>                  ),<br>                ),               const SizedBox(height: 10),<br>                TextField(<br>                  controller: newTodoContentController,<br>                  decoration: const InputDecoration(<br>                    border: OutlineInputBorder(),<br>                    hintText: &quot;Content&quot;,<br>                  ),<br>                ),<br>                const SizedBox(height: 15),<br>                ElevatedButton.icon(<br>                  onPressed: () {<br>                    setState(() {<br>                      todos.add(<br>                        ToDo(<br>                          title: newTodoTitleController.text,<br>                          content: newTodoContentController.text,<br>                          completed: false,<br>                          from: DateTime.now(),<br>                        ),<br>                      );<br>                    });<br><br>                    newTodoTitleController.clear();<br>                    newTodoContentController.clear();<br><br>                    Navigator.of(context).pop();<br>                  },<br>                  icon: const Icon(Icons.done_rounded),<br>                  label: const Text(&quot;Add Todo&quot;),<br>                ),<br>              ],<br>            ),<br>          );</pre><p>This will show a dialog where the user can enter a title and content of the todo.</p><p>Now we need the functionality to delete todos, we can do this by adding a new package, <a href="https://pub.dev/packages/flutter_slidable">flutter_slidable</a>.</p><pre>flutter pub add flutter_slidable</pre><p>Next, wrap your ListTile with a Slidable widget. And insert the following code:</p><pre>Slidable(<br>            key: ValueKey(todos[index]),<br>            startActionPane: ActionPane(<br>              motion: const ScrollMotion(),<br>              dismissible: DismissiblePane(<br>                onDismissed: () {<br>                  setState(() {<br>                    todos.removeAt(index);<br>                  });<br>                },<br>              ),<br>              children: [<br>                SlidableAction(<br>                  onPressed: (context) {},<br>                  borderRadius: BorderRadius.circular(10),<br>                  backgroundColor: Theme.of(context).colorScheme.errorContainer,<br>                  foregroundColor:<br>                      Theme.of(context).colorScheme.onErrorContainer,<br>                  icon: Icons.delete,<br>                  label: &#39;Delete&#39;,<br>                ),<br>              ],<br>            ),<br>            endActionPane: ActionPane(<br>              motion: const ScrollMotion(),<br>              children: [<br>                SlidableAction(<br>                  onPressed: (context) {},<br>                  borderRadius: BorderRadius.circular(10),<br>                  backgroundColor: Theme.of(context).colorScheme.errorContainer,<br>                  foregroundColor:<br>                      Theme.of(context).colorScheme.onErrorContainer,<br>                  icon: Icons.date_range_rounded,<br>                  label:<br>                      &quot;${_addLeadingZero(todos[index].from.hour)}:${_addLeadingZero(todos[index].from.minute)}, ${todos[index].from.day}&quot;,<br>                ),<br>              ],<br>            ),<br>            child: ListTile(...),<br>          ),</pre><p>With this code, you can slide the ListTile to the write, this will delete the todo, or you slide the ListTile to the left, then the current date will be shown.</p><p>Now everything works, except one thing. When you close the app and open it again, nothing is saved. If you want, you can use pre build libraries like hive or objectbox, which will do the most things for you, but I want to write it by myself.</p><h3>Save and Load</h3><p>You need two packages, <a href="https://pub.dev/packages/path_provider">path_provider </a>for your applications path in the storage and <a href="https://pub.dev/packages/encrypt">encrypt</a>, if you want to encrypt and decrypt your data. Note, when you write it by yourself, I think the performance will be slightly worse, but for such a small project, this will be ok. I did a performance test, where 5 todos are saved and it only took 0:00:00.006468. So, you can’t even recognize. The file size is for 5 normal todos round about 700 bytes, wich is in my opinion also ok. Here is the code to add the two packages:</p><pre>dart pub add encrypt<br>flutter pub add path_provider</pre><p>Now, create a file under lib/models/data_storage.dart, wich looks like:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:io&#39;;<br><br>import &#39;package:encrypt/encrypt.dart&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39;;<br>import &#39;package:todoapp/models/todo.dart&#39;;<br><br>class DataStorage {<br>  static final DataStorage instance = DataStorage._internal();<br><br>  factory DataStorage() {<br>    return instance;<br>  }<br><br>  DataStorage._internal() {<br>    // initialization logic<br>    <br>    // Load the todo file<br>    _loadTodoFile();<br>  }<br>  <br>  // Variables for encryption and decryption<br>  static final Key key = Key.fromBase64(&quot;q5Yy9hkTRhf6cfkBW47sF3eqTneMkGM&quot;); // This is your key, you can use whatever you want<br>  static final Encrypter encrypter = Encrypter(AES(key));<br>  static final IV iv = IV.fromLength(16);<br>  <br>  // Your todo file<br>  File todoStorage = File(&quot;&quot;);<br><br>  Future _loadTodoFile() async {<br>    todoStorage = File(<br>      &quot;${(await getApplicationDocumentsDirectory()).path}/todos.json&quot;,<br>    );<br>  }<br><br>  Future&lt;void&gt; saveTodos(List&lt;ToDo&gt; todos) async {<br>    // Create a list for all todos to save them<br>    List&lt;String&gt; encryptedTodos = List.generate(<br>      todos.length,<br>      (index) =&gt; jsonEncode(todos[index].toEncryptJson(encrypter, iv)),<br>    );<br>    <br>    // Write to the file<br>    todoStorage.writeAsStringSync(&#39;{&quot;todos&quot;: $encryptedTodos}&#39;);<br>  }<br>}</pre><p>In your todo class, add the following function:</p><pre>Map&lt;String, dynamic&gt; toEncryptJson(Encrypter encrypter, IV iv) {<br>    return {<br>      &quot;title&quot;: encrypter.encrypt(title, iv: iv).base64,<br>      &quot;content&quot;: encrypter.encrypt(content, iv: iv).base64,<br>      &quot;completed&quot;: completed,<br>      &quot;from&quot;: encrypter.encrypt(from.millisecondsSinceEpoch.toString(), iv: iv).base64,<br>    };<br>  }</pre><p>This function, converts your todo model to json and encrypts it.</p><p>In your HomePage, everywhere you change the state of the todos (create, save, delete), call the following function:</p><pre>await DataStorage.instance.saveTodos(todos);</pre><p>Now we only need a function, wich reads the todos and loads them to memory. In the DataStorage class, add the following function:</p><pre>Future&lt;List&lt;ToDo&gt;&gt; loadTodos() async {<br>    // Make sure todo file is loaded<br>    if (todoStorage.path == &quot;&quot;) {<br>      await _loadTodoFile();<br>    }<br><br>    List&lt;ToDo&gt; todos = [];<br><br>    // Read the json data<br>    final data = jsonDecode(todoStorage.readAsStringSync());<br>    List encryptedTodos = data[&quot;todos&quot;];<br><br>    // Iterate over each todo and convert it to the todo class<br>    for (int i = 0; i &lt; encryptedTodos.length; i++) {<br>      Map&lt;String, dynamic&gt; json = encryptedTodos[i];<br>      todos.add(ToDo.fromJson(json, encrypter, iv));<br>    }<br><br>    return todos;<br>  }</pre><p>In your ToDo class at the following function, wich converts the json to a ToDo class:</p><pre>ToDo.fromJson(Map&lt;String, dynamic&gt; json, Encrypter encrypter, IV iv)<br>      : title = encrypter.decrypt(Encrypted.fromBase64(json[&quot;title&quot;]), iv: iv),<br>        content =<br>            encrypter.decrypt(Encrypted.fromBase64(json[&quot;content&quot;]), iv: iv),<br>        completed = json[&quot;completed&quot;],<br>        from = DateTime.fromMillisecondsSinceEpoch(<br>          int.parse(<br>            encrypter.decrypt(Encrypted.fromBase64(json[&quot;from&quot;]), iv: iv),<br>          ),<br>        );</pre><p>In your HomePage, add this method:</p><pre>void _loadTodos() async {<br>    // Load todos<br>    todos = await DataStorage.instance.loadTodos();<br>    setState(() {});<br><br>    // Update the ui after one second, otherwise the todo list will not use the meterial you color scheme<br>    await Future.delayed(const Duration(seconds: 1));<br>    setState(() {});<br>  }</pre><p>In your initState method add the following:</p><pre>_loadTodos();<br><br>    // Checking if brightness changed, than setState to update the ui, otherwise the todo list <br>    // will not use the material you design<br>    final window = WidgetsBinding.instance.window;<br>    // This callback is called every time the brightness changes.<br>    window.onPlatformBrightnessChanged = () async {<br>      await Future.delayed(const Duration(seconds: 1));<br>      setState(() {});<br>    };</pre><p>The last thing to do is to change the app name and add an app icon. To change the app name, go to android\app\src\main\AndroidManifest.xml and change the android:label to your app name:</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;application<br>        android:label=&quot;your-app-name&quot;<br>        ...</pre><p>For your app icon, you have to create an image for example in Figma, with size 512x512. Next, visit <a href="https://www.appicon.co/">App Icon Generator</a> and select your image. Then generate the app icons and extract the zip folder you have downloaded.</p><p>In the folder go to the android folder, there you have 5 other folders. In your Flutter project open the following path and replace the icons.</p><p>Path: android\app\src\main\res</p><p>Tada, you have a working todo app, with light and dark mode as well as material you support. Also, you have written your own save and load system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa07bb888395" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>