<?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 Akshay Maurya on Medium]]></title>
        <description><![CDATA[Stories by Akshay Maurya on Medium]]></description>
        <link>https://medium.com/@codenameakshay?source=rss-b46a5c18f171------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NyMm-1DHqTGBRXvYQ340fA.png</url>
            <title>Stories by Akshay Maurya on Medium</title>
            <link>https://medium.com/@codenameakshay?source=rss-b46a5c18f171------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:22:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codenameakshay/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[“I Just Deleted Some Data in a Tunnel and It Still Synced” — Building an Offline-First Sync Engine…]]></title>
            <link>https://codenameakshay.medium.com/i-just-deleted-some-data-in-a-tunnel-and-it-still-synced-building-an-offline-first-sync-engine-75ee0b49eced?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ee0b49eced</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 08:54:48 GMT</pubDate>
            <atom:updated>2026-06-10T08:54:48.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>“I Just Deleted Some Data in a Tunnel and It Still Synced” — Building an Offline-First Sync Engine in Flutter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFYZjlI1AQYYuqzkTV5H2Q.png" /></figure><p>You know that moment when you’re in a subway, make a change in an app, step out, open it again, and everything is exactly where it should be? Not a spinner. Not a “something went wrong.” Just… there. Everyone else already sees your change.</p><p>That’s the feeling we wanted for every action in the app. Create something. Delete it. Restore it. Rename it. Don’t worry about your connection — the app will figure it out.</p><p>Here’s how we built it, what broke, and the things nobody tells you about local-first architecture until you’re 3 schema migrations deep and questioning your life choices.</p><h3>The Core Idea: Optimistic Execution With a Safety Net</h3><p>Most apps handle offline like this:</p><pre>try {<br>  await api.createItem(item);<br>} catch (e) {<br>  showSnackBar(&#39;No internet. Try again later.&#39;);<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEjI6SIIHBdRxXI40%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEjI6SIIHBdRxXI40%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZWs2bzZvbGZxdnlueHFreGlwaTJuNHJobWJuMmRsbmNrZGQ3dnAweiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3oEjI6SIIHBdRxXI40%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/735b564b0d13836269e4f862697b1530/href">https://medium.com/media/735b564b0d13836269e4f862697b1530/href</a></iframe><p>This is terrible. The user did the work. They filled out the form. They picked the category. They tapped “Save.” And now you’re telling them “try again later” like it’s their fault?</p><p>Instead, here’s what we wanted:</p><ol><li>The user taps “Delete.”</li><li>The item disappears from the UI <strong>instantly</strong> — before the API call even finishes.</li><li>If the API succeeds, great. If it fails with a transient error (or no connection), the mutation gets queued.</li><li>When connectivity returns, the queue replays itself in order.</li><li>If the server permanently rejects a queued mutation (404, 409, 403), we surface it as a conflict the user can resolve.</li><li>Oh, and when the server assigns a real ID to something we created locally with a temporary UUID, we need to rewrite that ID across every row that references it. Atomically.</li></ol><p>This is not a “try/catch with a toast.” This is a sync engine with a mutation queue, stateful retry logic, and atomic temp-ID resolution. Let’s build it.</p><h3>Step 1: The Pending Mutation Table (Drift)</h3><p>Every offline mutation lives in a SQLite table. We used Drift (née Moor) because it gives you type-safe queries on top of raw SQLite — the best of both worlds.</p><pre>class PendingMutations extends Table {<br>  TextColumn get id =&gt; text()();                 // UUID v4<br>  TextColumn get domain =&gt; text()();             // &#39;item&#39;, &#39;comment&#39;, &#39;list&#39;<br>  TextColumn get action =&gt; text()();             // &#39;create&#39;, &#39;delete&#39;, &#39;update&#39;<br>  TextColumn get entityId =&gt; text().nullable()(); // local UUID or server ID<br>  TextColumn get payloadJson =&gt; text()();         // full mutation body as JSON<br>  DateTimeColumn get createdAt =&gt; dateTime()();<br>  TextColumn get status =&gt; text().withDefault(const Constant(&#39;pending&#39;))();<br>  TextColumn get errorMessage =&gt; text().nullable()();<br>  IntColumn get retryCount =&gt; integer().withDefault(const Constant(0))();<br><br>  @override<br>  Set&lt;Column&gt; get primaryKey =&gt; {id};<br>}</pre><p>A few design decisions worth mentioning:</p><ul><li><strong>payloadJson stores the full mutation body</strong> as a JSON string. This lets the replay handler reconstruct exactly what was sent — no guessing, no stale references. When the user deletes item id: &quot;abc&quot; while offline, the payload is {&quot;id&quot;: &quot;abc&quot;}. When connectivity returns, we replay that exact payload against the API.</li><li><strong>domain + </strong><strong>action form a dispatch key.</strong> The sync engine maintains a Map&lt;String, MutationHandler&gt; where the key is the domain (like &#39;item&#39;). When it replays a queued mutation, it looks up the handler for that domain and calls it with the action and payload.</li><li><strong>status is a four-state machine:</strong> pending → in_flight → (removed on success) or failed or conflict. The conflict state is special — it means the server permanently rejected this mutation (404, 409, 403), and the user needs to decide what to do.</li></ul><h3>Step 2: The Sync Engine (The Brain)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXIqCQx02E1U9W%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FXIqCQx02E1U9W&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZ2VwbjJxeW1lZGk4cXVtZnJ1NWcxNzcxY2tkbnJqZHc2MnFycXN1OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FXIqCQx02E1U9W%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/2134f4d38bb2e92618e8a380dde61da6/href">https://medium.com/media/2134f4d38bb2e92618e8a380dde61da6/href</a></iframe><p>Here’s the heart of the system. The SyncEngine has one job: execute a mutation, either online (directly) or offline (queued + replayed later).</p><pre>Future&lt;T&gt; execute&lt;T&gt;({<br>  required String domain,<br>  required String action,<br>  required String? entityId,<br>  required Map&lt;String, dynamic&gt; payload,<br>  required Future&lt;T&gt; Function() apiCall,<br>  required Future&lt;void&gt; Function(T result) onSuccess,<br>  required Future&lt;void&gt; Function() optimisticUpdate,<br>  required Future&lt;void&gt; Function() rollback,<br>}) async {<br>  if (connectivity.isOnline) {<br>    try {<br>      final result = await apiCall();<br>      await onSuccess(result);<br>      return result;<br>    } on HttpException catch (e) {<br>      final status = e.statusCode;<br>      if (status != null &amp;&amp; status &gt;= 500) {<br>        // Transient server error — fall through to the offline path.<br>        // We treat 5xx the same as &quot;no connection&quot; because the server<br>        // is temporarily unavailable, but the user&#39;s intent is still valid.<br>      } else {<br>        rethrow; // 4xx is a hard failure — let the caller handle it.<br>      }<br>    }<br>  }<br><br>  // Offline path (or transient server failure)<br>  await optimisticUpdate();<br>  await queue.enqueue(<br>    domain: domain,<br>    action: action,<br>    entityId: entityId,<br>    payloadJson: jsonEncode(payload),<br>  );<br>  throw OfflineMutationQueued();<br>}</pre><p>This method is called from every mutating repository method. Here’s what a delete looks like:</p><pre>Future&lt;void&gt; deleteItem(String id) async {<br>  try {<br>    await syncEngine.execute&lt;void&gt;(<br>      domain: &#39;item&#39;,<br>      action: &#39;delete&#39;,<br>      entityId: id,<br>      payload: {&#39;id&#39;: id},<br>      apiCall: () =&gt; apiClient.deleteItem(id),<br>      onSuccess: (_) async =&gt; itemDao.softDelete(id),<br>      optimisticUpdate: () =&gt; itemDao.softDelete(id),<br>      rollback: () =&gt; itemDao.restore(id),<br>    );<br>  } on OfflineMutationQueued {<br>    // Already soft-deleted locally. The UI already reflects it.<br>    // The queue will replay when connectivity returns.<br>  }<br>}</pre><p>Notice something crucial: <strong>optimisticUpdate and </strong><strong>onSuccess do the same thing.</strong> Both call softDelete. The difference is timing — optimisticUpdate runs immediately (before the API call even starts, when we know we&#39;re going off the offline path), while onSuccess runs after a successful API call.</p><p>This means the local database is always the source of truth for what the UI renders. The server is a mirror. When the mirror is unavailable, the local truth still holds.</p><h3>Step 3: The Replay Loop (Where It Gets Interesting)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7aCTfyhYawdOXcFW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fanimation-loop-3o7aCTfyhYawdOXcFW&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcnB6MTN4N3kzcnFidzEzNWNqajAybWg1amtqc2g1aGdxbG82MjVoMyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7aCTfyhYawdOXcFW%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fa0aec05c9aa9340ad4a4e823bc5d1f/href">https://medium.com/media/1fa0aec05c9aa9340ad4a4e823bc5d1f/href</a></iframe><p>When connectivity comes back, the sync engine replays every pending mutation in insertion order. This is where the magic happens — the app silently reconciles everything the user did while offline.</p><pre>Future&lt;void&gt; replayQueue() async {<br>  if (_replaying) return;          // Prevent concurrent replays<br>  _replaying = true;<br><br>  try {<br>    final pending = await queue.getPending();     // ORDER BY created_at ASC<br>    for (final mutation in pending) {<br>      final handler = handlers[mutation.domain];<br>      if (handler == null) continue;              // No handler registered<br><br>      await queue.markInFlight(mutation.id);      // pending → in_flight<br><br>      try {<br>        final payload = jsonDecode(mutation.payloadJson);<br>        final result = await handler(mutation.action, mutation.entityId, payload);<br><br>        // If this was a &quot;create&quot; mutation and the server returned a real ID,<br>        // atomically swap the temporary UUID for the real one everywhere.<br>        if (mutation.action == &#39;create&#39; &amp;&amp; result[&#39;id&#39;] != null &amp;&amp; mutation.entityId != null) {<br>          await tempIdResolver.resolve(mutation.entityId!, result[&#39;id&#39;], mutation.domain);<br>        }<br><br>        await queue.remove(mutation.id);          // Done — delete from queue<br>      } on HttpException catch (e) {<br>        final code = e.statusCode ?? 0;<br>        if (code == 404 || code == 409 || code == 403) {<br>          await queue.markConflict(mutation.id, e.toString());<br>        } else {<br>          await queue.incrementRetryAndReset(mutation.id);  // pending again, retry later<br>          break;  // Stop replaying — if one fails transiently, retry the whole queue later<br>        }<br>      } catch (e) {<br>        await queue.incrementRetryAndReset(mutation.id);<br>        break;<br>      }<br>    }<br>  } finally {<br>    _replaying = false;<br>  }<br>}</pre><p>A few decisions here:</p><p><strong>We break on transient failure.</strong> If mutation #3 fails with a 503, we don’t try mutation #4. They likely depend on each other — you can’t delete something you haven’t created yet, and you can’t update something that doesn’t exist. The whole queue will retry on the next connectivity pulse.</p><p><strong>We mark conflicts separately.</strong> A 404 on replay means the server no longer has that entity — maybe it was deleted from another device. A 409 means a version conflict. A 403 means unauthorized. These are not transient. We mark them as conflict and let the UI surface them with &quot;Discard&quot; and &quot;Retry&quot; buttons.</p><p><strong>The queue is linear, not parallel.</strong> This is intentional. Order matters. Create item → add details → assign owner. You can’t parallelize that.</p><h3>Step 4: The Temp ID Problem (And Why It Needs a Transaction)</h3><p>Here’s the sneaky one. When a user creates something while offline, they don’t have a server-assigned ID yet. So we generate a local UUID (v4) and use it everywhere:</p><ul><li>The main record: id = &quot;a1b2c3d4-...&quot;</li><li>Related child rows: parent_id = &quot;a1b2c3d4-...&quot;</li><li>Metadata rows: referenced by that same ID</li></ul><p>When the server processes the creation, it assigns its own ID: &quot;res_7f8a9b0c&quot;. Now we have a problem: every row that references the old temporary ID is dangling. Worse, if we update them one at a time and the app crashes halfway through, we&#39;re in an inconsistent state.</p><p>The solution: <strong>a single Drift transaction that rewrites the temp ID across all referencing tables atomically.</strong></p><pre>class TempIdResolver {<br>  final AppDatabase db;<br><br>  Future&lt;void&gt; resolve(String tempId, String realId, String domain) {<br>    return db.transaction(() async {<br>      switch (domain) {<br>        case &#39;item&#39;:<br>          // Update the item&#39;s own ID<br>          await (db.update(db.items)..where((t) =&gt; t.id.equals(tempId)))<br>              .write(ItemsCompanion(id: Value(realId)));<br><br>          // Update all foreign key references in related tables<br>          await (db.update(db.itemDetails)..where((d) =&gt; d.itemId.equals(tempId)))<br>              .write(ItemDetailsCompanion(itemId: Value(realId)));<br><br>          await (db.update(db.tags)..where((t) =&gt; t.itemId.equals(tempId)))<br>              .write(TagsCompanion(itemId: Value(realId)));<br>      }<br>    });<br>  }<br>}</pre><p>Why a transaction? Because SQLite transactions are atomic. If the app crashes mid-transaction, SQLite rolls back the entire thing. You can’t end up with half-rewritten foreign keys. This is one of those things that sounds obvious in retrospect but is surprisingly easy to skip when you’re focused on the happy path.</p><p>Without this, you’d have orphaned rows — child records pointing to a parent ID that no longer exists. The app would render blank screens or, worse, crash on a foreign key violation.</p><h3>Step 5: The Connectivity Monitor (With Debounce)</h3><p>You don’t want to fire the replay loop on every network flutter. Switch from WiFi to cellular? Two events. Go through a tunnel? Three. The connectivity_plus package fires rapidly under real-world conditions.</p><pre>class ConnectivityMonitor {<br>  final BehaviorSubject&lt;ConnectivityState&gt; _controller =<br>      BehaviorSubject.seeded(ConnectivityState.online);<br><br>  ConnectivityMonitor() {<br>    connectivity.onConnectivityChanged<br>        .debounceTime(const Duration(milliseconds: 300))  // &lt;--- the secret sauce<br>        .listen(_onChanged);<br>  }<br><br>  void _onChanged(List&lt;ConnectivityResult&gt; results) {<br>    final online = results.any((r) =&gt; r != ConnectivityResult.none);<br>    final newState = online ? ConnectivityState.online : ConnectivityState.offline;<br>    if (newState != _controller.value) {<br>      _controller.add(newState);     // Only emit on actual change<br>    }<br>  }<br>}</pre><p>Then, in the sync engine’s constructor:</p><pre>_connectivity.state<br>    .where((s) =&gt; s == ConnectivityState.online)<br>    .listen((_) =&gt; replayQueue());</pre><p>The debounceTime(300ms) is critical. Without it, you&#39;d kick off the replay loop 3 times in 200 milliseconds when a user emerges from a subway. With it, you wait until connectivity has actually settled.</p><p>We also seed the initial state as online instead of offline. This is a deliberate choice — if the monitor can&#39;t initialize (e.g., in a unit test where the platform channel isn&#39;t available), we assume online and let API calls fail naturally rather than queueing everything defensively.</p><h3>Step 6: Wiring It Together (The Repository Layer)</h3><p>Here’s the glue. Each domain registers a mutation handler with the sync engine at construction time:</p><pre>class ItemRepository {<br>  ItemRepository({<br>    required ItemDao dao,<br>    required ItemApiClient client,<br>    required SyncEngine syncEngine,<br>  }) : _dao = dao, _client = client, _syncEngine = syncEngine {<br>    // Register how to replay item mutations when connectivity returns<br>    _syncEngine.registerHandler(&#39;item&#39;, _replayMutation);<br>  }<br><br>  Future&lt;Map&lt;String, dynamic&gt;&gt; _replayMutation(<br>    String action,<br>    String? entityId,<br>    Map&lt;String, dynamic&gt; payload,<br>  ) async {<br>    switch (action) {<br>      case &#39;delete&#39;:<br>        await _client.deleteItem(payload[&#39;id&#39;] as String);<br>        return {};<br>      case &#39;restore&#39;:<br>        await _client.restoreItem(payload[&#39;id&#39;] as String);<br>        return {};<br>      case &#39;update&#39;:<br>        final id = entityId!;<br>        final data = payload[&#39;data&#39;] as Map&lt;String, dynamic&gt;;<br>        return await _client.updateItem(id, data);<br>      default:<br>        throw StateError(&#39;Unknown replay action: $action&#39;);<br>    }<br>  }<br><br>  // ... the deleteItem(), restoreItem(), updateItem() methods from earlier<br>}</pre><p>The repo becomes the canonical place where “how to mutate an item” is defined — both online and offline. The sync engine doesn’t know what an item is. It just knows “when connectivity returns, call this function for domain ‘item’ with this payload.”</p><h3>The Happy Path, Visualized</h3><p>Here’s what happens when a user deletes something in a tunnel:</p><pre>                                          ┌─────────────┐<br>  User taps &quot;Delete&quot;  ──────────────────▶ │  deleteItem()│<br>                                          └──────┬──────┘<br>                                                 │<br>                                    ┌────────────▼────────────┐<br>                                    │ connectivity.isOnline?   │<br>                                    └─────┬──────────────┬────┘<br>                                          │ NO           │ YES<br>                                          ▼              ▼<br>                              ┌──────────────────┐  ┌──────────────┐<br>                              │ optimisticUpdate()│  │  apiCall()   │<br>                              │ (UI updates NOW)  │  └──────┬───────┘<br>                              └────────┬─────────┘         │<br>                                       │              ┌────▼────┐<br>                                       ▼              │ Success? │<br>                              ┌──────────────────┐    └─┬────┬───┘<br>                              │ enqueue mutation  │  YES │    │ NO (5xx)<br>                              │ in SQLite queue   │      │    │<br>                              └────────┬─────────┘      │    │<br>                                       │                 │    │<br>                                       ▼                 ▼    │<br>                              ┌──────────────────┐  ┌────────┐ │<br>                              │ OfflineMutation   │  │onSuccess│ │<br>                              │ Queued (ignored)  │  │  + done │ │<br>                              └────────┬─────────┘  └────────┘ │<br>                                       │                        │<br>                                       │    ┌───────────────────┘<br>                                       │    │ (fall through to<br>                                       │    │  offline path)<br>                           ┌───────────▼────▼───────────┐<br>                           │ User emerges from tunnel    │<br>                           │ ConnectivityMonitor fires   │<br>                           │ (after 300ms debounce)      │<br>                           └───────────┬────────────────┘<br>                                       │<br>                                       ▼<br>                              ┌──────────────────┐<br>                              │  replayQueue()    │<br>                              │  fetches pending  │<br>                              │  ORDER BY created │<br>                              └────────┬─────────┘<br>                                       │<br>                              ┌────────▼─────────┐<br>                              │ markInFlight(id)  │<br>                              │ call handler(...) │<br>                              │ → apiClient call  │<br>                              └────────┬─────────┘<br>                                       │<br>                                 200 OK?<br>                                  │    │<br>                                  ▼    ▼<br>                              ┌─────┐ ┌──────────┐<br>                              │remove│ │markConflict│<br>                              │ done │ │ or retry   │<br>                              └─────┘ └──────────┘</pre><p>No spinners. No toasts. No “please try again.” Just… done.</p><h3>Edge Cases You’ll Hit (And How We Handled Them)</h3><h4>1. What if the user creates an item offline, then comes online, but someone else already created a conflicting one?</h4><p>We treat create mutations specially in the replay loop. When the server responds with a result[&#39;id&#39;], we know the creation succeeded — and we run the temp ID resolver to atomically swap the local UUID for the server ID. If the server returns 409 (conflict), the mutation gets marked as conflict and surfaced to the user.</p><h4>2. What if the user deletes an item on Device A while Device B is offline?</h4><p>Device B’s replay will hit a 404 because the item literally doesn’t exist anymore. We mark it as a conflict — not silently discard it. The user on Device B sees “This item no longer exists” with a “Discard” button. Silently swallowing mutations is worse than surfacing a conflict, because the user might have made other decisions based on that mutation.</p><h4>3. What if the replay loop itself fails mid-way?</h4><p>We break out of the loop and let the next connectivity pulse retry it. The mutations that already succeeded are already deleted from the queue. The failed one is reset to pending (with incremented retry count). This means the queue is always in a consistent state — mutations are either fully replayed and removed, or still pending.</p><h4>4. What if the app is killed during replay?</h4><p>Each mutation is individually marked in_flight before the API call. On next app launch, getPending() returns only mutations with status pending (not in_flight), so any mutation that was in in_flight when the app was killed gets ignored. This leaves it orphaned. To handle this, add an onAppStart check that resets any in_flight mutations back to pending before the first replay.</p><h3>Bonus: Things I’d Do Differently Next Time</h3><ol><li><strong>Don’t queue by default for every domain.</strong> Some mutations (like “send message” or “react”) don’t make sense to replay hours later. We added a requiresConnectivity flag on certain mutations that skip the queue entirely and show a toast instead. Not everything needs to be offline-first.</li><li><strong>The payload JSON column is a double-edged sword.</strong> It’s simple and universal, but you lose type safety. If the payload shape changes between app versions, replaying an old mutation can fail cryptically. Consider versioning your payloads or using protobuf with a schema registry.</li><li><strong>The replay loop needs a ceiling.</strong> If a mutation permanently fails and gets reset to pending repeatedly, it&#39;ll retry on every connectivity pulse forever. A maxRetries column with an exponential backoff strategy (retry after 1s, 2s, 4s, 8s…) would be kinder to both the server and the user&#39;s battery.</li><li><strong>Test with real network conditions.</strong> Unit tests with NativeDatabase.memory() and a fake API are great for logic. But nothing beats testing on actual spotty WiFi, airplane mode toggles, and subway tunnels. We discovered the debounce-time issue (and the in_flight orphan problem) only through manual testing on real devices.</li><li><strong>Surface pending count in the UI.</strong> A small badge showing “2 pending changes” builds trust. Users who know their offline changes are queued feel confident. Users who see a silent spinner feel anxious. A tiny bit of transparency goes a long way.</li></ol><h3>The Big Insight</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7abldj0b3rxrZUxW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcarlton-fresh-prince-dance-3o7abldj0b3rxrZUxW&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExa3lwN3R5ZmpqaHp4OWtlbnBtNnc5aXdlbG1xY2ZncHU5MjBxYWwzZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7abldj0b3rxrZUxW%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="335" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e435e6dd734ccedc0a8fe60e6afdb6/href">https://medium.com/media/61e435e6dd734ccedc0a8fe60e6afdb6/href</a></iframe><p>Offline-first isn’t a feature. It’s an architecture decision that touches every layer of your app:</p><ul><li><strong>Database layer</strong>: Your schema needs a pending mutations table and temp-ID-aware foreign keys.</li><li><strong>Repository layer</strong>: Every mutating method gets wrapped in the execute() pattern with optimistic updates.</li><li><strong>Sync layer</strong>: You need a replay loop, a conflict model, and connectivity-driven triggers.</li><li><strong>UI layer</strong>: Your widgets must render from local state, not server responses. The server is a reconciliation target, not a source of truth.</li></ul><p>Once you commit to this, something magical happens: your app feels <strong>fast</strong> even when the network is slow. It feels <strong>reliable</strong> even when the network is gone. And your users stop thinking about whether they have a connection — they just use the app.</p><p>And that, honestly, is the whole point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ee0b49eced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Level Up Your Dart Terminal Apps with dart_tui]]></title>
            <link>https://levelup.gitconnected.com/how-to-level-up-your-dart-terminal-apps-with-dart-tui-3eb5a1a80790?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb5a1a80790</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 14:33:03 GMT</pubDate>
            <atom:updated>2026-03-26T14:33:03.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Build beautiful, interactive terminal UIs in Dart — the Flutter way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Lmm1VxDXoxpGoWIRwvZPUg.gif" /></figure><p>Look at that. That’s a <strong>Dart terminal app</strong>. No Flutter. No web. Pure Dart, running in your terminal.</p><p>If your CLI tools still look like this:</p><pre>Loading…<br>Done.<br>Error.</pre><p>This article is for you.</p><h3>The Problem with `print()`</h3><p>When you start building Dart CLI tools, print() feels fine. It gets the job done. But the moment your tool needs to show progress, ask for user input, or display structured data — you hit a wall fast.</p><p>You start hacking together ANSI escape codes. You find a spinner package. You string it all together and it kind of works. But it’s messy, it flickers, and adding one more feature breaks everything.</p><p>There’s a better way.</p><h3>Meet dart_tui</h3><p><a href="https://pub.dev/packages/dart_tui"><strong>dart_tui</strong></a> is an Elm-style terminal UI framework for Dart. It gives you 20+ components — spinners, progress bars, text inputs, tables, file pickers, and more — all with a clean, structured architecture.</p><p>It’s heavily inspired by <a href="https://github.com/charmbracelet/bubbletea">Bubble Tea</a> (the Go TUI framework) and brings that same quality to the Dart ecosystem.</p><p>If you’re a Flutter developer, you’re going to feel right at home.</p><h3>If You Know Flutter, You Already Know dart_tui</h3><p>This is the part Flutter developers will appreciate.</p><p>Flutter has <strong>StatefulWidget → setState → build</strong>. dart_tui has <strong>Model → update → view</strong>. They’re the same idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41XotxRXukpBQB4VhQhGDA.png" /></figure><p>Here’s a simple counter in Flutter vs dart_tui side by side:</p><p><strong>Flutter:</strong></p><pre>class CounterWidget extends StatefulWidget { ... }<br>class _CounterState extends State&lt;CounterWidget&gt; {<br>  int count = 0;<br><br>  void _increment() =&gt; setState(() =&gt; count++);<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Text(&#39;Count: $count&#39;);<br>}</pre><p><strong>dart_tui:</strong></p><pre>final class CounterModel extends TeaModel {<br>  CounterModel({this.count = 0});<br>  final int count;<br><br>  @override<br>  (Model, Cmd?) update(Msg msg) {<br>    if (msg is _IncrementMsg) {<br>      return (CounterModel(count: count + 1), null);<br>    }<br>    return (this, null);<br>  }<br><br>  @override<br>  View view() =&gt; newView(&#39;Count: $count\n\nPress q to quit.&#39;);<br>}</pre><p>Same mental model. Immutable state, pure update function, declarative view. The difference is your “widget tree” is a string you render to the terminal.</p><p>So, without any further ado, let’s get started.</p><h3>Step 1: Installation</h3><p>Add dart_tui to your pubspec.yaml:</p><pre>dependencies:<br>  dart_tui: ^1.0.0</pre><p>Then run:</p><pre>dart pub get</pre><p>That’s it. No native dependencies, no platform-specific setup. Pure Dart.</p><h3>Step 2: Spinners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2AcruR39i3fqRKbz8Lqzyg.gif" /></figure><p>The first thing any CLI tool needs is a good loading indicator. dart_tui has built-in animated spinners with multiple styles.</p><pre>import &#39;package:dart_tui/dart_tui.dart&#39;;<br><br>final class LoadingModel extends TeaModel {<br>  LoadingModel({this.spinner = const SpinnerModel()});<br>  final SpinnerModel spinner;<br><br>  @override<br>  Cmd? init() =&gt; tick(const Duration(milliseconds: 80), (_) =&gt; _TickMsg());<br><br>  @override<br>  (Model, Cmd?) update(Msg msg) {<br>    if (msg is _TickMsg) {<br>      return (<br>        LoadingModel(spinner: spinner.tick()),<br>        tick(const Duration(milliseconds: 80), (_) =&gt; _TickMsg()),<br>      );<br>    }<br>    if (msg is KeyPressMsg &amp;&amp; msg.key == &#39;q&#39;) return (this, () =&gt; quit());<br>    return (this, null);<br>  }<br><br>  @override<br>  View view() =&gt; newView(&#39;${spinner.view()} Fetching data...\n\nPress q to quit&#39;);<br>}</pre><p>You get dots, braille patterns, and more — all driven by TickMsg so they fit naturally into your update loop.</p><h3>Step 3: Progress Bars</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*tcjRqWU1Gtywh1IdwTL_mA.gif" /></figure><p>Download progress, install steps, file processing — progress bars are everywhere in good CLI tools.</p><pre>final class DownloadModel extends TeaModel {<br>  DownloadModel({this.progress = 0.0});<br>  final double progress;<br><br>  @override<br>  Cmd? init() =&gt; tick(const Duration(milliseconds: 100), (_) =&gt; _TickMsg());<br><br>  @override<br>  (Model, Cmd?) update(Msg msg) {<br>    if (msg is _TickMsg) {<br>      final next = (progress + 0.02).clamp(0.0, 1.0);<br>      if (next &gt;= 1.0) return (DownloadModel(progress: 1.0), () =&gt; quit());<br>      return (<br>        DownloadModel(progress: next),<br>        tick(const Duration(milliseconds: 100), (_) =&gt; _TickMsg()),<br>      );<br>    }<br>    return (this, null);<br>  }<br><br>  @override<br>  View view() =&gt; newView(<br>    ProgressModel(progress: progress, width: 40, showPercent: true).view(),<br>  );<br>}</pre><p>The ProgressModel handles the █░░░ rendering. You just feed it a double from 0.0 to 1.0.</p><h3>Step 4: Text Input</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nQenrTKgtmk8xkxqnryoLQ.gif" /></figure><p>Interactive prompts, login forms, configuration wizards — text input is where CLI tools get genuinely useful.</p><pre>final input = TextInputModel(<br>  placeholder: &#39;Enter your name...&#39;,<br>  charLimit: 80,<br>);</pre><p>You get:</p><ul><li><strong>Placeholder text</strong></li><li><strong>Character limits</strong></li><li><strong>Password mode</strong> (shows ● instead of characters)</li><li><strong>Tab completion</strong> for autocomplete suggestions</li><li><strong>Real-time validation</strong> with ValidationFailedMsg</li><li><strong>Focus/blur</strong> for multi-field forms</li></ul><p>For multi-field forms, Tab moves focus between fields automatically — just like FocusNode in Flutter.</p><h3>Step 5: Tables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*NQK3g2mKyuwq2n1MJ15qcA.gif" /></figure><p>Nothing says “professional CLI tool” like a properly formatted data table with scrollable rows.</p><pre>final table = TableModel(<br>  columns: [<br>    TableColumn(title: &#39;Name&#39;, width: 20),<br>    TableColumn(title: &#39;Version&#39;, width: 10),<br>    TableColumn(title: &#39;Status&#39;, width: 12),<br>  ],<br>  rows: packages.map((p) =&gt; [p.name, p.version, p.status]).toList(),<br>  styles: TableStyles(<br>    header: const Style(isBold: true, foregroundRgb: RgbColor(137, 180, 250)),<br>    selected: const Style(foregroundRgb: RgbColor(166, 227, 161)),<br>  ),<br>);</pre><p>Arrow keys scroll through rows. You can style headers, selected rows, and individual cells using styleFunc for conditional formatting — think DataTable in Flutter but for the terminal.</p><h3>Step 6: Styled Layouts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7YGDwIbXLpcAfDgUi74LAg.gif" /></figure><p>dart_tui has a full styling system inspired by <a href="https://github.com/charmbracelet/lipgloss">Lipgloss</a>. Borders, padding, colors, alignment, gradients — all composable.</p><pre>// Rounded border box with padding<br>final box = const Style(<br>  border: Border.rounded,<br>  foregroundRgb: RgbColor(137, 180, 250),<br>).withWidth(40).withPadding(EdgeInsets.all(1)).render(content);<br><br>// Gradient text<br>final title = gradientText(&#39;dart_tui&#39;, [<br>  const RgbColor(203, 166, 247), // mauve<br>  const RgbColor(116, 199, 236), // sky<br>  const RgbColor(166, 227, 161), // green<br>]);<br><br>// Side-by-side layout<br>final ui = joinHorizontal(AlignVertical.top, [leftPane, rightPane]);</pre><p>joinHorizontal, joinVertical, and place are layout helpers that work like Row, Column, and Center in Flutter. Your mental model transfers directly.</p><h3>Step 7: Quick Wins with Prompt Helpers</h3><p>Not every tool needs a full MUV loop. Sometimes you just want to ask a quick question and move on. dart_tui has one-liner helpers for that:</p><pre>// Selection menu<br>final selected = await promptSelect([&#39;Create project&#39;, &#39;Open project&#39;, &#39;Settings&#39;]);<br><br>// Yes/no confirmation<br>final confirmed = await promptConfirm(&#39;Delete this file?&#39;);<br><br>// Free text<br>final name = await promptInput(&#39;Enter project name:&#39;);</pre><p>These return Future&lt;T?&gt; — null if the user cancels with Escape, the value if they confirm. Drop them anywhere in your main() and you instantly have interactive prompts.</p><h3>Bonus #1: Your Terminal Just Became Clickable 🖱️</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*fr989Hsm4jMsMUYMpISnIw.gif" /></figure><p>This one genuinely surprises people. Most developers don’t know terminals can track mouse input. dart_tui supports full mouse events — clicks, hover, scroll, release — out of the box.</p><pre>@override<br>(Model, Cmd?) update(Msg msg) {<br>  if (msg is MouseClickMsg) {<br>    // msg.x, msg.y — exact cell coordinates of the click<br>    // msg.button — left, right, middle, wheel<br>    return (MyModel(lastClick: &#39;${msg.x},${msg.y}&#39;), null);<br>  }<br>  if (msg is MouseWheelMsg) {<br>    return (MyModel(scrolled: true), null);<br>  }<br>  return (this, null);<br>}<br><br>@override<br>View view() =&gt; newView(<br>  content,<br>  mouseMode: MouseMode.cellMotion, // enable mouse tracking<br>);</pre><p>You can build clickable menus, draggable elements, scroll areas — things people assume are impossible in a terminal. Pair this with the styling system and you can render “buttons” that actually respond to clicks.</p><h3>Bonus #2: Split Panes with Canvas Compositing 🎨</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*44Z2LcnKKV3aTelatjqJCw.gif" /></figure><p>This is the one that makes Flutter developers do a double take. dart_tui has a <strong>Canvas</strong> system — you paint styled blocks at arbitrary (x, y) positions with z-index layering. It&#39;s exactly like Flutter&#39;s Stack widget.</p><pre>@override<br>View view() {<br>  final canvas = Canvas(termWidth, termHeight);<br><br>  // Left panel — file list<br>  final leftPanel = const Style(<br>    border: Border.rounded,<br>    foregroundRgb: RgbColor(137, 180, 250),<br>  ).withWidth(30).withHeight(termHeight - 2).render(fileList);<br><br>  // Right panel — file preview<br>  final rightPanel = const Style(<br>    border: Border.rounded,<br>    foregroundRgb: RgbColor(166, 227, 161),<br>  ).withWidth(termWidth - 34).withHeight(termHeight - 2).render(preview);<br><br>  // Floating status overlay — higher z-index draws on top<br>  final statusBar = const Style(<br>    foregroundRgb: RgbColor(249, 226, 175),<br>    isBold: true,<br>  ).render(&#39; $selectedFile &#39;);<br><br>  canvas.paint(0, 0, leftPanel, zIndex: 1);<br>  canvas.paint(32, 0, rightPanel, zIndex: 1);<br>  canvas.paint(termWidth ~/ 2 - 10, termHeight - 1, statusBar, zIndex: 2);<br><br>  return newView(canvas.render());<br>}</pre><p>The result is a two-panel layout with a floating status bar — in about 20 lines of layout code. No manual string padding, no ANSI cursor gymnastics. Just paint and let the Canvas handle compositing.</p><h3>One More Thing: Performance</h3><p>dart_tui doesn’t just look good, it’s fast. The default renderer does line-level diffing — only changed lines emit ANSI sequences. Switch to withCellRenderer() for cell-level diffing that eliminates flicker even on slow terminals.</p><pre>await Program(<br>  options: const ProgramOptions(altScreen: true, hideCursor: true),<br>  programOptions: [withCellRenderer(), withFps(60)],<br>).run(MyModel());</pre><p>AOT compiled, your app starts in <strong>~100ms</strong>. Even as a JIT app it’s under 500ms on WSL2. Your users won’t wait.</p><h3>Conclusion</h3><p>Add it to your project:</p><pre>dependencies:<br>  dart_tui: ^1.0.0</pre><ul><li><strong>pub.dev:</strong> <a href="https://pub.dev/packages/dart_tui">pub.dev/packages/dart_tui</a></li><li><strong>GitHub:</strong> <a href="https://github.com/codenameakshay/dart_tui">github.com/codenameakshay/dart_tui</a></li><li><strong>48 examples included</strong> — run dart run example/showcase.dart to see everything at once</li></ul><p>The next time you build a Dart CLI tool, you don’t have to settle for plain text. Your terminal can be just as polished as your Flutter apps.</p><p>Go build something.</p><p><em>If this helped you, give dart_tui a ⭐ on GitHub. It means a lot and helps other Dart developers find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb5a1a80790" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-level-up-your-dart-terminal-apps-with-dart-tui-3eb5a1a80790">How to Level Up Your Dart Terminal Apps with dart_tui</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When I got tired of re-learning every provider’s streaming format]]></title>
            <link>https://codenameakshay.medium.com/when-i-got-tired-of-re-learning-every-providers-streaming-format-f458ee64601b?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/f458ee64601b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 12:04:55 GMT</pubDate>
            <atom:updated>2026-03-21T12:04:55.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lUcaur_nwt4gdD2A" /><figcaption>ai.sdk for dart/flutter?</figcaption></figure><h3>TL;DR</h3><p>If you already build AI features in Dart/Flutter and you’re <strong>copy-pasting slightly different HTTP + SSE handling</strong> for each vendor, a <strong>provider-agnostic layer</strong> can save real time. <strong>AI SDK Dart</strong> is a port of <strong>Vercel AI SDK v6</strong> ideas to Dart: same broad concepts (generateText, streamText, tools, structured output, middleware), so you can <strong>reuse mental models</strong> and official upstream examples as rough guides — then verify details in the Dart API and the repo’s <a href="https://github.com/codenameakshay/ai_sdk_dart/blob/main/docs/v6-parity-matrix.md">v6 parity matrix</a>.</p><p>This post is <strong>not</strong> “use this library.” It’s: <strong>here’s the problem it tries to solve, how to try it safely, and when to walk away.</strong></p><h3>The part nobody puts in the README: integration is boring and expensive</h3><p>Shipping a chat screen is easy. <strong>Keeping</strong> streaming, tool calls, retries, and “the model wrapped my JSON in a fence” <strong>consistent across OpenAI, Anthropic, and Google</strong> is where weeks disappear. You’re not blocked by “AI” — you’re blocked by <strong>glue</strong>: parsers, stream event shapes, and another place to leak API keys.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7btPCcdNniyf0ArS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcbc-comedy-what-3o7btPCcdNniyf0ArS&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaWlnbzZyNmZjNWRiaHpmMGRsaXB5ZXcwanR2Y2pyZzdvOXlwbjgxaSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7btPCcdNniyf0ArS%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/68762a22e3eaf43ec251580c0340f3a7/href">https://medium.com/media/68762a22e3eaf43ec251580c0340f3a7/href</a></iframe><p>If that paragraph felt familiar, you’re the audience. If not, you might be fine with a thin HTTP client forever — no shame.</p><h3>What this stack actually changes for you</h3><p>Not a feature list for marketing — a <strong>decision lens</strong>:</p><ol><li><strong>One call style for text</strong> — You call generateText / streamText with a LanguageModelV3. Swapping vendors is mostly <strong>changing how you construct the model</strong> (openai(...), anthropic(...), google(...)) and your secrets—not rewriting your whole feature.</li><li><strong>Structured output as a first-class idea</strong> — Output.object / Output.array / etc. exist so you’re not always regex-ing assistant strings. You’ll still handle edge cases—but the <strong>happy path</strong> isn’t bespoke.</li><li><strong>Tools + multi-step flows</strong> — Typed tool() plus ToolLoopAgent (and friends) mean you’re not hand-rolling the “model called a tool → run it → feed result back” loop every time.</li><li><strong>Flutter UI</strong> — ai_sdk_flutter_ui gives ChatController / CompletionController / ObjectStreamController so you’re not re-implementing “buffer streaming text into a Listenable” for every screen.</li><li><strong>MCP (optional)</strong> — If you use Model Context Protocol servers, the client can surface tools in the same shape as hand-defined tools — <strong>when</strong> MCP fits your architecture.</li></ol><p>None of that removes the need for <strong>good prompts, evals, and product judgment</strong>. It removes a class of <strong>mechanical</strong> bugs.</p><h3>How to evaluate it in an afternoon (without betting the company)</h3><ol><li><strong>Read the parity matrix</strong> — <a href="https://github.com/codenameakshay/ai_sdk_dart/blob/main/docs/v6-parity-matrix.md">docs/v6-parity-matrix.md</a> tells you what’s aligned with v6 and what’s partial. Use it to <strong>set expectations</strong> before you file “missing feature” issues.</li><li><strong>Run the examples with real keys</strong> — From the repo: make run-basic (CLI), make run / make run-web (flutter_chat), make run-advanced (broader surface). Fail fast on “does this feel like how I think?”</li><li><strong>Try one vertical</strong> — e.g. only streaming chat, or only structured JSON — <strong>don’t</strong> boil the ocean on day one.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12XMGIWtrHBl5e%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthe-office-no-steve-carell-12XMGIWtrHBl5e&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNXZ2OThqOXM4Z2N1Mjd6OTVoaGQ4N2poOHFkOGhpeDFwbmM4eTVkeiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F12XMGIWtrHBl5e%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="357" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93f265f56a13b1ba2ff3aa28c9b098c/href">https://medium.com/media/f93f265f56a13b1ba2ff3aa28c9b098c/href</a></iframe><h3>Code you can paste and tweak</h3><p><strong>Minimal call</strong></p><pre>import &#39;package:ai_sdk_dart/ai_sdk_dart.dart&#39;;<br>import &#39;package:ai_sdk_openai/ai_sdk_openai.dart&#39;;<br><br>void main() async {<br>  final result = await generateText(<br>    model: openai(&#39;gpt-4.1-mini&#39;),<br>    prompt: &#39;Say hello from AI SDK Dart!&#39;,<br>  );<br>  print(result.text);<br>}</pre><p><strong>Streaming</strong></p><pre>final result = await streamText(<br>  model: openai(&#39;gpt-4.1-mini&#39;),<br>  prompt: &#39;Count from 1 to 5.&#39;,<br>);<br>await for (final chunk in result.textStream) {<br>  stdout.write(chunk);<br>}</pre><p><strong>One tool (sanity check that the loop works)</strong></p><pre>final result = await generateText(<br>  model: openai(&#39;gpt-4.1-mini&#39;),<br>  prompt: &#39;What is the weather in Paris?&#39;,<br>  maxSteps: 5,<br>  tools: {<br>    &#39;getWeather&#39;: tool&lt;Map&lt;String, dynamic&gt;, String&gt;(<br>      description: &#39;Get current weather for a city.&#39;,<br>      inputSchema: Schema(<br>        jsonSchema: const {<br>          &#39;type&#39;: &#39;object&#39;,<br>          &#39;properties&#39;: {&#39;city&#39;: {&#39;type&#39;: &#39;string&#39;}},<br>        },<br>        fromJson: (json) =&gt; json,<br>      ),<br>      execute: (input, _) async =&gt; &#39;Sunny, 18°C&#39;,<br>    ),<br>  },<br>);<br>print(result.text);</pre><p>If these three work in <strong>your</strong> environment, you’ve learned more than any paragraph in this file.</p><h3>When to not reach for this</h3><ul><li>You only ever call <strong>one</strong> provider with <strong>one</strong> endpoint and you’ll never switch — <strong>a thin client might be simpler</strong>.</li><li>You need <strong>guarantees</strong> the README doesn’t claim yet (check roadmap in the repo root README.md—video, extra providers, richer MCP streaming, etc.).</li><li>You want <strong>minimal dependencies</strong> in a tiny package — this is a <strong>full toolkit</strong>, not a 200-line helper.</li></ul><h3>Closing</h3><p>If this saves you from rebuilding the same streaming parser for the fifth time, the win is <strong>less wasted focus</strong>, not loyalty to a package name. Run the examples, skim the parity doc, and decide. If something’s unclear, <strong>issues and discussions on the repo</strong> are the right place — good maintainers want actionable feedback.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0MYt5jPR6QX5pnqM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fparty-the-office-hard-l0MYt5jPR6QX5pnqM&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbzN1dzA4bmRhNG8xeGc1NGt5OXlldmhlZWxwYjJuc3ZlYWp3eWo1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fl0MYt5jPR6QX5pnqM%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cadcb5bc1e8fadcea061956bdb7c28a/href">https://medium.com/media/5cadcb5bc1e8fadcea061956bdb7c28a/href</a></iframe><h3>Link pack</h3><ul><li><strong>Repo:</strong> <a href="https://github.com/codenameakshay/ai_sdk_dart">https://github.com/codenameakshay/ai_sdk_dart</a></li><li><strong>Core package:</strong> <a href="https://pub.dev/packages/ai_sdk_dart">https://pub.dev/packages/ai_sdk_dart</a></li><li><strong>Vercel AI SDK (reference concepts):</strong> <a href="https://sdk.vercel.ai/">https://sdk.vercel.ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f458ee64601b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter in a Blur: Shader Your Way to High-Performance UI Magic!]]></title>
            <link>https://codenameakshay.medium.com/flutter-in-a-blur-shader-your-way-to-high-performance-ui-magic-703a5cafc0fb?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/703a5cafc0fb</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 07:36:30 GMT</pubDate>
            <atom:updated>2025-04-17T07:36:30.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjHb3dQ3LBF87s246XHCiA.png" /></figure><p>Ever wondered how Instagram creates those beautifully blurred backgrounds, or how apps effortlessly showcase sleek frosted-glass effects without lag? The answer lies in shaders! In this blog, we’ll reveal how to elevate your Flutter app’s visual elegance by leveraging the incredible power of GPU shaders for silky-smooth blur effects. Ready to go beyond Flutter’s basics? Let’s dive into the mesmerizing world of shaders!</p><h3>Wait, What Exactly are Shaders?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQ5nC7IadHHomNRRouctMQ.png" /></figure><p>Shaders are tiny but mighty programs that run on your GPU (Graphics Processing Unit), enabling eye-popping visual effects by handling millions of pixels simultaneously. Imagine your GPU as an army of pixels, with shaders directing every pixel simultaneously. Cool, right?</p><p>Shaders come in two flavors:</p><ul><li><strong>Vertex Shaders:</strong> Move and position points (vertices) in 3D space.</li><li><strong>Fragment Shaders:</strong> Control pixel-by-pixel colors and effects, perfect for smooth blurs.</li></ul><p>For crafting blur effects, we’ll harness the magic of <strong>fragment shaders</strong>.</p><h3>Why Shader-Powered Blur is a Game-Changer?</h3><p>Let’s be clear: Flutter’s built-in blur (ImageFilter.blur) does the job—but custom shaders take your visuals to another level:</p><ol><li>🚀 <strong>Supercharged Performance</strong>: GPU shaders process visuals lightning-fast, preventing lag even on heavy blurs.</li><li>🎨 <strong>Visual Excellence</strong>: Create richer, smoother blur effects with custom algorithms.</li><li>🔧 <strong>Pixel-Perfect Control</strong>: Precisely adjust how every pixel renders.</li><li>🔋 <strong>Battery-Friendly</strong>: GPU blurring uses less battery compared to CPU-driven alternatives.</li></ol><p>Shader-driven blur means your UI stays smooth and stunning, without sacrificing performance.</p><h3>How to Get Shady in Flutter: Shader Setup</h3><p>Here’s how to quickly get shader-based blur running in your Flutter app:</p><h4>Step 1: Add Shader Package</h4><p>First, include the flutter_shaders package in your pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_shaders: ^latest_version</pre><h4>Step 2: Create Your Shader Files</h4><p>Make a shaders/ directory and add your custom shaders:</p><pre>shaders:<br>  - shaders/blur.frag<br>  - shaders/blur_android.frag</pre><h4>Step 3: Register Shaders</h4><p>Tell Flutter where your shader files are:</p><pre>flutter:<br>  shaders:<br>    - shaders/blur.frag<br>    - shaders/blur_android.frag</pre><h4>Step 4: Load Shaders in Widgets</h4><p>Use the shaders easily in your widgets with Flutter’s shader tools (details below).</p><h3>Flutter’s Default Blur (and Its Limits!)</h3><p>The built-in blur uses ImageFilter.blur and looks something like this:</p><pre>class ImageFilterBlur extends StatelessWidget {<br>  final Widget child;<br>  final double blurRadius;<br><br>const ImageFilterBlur({required this.child, this.blurRadius = 10.0});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ClipRect(<br>      child: BackdropFilter(<br>        filter: ImageFilter.blur(sigmaX: blurRadius, sigmaY: blurRadius),<br>        child: child,<br>      ),<br>    );<br>  }<br>}</pre><p>This is easy but can slow down performance, especially with large blurs and complex UIs.</p><h3>Blazing-Fast Blur: Shader Implementation</h3><p>Take it up a notch with shaders:</p><h4>Shader Widget</h4><pre>class ShaderBlur extends StatelessWidget {<br>  final Widget child;<br>  final double blurRadius;<br><br>const ShaderBlur({required this.child, this.blurRadius = 10.0});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ClipRect(<br>      child: ShaderBuilder(<br>        assetKey: &#39;shaders/blur.frag&#39;,<br>        uniforms: [blurRadius],<br>        child: child,<br>      ),<br>    );<br>  }<br>}</pre><h3>Fragment Shader Magic (blur.frag)</h3><pre>#version 460 core<br>#include &lt;flutter/runtime_effect.glsl&gt;<br>uniform vec2 uResolution;<br>uniform float uBlurRadius;<br>uniform sampler2D uTexture;<br>out vec4 fragColor;<br>float gaussian(float x, float sigma) {<br>  return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * 3.14159) * sigma);<br>}<br>void main() {<br>  vec2 texCoord = FlutterFragCoord().xy / uResolution;<br>  vec4 blurredColor = vec4(0.0);<br>  float sigma = max(1.0, uBlurRadius / 2.0);<br>  int radius = int(sigma * 2.0);<br>  float weightSum = 0.0;<br>  for(int x = -radius; x &lt;= radius; x++){<br>    for(int y = -radius; y &lt;= radius; y++){<br>      float weight = gaussian(length(vec2(x, y)), sigma);<br>      blurredColor += texture(uTexture, texCoord + vec2(x, y)/uResolution) * weight;<br>      weightSum += weight;<br>    }<br>  }<br>  fragColor = blurredColor / weightSum;<br>}</pre><p>This shader creates buttery-smooth Gaussian blurs with minimal performance impact.</p><p>Full code example (with better shaders) available on my <a href="https://github.com/codenameakshay/shader-blur">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*S6VJbJzJBFIjuMhdhC0VkA.gif" /></figure><h3>Shader Blur vs. ImageFilter Blur: The Ultimate Showdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QolGDocBXF0gSykma_vPw.png" /></figure><p><strong>Use Shader Blur When:</strong></p><ul><li>You need ultra-performance</li><li>Medium-large blur radius</li><li>Custom visuals are crucial</li></ul><p><strong>Use Default Blur When:</strong></p><ul><li>Quick and small blur tasks</li><li>Easy, cross-platform consistency</li></ul><h3>Wrapping Up the Magic!</h3><p>Harnessing GPU shaders transforms your Flutter apps, creating mesmerizing visuals without performance hiccups. Whether crafting sophisticated UI designs or ensuring buttery-smooth performance, mastering shader blur is your ticket to next-level app aesthetics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXI5N8VknBuiSFAwPZKT9g.png" /></figure><p><strong>Ready to blur the lines between good and great UI?</strong> Grab the shader magic today, and elevate your Flutter creations instantly!</p><p>P.S. — This is just a starting point for shaders in Flutter, and I wanted to keep it basic and simple to give beginners a headstart, so have not included the much realistic usecases of shaders (like 3d graphics, and obviously much better animations).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703a5cafc0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Get Real (Time)! Handling WebSockets in Flutter Like a Pro]]></title>
            <link>https://codenameakshay.medium.com/lets-get-real-time-handling-websockets-in-flutter-like-a-pro-d1cdc3267a20?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1cdc3267a20</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 08:26:45 GMT</pubDate>
            <atom:updated>2025-04-10T08:26:45.374Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, so if you’re making a Flutter app, and want to handle instantaneous updates, real-time interactions, and seamless connectivity, WebSockets are something you might consider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnRtQkrJfKId4BMB1hDnmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*AA2Y-i_VU--gGf8O.png" /></figure><p>WebSockets — a powerful communication protocol that keeps data flowing between client and server without the constant back-and-forth of traditional HTTP requests. Whether you’re building a chat app, a live stock ticker, or even a multiplayer game, WebSockets can take your app’s real-time capabilities to the next level.</p><p>In this blog, we’ll explore how to harness the power of WebSockets in Flutter. We’ll start by establishing a connection, then dive into sending and receiving messages, handling errors, and even ensuring robust reconnections. By the end, you’ll have all the tools to make your Flutter app a real-time powerhouse!</p><p>But first let’s understand what are Websockets, and why Websockets?</p><h3>Websockets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*lRVliueQpbTfDkGHvPUtJg.png" /></figure><p>WebSockets are a communication protocol that enables interactive, two-way communication between a client (like a Flutter app) and a server over a single, long-lived connection. Unlike traditional HTTP requests, which follow a request-response pattern, WebSockets keep the connection open, allowing data to be sent and received instantly as events occur. This makes them a perfect fit for applications that require real-time updates, such as chat apps, live sports scores, collaborative editing tools, or financial market data.</p><h4>Why Websockets?</h4><p>The benefits of using WebSockets in your Flutter apps go beyond just faster updates. Here are a few key reasons why you should consider WebSockets:</p><ol><li><strong>Real-Time Data Updates</strong>: With WebSockets, you can push updates to your app as soon as data changes on the server, creating a responsive and engaging user experience.</li><li><strong>Lower Latency</strong>: Unlike polling or periodic refresh techniques that introduce delays, WebSockets transmit messages almost instantly, reducing latency and enhancing performance.</li><li><strong>Reduced Overhead</strong>: WebSockets maintain a single open connection, avoiding the repeated handshake overhead of HTTP requests. This can lead to more efficient use of network resources.</li><li><strong>Bi-Directional Communication</strong>: WebSockets allow both the client and server to send messages independently. This is especially useful for interactive applications where responses are needed on-demand from either end.</li><li><strong>Event-Driven Model</strong>: WebSocket communication leverages an event-driven model, meaning you can easily react to incoming data, errors, and other events in your Flutter app’s business logic.</li></ol><p>In the next section, let us understand what to choose between websockets and gRPC.</p><h3>WebSockets vs. gRPC: A Comparison</h3><p>When building real-time communication in your Flutter apps, you might wonder if WebSockets is the best option or if you should consider other protocols like gRPC. While both WebSockets and gRPC enable robust communication between clients and servers, they have distinct differences and strengths. Let’s break down how they compare:</p><h4><strong>What is gRPC?</strong></h4><p>gRPC (Google Remote Procedure Call) is an open-source RPC (Remote Procedure Call) framework that uses HTTP/2 for transport, Protocol Buffers for efficient serialization, and allows for bi-directional streaming communication. Unlike traditional REST APIs, gRPC is built for fast, structured, and lightweight communication, making it ideal for microservices and efficient data transfer.</p><h4><strong>Comparing WebSockets and gRPC</strong></h4><p>1. <strong>Communication Model</strong>:</p><ul><li><strong>WebSockets</strong>: WebSockets maintain a persistent, full-duplex connection between the client and server. This means both sides can send data independently without a request-response structure. WebSockets are event-driven, making them great for scenarios like real-time notifications, chat, and gaming.</li><li><strong>gRPC</strong>: gRPC also supports bi-directional streaming, but it revolves around service definitions and method calls (similar to calling functions on a remote server). gRPC is great for structured communication, such as microservices and API interactions that require strict data contracts.</li></ul><p>2. <strong>Performance</strong>:</p><ul><li><strong>WebSockets</strong>: Offer low latency communication with minimal overhead once the connection is established. Ideal for high-frequency data updates and event-driven systems.</li><li><strong>gRPC</strong>: Optimized for high performance using HTTP/2, with features like multiplexing and efficient serialization through Protocol Buffers. gRPC can be more efficient for structured API calls or when data needs to be serialized and validated quickly.</li></ul><p>3. <strong>Ease of Use</strong>:</p><ul><li><strong>WebSockets</strong>: Simple to set up and use, especially for scenarios that require continuous data streaming. It’s well-supported in Flutter, making it a good fit for projects that prioritize real-time interactions without complex service definitions.</li><li><strong>gRPC</strong>: Comes with more complexity due to service definitions and the need to generate code using Protocol Buffers. However, it offers strong type safety and consistent APIs across languages.</li></ul><p>4. <strong>Use Cases</strong>:</p><ul><li><strong>WebSockets</strong>: Ideal for real-time apps such as chat applications, live dashboards, collaborative editing tools, or games where low latency updates are critical.</li><li><strong>gRPC</strong>: Better suited for microservices architectures, API interactions, or scenarios requiring strict contract validation, streaming RPCs, and service-to-service communication.</li></ul><p>5. <strong>Protocol Compatibility</strong>:</p><ul><li><strong>WebSockets</strong>: Typically works over TCP, and while it can operate securely over WSS (WebSocket Secure), it doesn’t use HTTP/2 features like gRPC does.</li><li><strong>gRPC</strong>: Utilizes HTTP/2, which allows for features like multiplexing (sending multiple requests for data in parallel over the same connection), making it more efficient in certain scenarios.</li></ul><h4><strong>Which to Choose?</strong></h4><p>The choice between WebSockets and gRPC depends on your specific application needs. If your Flutter app needs continuous, event-driven updates (like chat messages or live game scores), WebSockets are an excellent choice for simplicity and speed. On the other hand, if you’re building a microservices-based backend with strict data structures or need efficient RPC communication, gRPC can offer a more structured approach with performance benefits.</p><p>By using WebSockets, you can transform your app’s user experience with blazing-fast communication, making your applications feel more like a conversation than a series of disconnected calls. In the next section, we’ll explore how to set up and use WebSockets in Flutter.</p><h3><strong>Setting Up a WebSocket Connection in Flutter</strong></h3><p>Now that we understand what WebSockets are and why they are valuable, let’s dive into how to set up a WebSocket connection in a Flutter app.</p><p>Flutter provides robust support for WebSockets through packages like <a href="https://pub.dev/packages/web_socket_channel"><em>web_socket_channel</em></a>, making it easy to establish a connection and start sending and receiving data in real time.</p><h4><strong>Step 1: Adding the web_socket_channel Package</strong></h4><p>First, add the web_socket_channel package to your <em>pubspec.yaml</em> file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  web_socket_channel: ^2.4.0</pre><p>Run flutter pub get to fetch the package.</p><h4><strong>Step 2: Establishing a WebSocket Connection</strong></h4><p>To set up a WebSocket connection, you’ll use the WebSocketChannel class from the <em>web_socket_channel</em> package. Here’s how to create a basic WebSocket connection:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:web_socket_channel/web_socket_channel.dart&#39;;<br><br>void main() =&gt; runApp(MyApp());<br><br>class MyApp extends StatelessWidget {<br>  final WebSocketChannel channel = WebSocketChannel.connect(<br>    Uri.parse(&#39;wss://echo.websocket.org&#39;),<br>  );<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(title: Text(&#39;Flutter WebSocket Example&#39;)),<br>        body: WebSocketPage(channel: channel),<br>      ),<br>    );<br>  }<br>}<br><br>class WebSocketPage extends StatefulWidget {<br>  final WebSocketChannel channel;<br><br>  WebSocketPage({required this.channel});<br><br>  @override<br>  _WebSocketPageState createState() =&gt; _WebSocketPageState();<br>}<br><br>class _WebSocketPageState extends State&lt;WebSocketPage&gt; {<br>  TextEditingController _controller = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.all(8.0),<br>      child: Column(<br>        children: &lt;Widget&gt;[<br>          TextField(<br>            controller: _controller,<br>            decoration: InputDecoration(labelText: &#39;Send a message&#39;),<br>          ),<br>          ElevatedButton(<br>            onPressed: _sendMessage,<br>            child: Text(&#39;Send&#39;),<br>          ),<br>          StreamBuilder(<br>            stream: widget.channel.stream,<br>            builder: (context, snapshot) {<br>              return Padding(<br>                padding: const EdgeInsets.symmetric(vertical: 24.0),<br>                child: Text(snapshot.hasData ? &#39;Received: ${snapshot.data}&#39; : &#39;&#39;),<br>              );<br>            },<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  void _sendMessage() {<br>    if (_controller.text.isNotEmpty) {<br>      widget.channel.sink.add(_controller.text);<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    widget.channel.sink.close();<br>    super.dispose();<br>  }<br>}</pre><p><strong>Code Explanation -</strong></p><p>1. <strong>WebSocket Channel</strong>: We create a WebSocketChannel by connecting to a WebSocket server. In this example, we use a public echo server (<em>wss://echo.websocket.org</em>), which echoes back any messages sent to it.</p><p>2. <strong>Sending Data</strong>: Use the sink.add() method to send data over the WebSocket connection.</p><p>3. <strong>Receiving Data</strong>: The stream property of the WebSocketChannel allows us to listen for incoming messages. We use a StreamBuilder widget to display received messages in real-time.</p><p>4. <strong>Closing the Connection</strong>: Always remember to close the WebSocket connection using channel.sink.close() to avoid potential memory leaks.</p><p>This basic setup gives you a two-way communication channel using WebSockets in Flutter. In the next sections, we’ll cover error handling, reconnection strategies, and more advanced features.</p><h3>Handling errors and reconnection strategy</h3><p>While WebSockets provide a powerful way to enable real-time communication, they are not immune to network issues, unexpected server errors, or connectivity drops.</p><p>Proper error handling ensures that your app can gracefully recover from such scenarios and continue providing a good user experience. Here are some strategies and best practices for handling errors when working with WebSockets.</p><h4><strong>1. Handling Connection Errors</strong></h4><p>When establishing a WebSocket connection, it’s important to catch any exceptions that may occur due to issues such as server unavailability or incorrect URLs.</p><pre>try {<br>  final channel = WebSocketChannel.connect(<br>    Uri.parse(&#39;wss://example.com/socket&#39;),<br>  );<br>} catch (e) {<br>  // Handle connection error<br>  print(&#39;Failed to connect: $e&#39;);<br>}</pre><h4><strong>2. Listening for Errors</strong></h4><p>The <em>web_socket_channel</em> package allows you to listen for errors through the stream property. You can handle these errors using the StreamBuilder widget or by manually listening to the stream.</p><pre>StreamBuilder(<br>  stream: widget.channel.stream,<br>  builder: (context, snapshot) {<br>    if (snapshot.hasError) {<br>      return Text(&#39;Error: ${snapshot.error}&#39;);<br>    }<br>    return Text(snapshot.hasData ? &#39;Received: ${snapshot.data}&#39; : &#39;&#39;);<br>  },<br>);</pre><p>In this example, if an error occurs during the communication, it will be displayed in the UI. You can also log it or trigger custom error-handling logic.</p><h4><strong>3. Managing Disconnections and Reconnecting</strong></h4><p>Network issues can cause WebSocket connections to drop. To provide a robust experience, it’s crucial to detect disconnections and attempt reconnections.</p><ul><li><strong>Detecting Disconnections</strong>: You can listen for connection closure events and attempt to reconnect when needed.</li></ul><pre>widget.channel.stream.listen(<br>  (message) {<br>    // Handle incoming messages<br>  },<br>  onError: (error) {<br>    print(&#39;WebSocket error: $error&#39;);<br>    _attemptReconnection();<br>  },<br>  onDone: () {<br>    print(&#39;WebSocket closed.&#39;);<br>    _attemptReconnection();<br>  },<br>);</pre><ul><li><strong>Reconnection Strategy</strong>: When attempting to reconnect, consider using a backoff strategy to avoid overwhelming the server with frequent reconnection attempts. A simple <em>exponential backoff</em> could be implemented using Future.delayed() .</li></ul><pre>int _reconnectAttempts = 0;<br><br>void _attemptReconnection() {<br>  if (_reconnectAttempts &lt; 5) {<br>    _reconnectAttempts++;<br>    Future.delayed(Duration(seconds: _reconnectAttempts * 2), () {<br>      // Reconnect logic here<br>      print(&#39;Attempting to reconnect...&#39;);<br>      _connectToWebSocket();<br>    });<br>  } else {<br>    print(&#39;Max reconnection attempts reached. Giving up.&#39;);<br>  }<br>}</pre><h4><strong>4. Handling Data Validation and Parsing Errors</strong></h4><p>When receiving data over a WebSocket connection, ensure that the data format is as expected. Invalid data could lead to parsing errors or app crashes. Use try-catch blocks or validation checks to handle these issues gracefully.</p><pre>widget.channel.stream.listen(<br>  (message) {<br>    try {<br>      // Assuming the message is JSON<br>      final parsedData = jsonDecode(message);<br>      // Handle parsed data<br>    } catch (e) {<br>      print(&#39;Error parsing message: $e&#39;);<br>    }<br>  },<br>);</pre><h4><strong>5. Closing the WebSocket Gracefully</strong></h4><p>When the user navigates away from the WebSocket-connected page or when the app goes to the background, it’s important to close the WebSocket connection properly.</p><pre>@override<br>void dispose() {<br>  widget.channel.sink.close();<br>  super.dispose();<br>}</pre><p>By closing the connection, you free up resources and avoid potential memory leaks.</p><p>With these error-handling strategies, your Flutter app can provide a stable and responsive experience when using WebSockets, even in the face of network issues or unexpected errors. In the next section, we’ll explore why closing Websocket is important.</p><h3><strong>Why Closing WebSockets is Important?</strong></h3><p>When building real-time applications with WebSockets, it’s essential to remember that what goes up must eventually come down. In this case, while keeping a WebSocket connection open is key to maintaining real-time data streams, closing it properly is critical for a variety of reasons. This section will cover why closing WebSockets matters and how to do it effectively.</p><h4><strong>Why Properly Closing WebSocket Connections is Important?</strong></h4><ol><li><strong>Resource Management</strong>:</li></ol><ul><li><strong>Memory and CPU Usage</strong>: Keeping WebSocket connections open unnecessarily can lead to memory leaks and excessive CPU usage. Every open connection consumes resources, and on mobile devices, this can negatively impact app performance and battery life.</li><li><strong>Network Bandwidth</strong>: An open WebSocket connection consumes network bandwidth, even if no data is being transmitted, due to keep-alive mechanisms like ping/pong frames. Properly closing connections when they’re no longer needed helps conserve data usage and network resources.</li></ul><p>2. <strong>Avoiding Unexpected Behavior</strong>:</p><ul><li><strong>Stale Connections</strong>: Failing to close WebSocket connections can leave “zombie” connections that continue to exist without any useful purpose. This can lead to unexpected behavior, such as receiving messages intended for another session.</li><li><strong>Server Overhead</strong>: Leaving unused WebSocket connections open can place unnecessary strain on the server, affecting overall server performance and potentially leading to degraded service for other users.</li></ul><p>3. <strong>Compliance and Security</strong>:</p><ul><li><strong>Connection Lifecycle Management</strong>: In some scenarios, proper connection termination is necessary for compliance with protocols and security policies, ensuring that sensitive data isn’t exposed inadvertently or that unauthorized sessions are properly terminated.</li><li><strong>Graceful Termination</strong>: Closing WebSocket connections gracefully ensures that both the client and server know the connection has been ended, preventing data loss or miscommunication.</li></ul><h4><strong>Best Practices for Closing WebSocket Connections</strong></h4><p>1. <strong>Close the Connection When Leaving a Screen</strong>:</p><ul><li>If your WebSocket connection is tied to a particular screen or page in your Flutter app, close the connection when navigating away from that page. This can be achieved using the dispose() method in Flutter’s widget lifecycle.</li></ul><pre>@override<br>void dispose() {<br>  widget.channel.sink.close();<br>  super.dispose();<br>}</pre><ul><li>This ensures that the connection is properly terminated when the user navigates away, freeing up resources.</li></ul><p>2. <strong>Handle App Lifecycle Changes</strong>:</p><ul><li>Use Flutter’s WidgetsBindingObserver to listen for app lifecycle changes, such as when the app goes to the background. You can close or suspend the WebSocket connection when the app is inactive and reconnect when it becomes active again.</li></ul><pre>class WebSocketPage extends StatefulWidget {<br>  // ...<br>}<br><br>class _WebSocketPageState extends State&lt;WebSocketPage&gt; with WidgetsBindingObserver {<br>  @override<br>  void initState() {<br>    super.initState();<br>    WidgetsBinding.instance.addObserver(this);<br>  }<br><br>  @override<br>  void dispose() {<br>    WidgetsBinding.instance.removeObserver(this);<br>    widget.channel.sink.close();<br>    super.dispose();<br>  }<br><br>  @override<br>  void didChangeAppLifecycleState(AppLifecycleState state) {<br>    if (state == AppLifecycleState.paused) {<br>      widget.channel.sink.close(); // Close when app goes to background<br>    } else if (state == AppLifecycleState.resumed) {<br>      // Optionally, reconnect when the app becomes active again<br>    }<br>  }<br>}</pre><p>3. <strong>Use Proper WebSocket Closure Codes</strong>:</p><ul><li>The WebSocket protocol provides a set of standard status codes for closing connections (e.g., 1000 for normal closure). When closing a WebSocket connection, it’s good practice to provide an appropriate status code and a reason.</li></ul><pre>widget.channel.sink.close(1000, &#39;Normal closure&#39;);</pre><p>4. <strong>Graceful Shutdown</strong>:</p><ul><li>Before closing the WebSocket, ensure that any ongoing communication (e.g., pending messages) is completed or canceled. This prevents data loss or incomplete communication.</li></ul><p>5. <strong>Reconnecting Strategies</strong>:</p><ul><li>When closing a connection due to a temporary error (like network issues), implement a strategy for reconnecting after a delay or when network conditions improve. This ensures that your app can resume normal operation seamlessly.</li></ul><h4><strong>Conclusion — When to Close a WebSocket Connection</strong></h4><ul><li><strong>When navigating away from a screen</strong> that uses a WebSocket connection.</li><li><strong>When the app goes to the background</strong> (optional depending on your use case).</li><li><strong>When shutting down the app</strong>.</li><li><strong>After detecting an error</strong> that requires a new connection.</li></ul><h3><strong>Advanced WebSockets: Authentication and Ping/Pong Frames</strong></h3><p>Once you have a basic WebSocket connection up and running, it’s time to explore more advanced features that can improve the security and stability of your WebSocket interactions. In this section, we’ll cover how to handle authentication for WebSocket connections and leverage ping/pong frames to maintain connection health.</p><h4><strong>1. WebSocket Authentication</strong></h4><p>Unlike traditional HTTP requests, WebSocket connections don’t inherently have built-in headers like cookies or authorization headers. This can make authentication for WebSocket connections a bit different from standard REST APIs. Here are some common approaches to authenticating WebSocket connections:</p><p><strong>Token-Based Authentication (e.g., JWT):</strong></p><ul><li>One of the most common ways to authenticate WebSocket connections is by sending a token (such as a JWT) as a query parameter when establishing the connection.</li></ul><pre>final WebSocketChannel channel = WebSocketChannel.connect(<br>  Uri.parse(&#39;wss://example.com/socket?token=your_jwt_token&#39;),<br>);</pre><ul><li>On the server side, the token can be verified during the WebSocket handshake, ensuring only authorized clients are allowed to connect.</li></ul><p><strong>Initial Message Authentication</strong>:</p><ul><li>Another approach is to establish the WebSocket connection first and then send an authentication message as soon as the connection is opened. The server can respond with an acknowledgment or close the connection if authentication fails.</li></ul><pre>widget.channel.sink.add(jsonEncode({&#39;type&#39;: &#39;auth&#39;, &#39;token&#39;: &#39;your_jwt_token&#39;}));</pre><ul><li>This method gives you more control over handling authenticated and unauthenticated states.</li></ul><p><strong>Header-Based Authentication (If Supported)</strong>:</p><ul><li>While the WebSocket handshake occurs over an HTTP/1.1 request, some WebSocket client libraries support sending custom headers during the handshake. Note that not all servers may support or process headers in the WebSocket handshake.</li></ul><h4><strong>2. Using Ping/Pong Frames to Maintain Connection Health</strong></h4><p>WebSocket connections are designed to stay open, but network issues, idle connections, or server timeouts can cause the connection to drop unexpectedly. To keep the connection alive and detect if it has been closed, WebSockets support a built-in mechanism called ping/pong frames.</p><p><strong>What are Ping/Pong Frames?</strong></p><ul><li>Ping and pong frames are special control frames sent between the client and server to ensure the connection is still open and responsive. A “ping” is sent from one end (client or server), and a “pong” is expected in response.</li><li>If a “pong” response is not received within a certain timeout period, it indicates that the connection may be dead, and the client can take appropriate action (e.g., reconnect).</li></ul><p><strong>Implementing Ping/Pong Frames in Flutter</strong>:</p><ul><li>While some WebSocket server implementations handle ping/pong frames automatically, you may need to manage them yourself in certain cases.</li><li>The <em>web_socket_channel</em> package in Flutter doesn’t explicitly expose ping/pong frames directly, but you can implement your own “heartbeat” mechanism to keep the connection alive. This involves periodically sending a message (like a “ping” message) and waiting for a response.</li></ul><p>Example implementation of a basic heartbeat mechanism:</p><pre>Timer? _heartbeatTimer;<br><br>void _startHeartbeat() {<br>  _heartbeatTimer?.cancel(); // Cancel any existing timer<br>  _heartbeatTimer = Timer.periodic(Duration(seconds: 30), (timer) {<br>    widget.channel.sink.add(jsonEncode({&#39;type&#39;: &#39;ping&#39;}));<br>  });<br>}<br><br>@override<br>void dispose() {<br>  _heartbeatTimer?.cancel();<br>  widget.channel.sink.close();<br>  super.dispose();<br>}</pre><p><strong>Handling Missed Pings</strong>:</p><ul><li>If the client does not receive a response (pong) within a specific timeframe, you can attempt to reconnect or alert the user that the connection was lost.</li></ul><p><strong>Benefits of Using Ping/Pong Frames</strong></p><ul><li><strong>Detecting Dead Connections</strong>: Keeps your WebSocket connection responsive by detecting dead connections and taking appropriate actions (e.g., reconnecting).</li><li><strong>Idle Connection Management</strong>: Ensures that idle connections are still active, preventing disconnections caused by server or network timeouts.</li><li><strong>Better Resource Management</strong>: Helps manage resources effectively by identifying and closing connections that are no longer active.</li></ul><h4>Conclusion — Advanced WebSocket Features</h4><p>Advanced WebSocket features like authentication and ping/pong frames are crucial for building secure, robust, and resilient real-time applications. By implementing proper authentication, you can ensure only authorized users gain access, while ping/pong frames help maintain connection health and responsiveness. Together, these techniques enhance both the security and reliability of your WebSocket interactions in Flutter apps.</p><p>While WebSockets offer a powerful means of real-time communication, they can also expose your app to potential security risks if not properly managed. Data transmitted over WebSockets can include sensitive information, making it crucial to prioritize security measures like encryption, authentication, and data validation.</p><p>In the next section, we’ll dive into best practices and strategies for securing your WebSocket connections, ensuring that your app’s real-time interactions remain safe, reliable, and resistant to threats.</p><h3><strong>Securing Your WebSocket Connections</strong></h3><p>WebSockets provide a fast, efficient way to maintain real-time communication between clients and servers. However, like any communication protocol, WebSockets can introduce security vulnerabilities if not properly secured. Protecting the integrity, confidentiality, and authenticity of your WebSocket connections is essential, especially if sensitive data is transmitted. Here’s how you can secure your WebSocket connections in Flutter.</p><h4><strong>1. Use Secure WebSocket Connections (WSS)</strong></h4><ul><li><strong>Always Use WSS (WebSocket Secure)</strong>: When establishing a WebSocket connection, use the secure protocol wss:// instead of the non-encrypted ws://. This ensures that data transmitted over the WebSocket is encrypted using TLS (similar to HTTPS).</li></ul><h4><strong>Benefits of WSS</strong>:</h4><ul><li><strong>Encryption</strong>: Data sent over a wss:// connection is encrypted, protecting it from being intercepted or tampered with during transmission.</li><li><strong>Data Integrity</strong>: TLS ensures that messages cannot be altered or corrupted without detection.</li><li><strong>Confidentiality</strong>: Only authorized parties can read the data being transmitted.</li></ul><h4><strong>2. Authenticate and Authorize Connections</strong></h4><ul><li><strong>Token-Based Authentication</strong>: As discussed earlier, using tokens (e.g., JWT) for authenticating WebSocket connections is a common practice. Ensure that tokens are securely stored (e.g., using Flutter’s secure storage packages) and transmitted.</li><li><strong>Role-Based Authorization</strong>: Once a connection is authenticated, you can implement role-based access control on the server side to restrict what actions each user can perform. This minimizes the impact of compromised accounts or malicious activity.</li></ul><h4><strong>3. Data Validation and Sanitization</strong></h4><ul><li><strong>Validate All Incoming Messages</strong>: Always validate and sanitize data received over WebSockets to prevent malicious inputs (e.g., SQL injection, code injection).</li></ul><pre>widget.channel.stream.listen((message) {<br>  try {<br>    final data = jsonDecode(message);<br>    // Validate data structure and values<br>  } catch (e) {<br>    print(&#39;Invalid data received: $e&#39;);<br>  }<br>});</pre><ul><li><strong>Sanitize Output Data</strong>: If you’re sending data to other clients, make sure to sanitize it to prevent issues like cross-site scripting (XSS) attacks.</li></ul><h4><strong>4. Implement Connection Limits and Rate Limiting</strong></h4><ul><li><strong>Rate Limiting</strong>: Limit the number of messages a client can send over a period of time to prevent abuse (e.g., spamming or DDoS attacks). This can be enforced on the server side.</li><li><strong>Connection Limits</strong>: Restrict the number of WebSocket connections per user or IP address to reduce the risk of resource exhaustion attacks.</li></ul><h4><strong>5. Handle Reconnection Strategies Securely</strong></h4><ul><li><strong>Throttle Reconnection Attempts</strong>: If a WebSocket connection is lost, it’s common to attempt a reconnection. However, be mindful not to overwhelm your server with repeated connection attempts. Implement exponential backoff strategies to slow down reconnections gradually.</li><li><strong>Revalidate on Reconnection</strong>: When reconnecting, ensure that the authentication token or session is still valid to prevent unauthorized access after reconnection.</li></ul><h4><strong>6. Prevent Cross-Site WebSocket Hijacking</strong></h4><ul><li><strong>Use Same-Origin Policy and CSRF Tokens</strong>: WebSockets do not natively enforce the same-origin policy like traditional HTTP requests. To mitigate risks of cross-site WebSocket hijacking (where malicious scripts connect to your WebSocket server using a victim’s session), use CSRF tokens for requests or enforce origin checks on the server.</li></ul><h4><strong>7. Keep Sensitive Data Encrypted</strong></h4><ul><li><strong>End-to-End Encryption</strong>: In some cases, you may want to implement end-to-end encryption, ensuring that data remains encrypted from client to client, even if it passes through intermediate servers.</li><li><strong>Secure Storage</strong>: Store sensitive data such as tokens and credentials securely in the Flutter app, avoiding plain-text storage.</li></ul><h4><strong>8. Regularly Update and Patch Dependencies</strong></h4><ul><li><strong>Keep Libraries Up-to-Date</strong>: Ensure that you’re using the latest versions of the <em>web_socket_channel</em> package and any related dependencies. Security vulnerabilities can be found and patched over time.</li><li><strong>Audit Code Regularly</strong>: Perform regular security audits of your WebSocket implementation and server-side logic to identify and fix potential vulnerabilities.</li></ul><h4><strong>9. Handle Errors Gracefully</strong></h4><ul><li><strong>Graceful Degradation</strong>: Ensure that your WebSocket connection fails gracefully without exposing sensitive data or creating unexpected behavior.</li><li><strong>Detailed Logging</strong>: Log errors related to WebSocket connections and security events to track suspicious activities and potential threats.</li></ul><h4>Conclusion — Security</h4><p>Securing WebSocket connections involves more than just establishing a connection — it requires careful planning, authentication, data validation, and robust error handling. By adopting these security measures, you can protect your WebSocket-based Flutter apps from common threats and ensure safe and reliable real-time communication.</p><h3>How I implemented WebSockets in my Finance app?</h3><p>In my finance app, delivering real-time updates such as market data, stock prices, and user portfolio changes is essential to keeping users informed and engaged. To achieve this, I rely on WebSockets for instant, bidirectional communication between the server and client.</p><p>In this section, I’ll walk you through the basic code architecture I used to integrate WebSockets and how I manage multiple WebSocket connections within the app.</p><h4><strong>Integrating Dependencies</strong></h4><p>To get started with WebSockets in our finance app, we’ll integrate the web_socket_channel package for WebSocket communication, flutter_bloc for state management, and freezed to create immutable and powerful data models. Add the following dependencies to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  web_socket_channel: ^2.3.0   # For WebSocket communication<br>  flutter_bloc: ^8.0.0        # For state management using the Bloc pattern<br>  freezed_annotation: ^2.1.0  # For generating immutable data classes<br><br>dev_dependencies:<br>  build_runner: ^2.1.0        # For code generation with Freezed<br>  freezed: ^2.1.0             # Freezed code generation package</pre><p>After adding these dependencies, run flutter pub get to fetch the packages.</p><p>With these packages in place, you’ll have the tools needed for establishing WebSocket connections, managing app state effectively, and creating immutable data models. Next, we’ll dive into setting up the basic code architecture for handling WebSocket communication.</p><h4><strong>Creating the WebSocket Repository</strong></h4><p>To manage multiple WebSocket connections efficiently, we’ll create a WebsocketRepository class. This class will handle connecting to WebSocket endpoints, sending and receiving messages, and managing multiple WebSocket connections in a clean and scalable way.</p><p>Create a new file named websocket_repository.dart and add the following code:</p><pre>import &#39;dart:async&#39;;<br>import &#39;package:web_socket_channel/web_socket_channel.dart&#39;;<br><br>class WebsocketRepository {<br>  final Map&lt;String, WebSocketChannel&gt; _channels = {};<br>  final Map&lt;String, StreamController&lt;String&gt;&gt; _controllers = {};<br><br>  /// Connect to a WebSocket endpoint with a unique ID.<br>  void connect(String id, String endpoint) {<br>    if (_channels.containsKey(id)) {<br>      throw Exception(&quot;Connection with id &#39;$id&#39; already exists.&quot;);<br>    }<br><br>    final channel = WebSocketChannel.connect(Uri.parse(endpoint));<br>    _channels[id] = channel;<br><br>    final controller = StreamController&lt;String&gt;.broadcast();<br>    _controllers[id] = controller;<br><br>    channel.stream.listen(<br>      (message) {<br>        if (message is String) {<br>          controller.add(message);<br>        }<br>      },<br>      onError: (dynamic error) {<br>        controller.addError(error.toString());<br>      },<br>      onDone: controller.close,<br>      cancelOnError: true,<br>    );<br>  }<br><br>  /// Send a message to a specific WebSocket connection.<br>  void send(String id, String message) {<br>    final channel = _channels[id];<br>    if (channel != null) {<br>      channel.sink.add(message);<br>    } else {<br>      throw Exception(&quot;No WebSocket connection found for id &#39;$id&#39;.&quot;);<br>    }<br>  }<br><br>  /// Disconnect a specific WebSocket connection.<br>  void disconnect(String id) {<br>    final channel = _channels.remove(id);<br>    final controller = _controllers.remove(id);<br>    if (channel != null) {<br>      channel.sink.close();<br>    }<br>    if (controller != null) {<br>      controller.close();<br>    }<br>  }<br><br>  /// Get the message stream for a specific connection.<br>  Stream&lt;String&gt; getMessages(String id) {<br>    final controller = _controllers[id];<br>    if (controller != null) {<br>      return controller.stream;<br>    } else {<br>      throw Exception(&quot;No WebSocket connection found for id &#39;$id&#39;.&quot;);<br>    }<br>  }<br><br>  /// Dispose all connections.<br>  void dispose() {<br>    _channels.forEach((id, channel) {<br>      channel.sink.close();<br>    });<br>    _controllers.forEach((id, controller) {<br>      controller.close();<br>    });<br>    _channels.clear();<br>    _controllers.clear();<br>  }<br>}</pre><h4><strong>Explanation:</strong></h4><ul><li><strong>Managing Connections</strong>: The repository maintains a map of WebSocket connections identified by unique IDs. This allows you to manage multiple WebSocket connections in a structured way.</li><li><strong>Message Streaming</strong>: Incoming messages for each connection are sent to a broadcast stream, making it easy to listen to messages for specific connections.</li><li><strong>Sending Messages</strong>: The send() method lets you send messages over a specific WebSocket connection.</li><li><strong>Connection Management</strong>: You can connect, disconnect, and get message streams for specific WebSocket connections.</li><li><strong>Disposing Resources</strong>: The dispose() method closes all WebSocket connections and cleans up resources to avoid memory leaks.</li></ul><p>This repository helps you manage multiple WebSocket connections efficiently, making your finance app responsive and scalable.</p><p>Next, we’ll cover how to use this repository in conjunction with state management to keep your app’s data in sync.</p><h4><strong>Creating the WebSocket Bloc, Events, and States</strong></h4><p>To effectively manage WebSocket connections in our finance app, we’ll use the <em>flutter_bloc</em> package to create a WebsocketBloc class. This Bloc will handle WebSocket events like connecting, disconnecting, sending, and receiving messages while keeping track of connection states. We’ll also define event and state classes using freezed to ensure immutability and consistency.</p><p>Create the following files to implement the WebSocket Bloc architecture:</p><h4><strong>websocket_bloc.j.dart</strong></h4><p>This file contains the main WebsocketBloc class that handles various WebSocket events and manages state transitions.</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>import &#39;package:wealth_app/commons/services/websocket/websocket_repository.dart&#39;;<br><br>part &#39;websocket_bloc.j.freezed.dart&#39;;<br>part &#39;websocket_event.dart&#39;;<br>part &#39;websocket_state.dart&#39;;<br><br>class WebsocketBloc extends Bloc&lt;WebsocketEvent, WebsocketState&gt; {<br>  WebsocketBloc(this._repository) : super(const WebsocketState(connections: {})) {<br>    on&lt;ConnectWebSocket&gt;(_onConnect);<br>    on&lt;DisconnectWebSocket&gt;(_onDisconnect);<br>    on&lt;SendMessageWebSocket&gt;(_onSendMessage);<br>    on&lt;ReceivedMessageWebSocket&gt;(_onReceivedMessage);<br>    on&lt;ErrorOccuredWebSocket&gt;(_onErrorOccurred);<br>  }<br><br>  final WebsocketRepository _repository;<br>  final Map&lt;String, StreamSubscription&lt;String&gt;&gt; _subscriptions = {};<br><br>  Future&lt;void&gt; _onConnect(ConnectWebSocket event, Emitter&lt;WebsocketState&gt; emit) async {<br>    final id = event.id;<br>    final endpoint = event.endpoint;<br><br>    if (state.connections.containsKey(id) &amp;&amp; state.connections[id]!.status != ConnectionStatus.disconnected) {<br>      emit(<br>        state.copyWith(<br>          connections: {<br>            ...state.connections,<br>            id: state.connections[id]!.copyWith(<br>              error: Exception(&quot;Connection with id &#39;$id&#39; already exists.&quot;),<br>            ),<br>          },<br>        ),<br>      );<br>      return;<br>    }<br><br>    emit(<br>      state.copyWith(<br>        connections: {<br>          ...state.connections,<br>          id: const ConnectionStateData(status: ConnectionStatus.connecting),<br>        },<br>      ),<br>    );<br><br>    try {<br>      _repository.connect(id, endpoint);<br>      // ignore: cancel_subscriptions<br>      final subscription = _repository.getMessages(id).listen(<br>        (message) {<br>          add(ReceivedMessageWebSocket(id: id, message: message));<br>        },<br>        onError: (dynamic error) {<br>          add(ErrorOccuredWebSocket(id: id, exception: Exception(error)));<br>        },<br>        onDone: () {<br>          add(DisconnectWebSocket(id: id));<br>        },<br>      );<br>      _subscriptions[id] = subscription;<br>      emit(<br>        state.copyWith(<br>          connections: {<br>            ...state.connections,<br>            // Clear any existing errors on successful connection<br>            id: ConnectionStateData.clearError(<br>              status: ConnectionStatus.connected,<br>              lastMessage: state.connections[id]?.lastMessage,<br>            ),<br>          },<br>        ),<br>      );<br>      // await subscription.cancel();<br>    } catch (e) {<br>      emit(<br>        state.copyWith(<br>          connections: {<br>            ...state.connections,<br>            id: ConnectionStateData(<br>              status: ConnectionStatus.disconnected,<br>              error: Exception(e),<br>            ),<br>          },<br>        ),<br>      );<br>    }<br>  }<br><br>  Future&lt;void&gt; _onDisconnect(DisconnectWebSocket event, Emitter&lt;WebsocketState&gt; emit) async {<br>    final id = event.id;<br><br>    await _subscriptions[id]?.cancel();<br>    _subscriptions.remove(id);<br><br>    _repository.disconnect(id);<br><br>    emit(<br>      state.copyWith(<br>        connections: {<br>          ...state.connections,<br>          // Clear any errors upon disconnection<br>          id: ConnectionStateData.clearError(<br>            status: ConnectionStatus.disconnected,<br>            lastMessage: state.connections[id]?.lastMessage,<br>          ),<br>        },<br>      ),<br>    );<br>  }<br><br>  void _onSendMessage(SendMessageWebSocket event, Emitter&lt;WebsocketState&gt; emit) {<br>    final id = event.id;<br>    final message = event.message;<br><br>    try {<br>      _repository.send(id, message);<br>      // Optionally, you can emit a state indicating the message was sent<br>      // Here, we clear any existing errors since sending succeeded<br>      emit(<br>        state.copyWith(<br>          connections: {<br>            ...state.connections,<br>            // Clear error on successful send<br>            id: ConnectionStateData.clearError(<br>              status: state.connections[id]?.status,<br>              lastMessage: state.connections[id]?.lastMessage,<br>            ),<br>          },<br>        ),<br>      );<br>    } catch (e) {<br>      add(ErrorOccuredWebSocket(id: id, exception: Exception(e)));<br>    }<br>  }<br><br>  void _onReceivedMessage(ReceivedMessageWebSocket event, Emitter&lt;WebsocketState&gt; emit) {<br>    final id = event.id;<br>    final message = event.message;<br><br>    emit(<br>      state.copyWith(<br>        connections: {<br>          ...state.connections,<br>          // Clear any existing errors on receiving a message<br>          id: ConnectionStateData.clearError(<br>            status: state.connections[id]?.status,<br>            lastMessage: message,<br>          ),<br>        },<br>      ),<br>    );<br>  }<br><br>  void _onErrorOccurred(ErrorOccuredWebSocket event, Emitter&lt;WebsocketState&gt; emit) {<br>    final id = event.id;<br>    final error = event.exception;<br><br>    emit(<br>      state.copyWith(<br>        connections: {<br>          ...state.connections,<br>          id: state.connections[id]!.copyWith(<br>            error: error,<br>          ),<br>        },<br>      ),<br>    );<br>  }<br><br>  @override<br>  Future&lt;void&gt; close() {<br>    _subscriptions.forEach(<br>      (id, subscription) {<br>        subscription.cancel();<br>      },<br>    );<br>    _repository.dispose();<br>    return super.close();<br>  }<br>}</pre><h4><strong>websocket_event.dart</strong></h4><p>This file defines the events that the WebsocketBloc will respond to, such as connecting, disconnecting, and sending messages.</p><pre>part of &#39;websocket_bloc.j.dart&#39;;<br><br>@freezed<br>class WebsocketEvent with _$WebsocketEvent {<br>  const factory WebsocketEvent.connect({<br>    required String id,<br>    required String endpoint,<br>  }) = ConnectWebSocket;<br>  const factory WebsocketEvent.disconnect({<br>    required String id,<br>  }) = DisconnectWebSocket;<br>  const factory WebsocketEvent.sendMessage({<br>    required String id,<br>    required String message,<br>  }) = SendMessageWebSocket;<br>  const factory WebsocketEvent.receivedMessage({<br>    required String id,<br>    required String message,<br>  }) = ReceivedMessageWebSocket;<br>  const factory WebsocketEvent.error({<br>    required String id,<br>    required Exception exception,<br>  }) = ErrorOccuredWebSocket;<br>}</pre><h4><strong>websocket_state.dart</strong></h4><p>This file defines the states that represent the current status of each WebSocket connection, including connection status, last received messages, and any errors.</p><pre>part of &#39;websocket_bloc.j.dart&#39;;<br><br>enum ConnectionStatus { initial, connecting, connected, disconnected }<br><br>@freezed<br>class ConnectionStateData with _$ConnectionStateData {<br>  const factory ConnectionStateData({<br>    ConnectionStatus? status,<br>    String? lastMessage,<br>    Exception? error,<br>  }) = _ConnectionStateData;<br><br>  /// Custom factory to create an instance with cleared error<br>  factory ConnectionStateData.clearError({<br>    ConnectionStatus? status,<br>    String? lastMessage,<br>  }) {<br>    return ConnectionStateData(<br>      status: status,<br>      lastMessage: lastMessage,<br>    );<br>  }<br>}<br><br>@freezed<br>class WebsocketState with _$WebsocketState {<br>  const factory WebsocketState({required Map&lt;String, ConnectionStateData&gt; connections}) = _WebsocketState;<br>}</pre><p>This setup provides a robust architecture for managing multiple WebSocket connections using BLoC in your finance app. The Bloc handles all events and state transitions, making it easy to connect, disconnect, and manage WebSocket communication in a scalable way.</p><p>Now finally, let us create a screen where we can actually handle websockets.</p><h4><strong>Building the UI for WebSocket Management</strong></h4><p>Now that we’ve set up the WebSocket repository and Bloc architecture, let’s create a user interface that allows us to manage multiple WebSocket connections and interact with them in real-time.</p><p>We’ll use a WebSocketScreen to demonstrate connecting, disconnecting, and sending messages through WebSockets.</p><h4><strong>websocket_screen.dart</strong></h4><p>Create a WebSocketScreen widget that displays a list of WebSocket endpoints. Each item in the list includes buttons for connecting and disconnecting, as well as a widget for displaying the connection status and last received messages.</p><p>Here’s the complete code for the UI:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:your_app_name/services/websocket/websocket_bloc.j.dart&#39;;<br><br>class WebSocketScreen extends StatefulWidget {<br>  const WebSocketScreen({super.key});<br><br>  @override<br>  State&lt;WebSocketScreen&gt; createState() =&gt; _WebSocketScreenState();<br>}<br><br>class _WebSocketScreenState extends State&lt;WebSocketScreen&gt; {<br>  final List&lt;Map&lt;String, String&gt;&gt; endpoints = [<br>    {&#39;id&#39;: &#39;ws1&#39;, &#39;endpoint&#39;: &#39;wss://echo.websocket.org&#39;},<br>    {&#39;id&#39;: &#39;ws2&#39;, &#39;endpoint&#39;: &#39;wss://echo.websocket.org&#39;},<br>  ];<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final bloc = BlocProvider.of&lt;WebsocketBloc&gt;(context);<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Multi WebSocket Bloc Example&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: endpoints.length,<br>        itemBuilder: (context, index) {<br>          final id = endpoints[index][&#39;id&#39;]!;<br>          final endpoint = endpoints[index][&#39;endpoint&#39;]!;<br><br>          return Padding(<br>            padding: const EdgeInsets.all(8),<br>            child: Column(<br>              children: [<br>                WebSocketWidget(id: id, title: &#39;WebSocket ${index + 1}&#39;),<br>                const SizedBox(height: 8),<br>                ElevatedButton(<br>                  onPressed: () {<br>                    bloc.add(ConnectWebSocket(id: id, endpoint: endpoint));<br>                  },<br>                  child: Text(&#39;Connect $id&#39;),<br>                ),<br>                ElevatedButton(<br>                  onPressed: () {<br>                    bloc.add(DisconnectWebSocket(id: id));<br>                  },<br>                  child: Text(&#39;Disconnect $id&#39;),<br>                ),<br>                const Divider(),<br>              ],<br>            ),<br>          );<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          // Example: Send a message to all connected WebSockets<br>          for (final endpointMap in endpoints) {<br>            final id = endpointMap[&#39;id&#39;]!;<br>            bloc.add(<br>              SendMessageWebSocket(id: id, message: &#39;Hello from $id&#39;),<br>            );<br>          }<br>        },<br>        child: const Icon(Icons.send),<br>      ),<br>    );<br>  }<br>}<br><br>class WebSocketWidget extends StatelessWidget {<br>  const WebSocketWidget({required this.id, required this.title, super.key});<br><br>  final String id;<br>  final String title;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocSelector&lt;WebsocketBloc, WebsocketState, ConnectionStateData?&gt;(<br>      selector: (state) =&gt; state.connections[id],<br>      builder: (context, connectionState) {<br>        String displayText = &#39;Not Connected&#39;;<br><br>        if (connectionState == null) {<br>          displayText = &#39;No Connection&#39;;<br>        } else {<br>          switch (connectionState.status) {<br>            case ConnectionStatus.initial:<br>              displayText = &#39;Initial&#39;;<br>              break;<br>            case ConnectionStatus.connecting:<br>              displayText = &#39;Connecting...&#39;;<br>              break;<br>            case ConnectionStatus.connected:<br>              displayText = &#39;Connected&#39;;<br>              break;<br>            case ConnectionStatus.disconnected:<br>              displayText = &#39;Disconnected&#39;;<br>              break;<br>            case null:<br>              displayText = &#39;null&#39;;<br>          }<br><br>          if (connectionState.lastMessage != null) {<br>            displayText += &#39;\nLast Message: ${connectionState.lastMessage}&#39;;<br>          }<br><br>          if (connectionState.error != null) {<br>            displayText += &#39;\nError: ${connectionState.error}&#39;;<br>          }<br>        }<br><br>        return Card(<br>          child: ListTile(<br>            title: Text(title),<br>            subtitle: Text(displayText),<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}</pre><h4><strong>Adding the Bloc to MaterialApp</strong></h4><p>To use the WebSocketScreen widget, wrap it in a BlocProvider and add it to your MaterialApp:</p><pre>MaterialApp(<br>  home: BlocProvider(<br>    create: (_) =&gt; WebsocketBloc(WebsocketRepository()),<br>    child: const WebSocketScreen(),<br>  ),<br>);</pre><h4><strong>Explanation</strong></h4><ul><li><strong>UI Components</strong>: The WebSocketScreen displays a list of WebSocket endpoints, each with buttons for connecting and disconnecting.</li><li><strong>WebSocketWidget</strong>: This widget displays the connection status, last message received, and any errors for a specific WebSocket connection using BlocSelector for efficient state updates.</li><li><strong>Floating Action Button</strong>: Sends a message to all connected WebSockets as an example of interacting with multiple connections.</li><li><strong>BlocProvider</strong>: The WebSocketBloc is provided at the top level to manage WebSocket events and states.</li></ul><p>With this setup, you have a complete UI for managing multiple WebSocket connections using Flutter Bloc. It ensures a clean architecture and responsive state management for real-time updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*AnrndNPF1rI8iWqVl3uArw.gif" /></figure><h3><strong>Conclusion</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*DyH0yPPnNUWe7pQe.jpg" /></figure><p>Building real-time applications using WebSockets in Flutter can significantly enhance user experience by providing instant data updates, low-latency interactions, and seamless communication. In this blog, we’ve covered the fundamentals of WebSocket integration in Flutter, including setting up connections, managing multiple WebSockets, handling errors, ensuring security, and creating a scalable architecture with Bloc for state management.</p><p>By leveraging WebSocket technology, you can create applications like chat apps, live dashboards, financial data streams, and more — empowering users with up-to-date information and interactive features. Proper connection management, security considerations, and effective state handling are crucial to ensuring a robust and resilient WebSocket-based app.</p><p>I hope this journey into WebSocket integration for your finance app has been insightful. As you continue exploring more real-time features and use cases, remember that the possibilities are endless when you combine WebSockets with Flutter’s flexibility and rich ecosystem.</p><p>Happy coding, and may your connections always stay open (until you close them properly)!</p><p><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1cdc3267a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Is the future or dead?]]></title>
            <link>https://codenameakshay.medium.com/flutter-is-the-future-or-dead-396a6b257d16?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/396a6b257d16</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[stadia]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 07:14:47 GMT</pubDate>
            <atom:updated>2022-11-04T07:14:47.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently Google pulled the plug on Stadia, its cloud-based gaming service. This leads us to think, will Flutter receive the same fate, or is it different?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_JG3LwWBkGu5UirSe0rsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJ6kG68dp0dxgkF9jI0D5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxXi4ROwQ5GXyjhJwEvVHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SmePVhQ5xCErLz4Hh0Cig.png" /><figcaption>Some of the Flutter community’s lead devs response on Google killing Stadia</figcaption></figure><p>Now I can directly tell you that the lead PM/UX for Flutter/Dart, recently wrote this in response to the above arguments.</p><blockquote>&quot;we&#39;re not shutting Flutter down&quot;<br>Google wouldn&#39;t be better off if we had to throw all that code away and start over.</blockquote><p>🔗<a href="https://news.ycombinator.com/item?id=33028259">(Disclosure: I lead PM/UX for Flutter &amp; Dart.) For sure, anything that I could s… | Hacker News (ycombinator.com)</a></p><p>But this tells us nothing. This just tells us the fact that currently, Flutter is not in a state like Stadia was, <strong>but can it be</strong>?</p><p>For this, we need to understand how Stadia started and how it finally met its demise.</p><h3>Chapter 1: Stadia — Google’s game changer?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4SRJO5n5xoQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4SRJO5n5xoQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4SRJO5n5xoQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2783b8a10b497ccbf54a52515b32864f/href">https://medium.com/media/2783b8a10b497ccbf54a52515b32864f/href</a></iframe><p>In the starting 30 secs of the video above, the narrator states that Google aimed to provide no lag no latency, and 4k game streaming, where you can play any game, anywhere. This concept can be understood as the internet-based version of Steam Link, in which you don’t need to have a PC to run games. Now overall the concept was pretty good, as I use this myself but with Xbox Cloud Gaming.</p><p>Google spent <strong>millions and millions</strong> of dollars into making Stadia a real thing and having both developers and gamers port their way onto it. But still, they <a href="https://www.thegamer.com/google-spent-millions-on-stadia-ports-including-20m-for-ubisoft-games/">missed out on targets by hundreds of thousands</a>. Why?</p><p>Now if you watch the above video from <a href="https://youtu.be/4SRJO5n5xoQ?t=182">3:02</a>, the narrator states that one needs at least 25mbps internet network connection to play games at 1080p 60FPS. Yeah, so many countries don’t have such internet infrastructure (<a href="https://fairinternetreport.com/research/internet-speed-by-country">source</a>), and therefore even basic 1080p game streaming was not possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nrk9Bg39ndK7u83h" /><figcaption>Stadia Pro membership</figcaption></figure><p>Don’t get me wrong, bigger markets such as the USA, and the UK have such infrastructure, and game streaming is getting picked up there as well, but they had another issue with Google Stadia. See in Stadia, one had to pay a subscription to play selected titles, and once you stop paying, the games are also taken away from you, unlike what happens in say Steam or any other store like Epic or Xbox. So you only have access to limited games, and you even have to pay for games that you already own, and they will not be yours forever and taken away once you stop paying.</p><p>Like if you just want to play My Little Pony, then you would have to buy the stadia Pro membership which is $10 per month, and you get to keep the game until you pay for the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P4t13BQgBM-pYgjy" /><figcaption>MyLittlePony available on Stadia Pro</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*t4VsXHSA0Gl9j6h-" /><figcaption>Same game available on Steam</figcaption></figure><p>And for that price, you can get the game for a lifetime if you just head over to Steam. So it didn’t make any sense for most games.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSDODi0MxLGI%3Fstart%3D461%26feature%3Doembed%26start%3D461&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSDODi0MxLGI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSDODi0MxLGI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c7ecdeb873bce3fba51521db662f614/href">https://medium.com/media/9c7ecdeb873bce3fba51521db662f614/href</a></iframe><p>So yeah not many people onboarded the Stadia train. (Watch the above video from <a href="https://youtu.be/SDODi0MxLGI?t=461">7:41</a>)</p><p>Now that we know how Google started Stadia, and why it met its demise, we can move on to Flutter.</p><h3>Chapter 2: Flutter, flutter and flutter</h3><p>Again we need to know why Flutter was started, and how it is doing currently to answer the question of whether is Flutter the future or dead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txX5hz4oJWuUReKRlNCFuw.png" /><figcaption>https://flutter.dev</figcaption></figure><p>So Flutter started with a mission to provide a single codebase for apps on Android, iOS, web &amp; desktop. It is a portable UI Kit, which is free and open-source and is used by developers and organizations around the world. One such organization is Google which uses Flutter for its apps such as Google Pay (<a href="https://flutter.dev/showcase/google-pay">source</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZB-PyxOManOqmBpg" /><figcaption><a href="https://www.freecodecamp.org/news/stack-overflow-developer-survey-2020-programming-language-framework-salary-data/">https://www.freecodecamp.org/news/stack-overflow-developer-survey-2020-programming-language-framework-salary-data/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RDEQDV_hIrj_7_ui" /><figcaption><a href="https://insights.stackoverflow.com/survey/2021#technology-most-popular-technologies">https://insights.stackoverflow.com/survey/2021#technology-most-popular-technologies</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQZLQWSTsGuuyCoG" /><figcaption><a href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">https://survey.stackoverflow.co/2022/#technology-most-popular-technologies</a></figcaption></figure><p>Now over the years, StackOverflow conducts a yearly survey that has many insights into the life of developers around the world. Now following that we can see that only 3.7% of the developers liked Dart in the year <a href="https://www.freecodecamp.org/news/stack-overflow-developer-survey-2020-programming-language-framework-salary-data/">2020</a>, which grew up to 6.02% in <a href="https://insights.stackoverflow.com/survey/2021#technology-most-popular-technologies">2021</a>, and 6.54% in <a href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">2022</a>. Now, this might not look big, but it is significant information, as due to the nature of Flutter being used in conjunction with the native language such as Kotlin, Swift, or JavaScript, these people are selecting Dart over these languages. We can see that Swift is declining each year by 1%, while Kotlin grows by around 0.5% each year. This makes us think <a href="https://stackoverflow.blog/2022/02/21/why-flutter-is-the-most-popular-cross-platform-mobile-sdk/">Why Flutter is the most popular cross-platform mobile SDK — Stack Overflow Blog</a>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*9T9VNUYPiEkvxjDL" /><figcaption>Flutter vs React Native (Number of questions on Stack Overflow each month)</figcaption></figure><p>Now, this percentage of StackOverflow questions shows the general developer’s interest in the corresponding framework, and we can see that number of questions in Flutter is growing way faster than the number of React Native questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*lLIOaqTchalYA_xI" /></figure><p>And quoting <a href="https://stackoverflow.blog/2022/02/21/why-flutter-is-the-most-popular-cross-platform-mobile-sdk/">this article</a>,</p><blockquote>After an explosive rise in usage over the past three years, Flutter’s market share is beginning to plateau.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxUnuzwhc6za-uY_" /><figcaption><a href="https://www.reddit.com/r/FlutterDev/comments/sxo41v/dart_is_the_lowest_paying_language_in_stack/">https://www.reddit.com/r/FlutterDev/comments/sxo41v/dart_is_the_lowest_paying_language_in_stack/</a></figcaption></figure><p>In the same surveys, it is constantly shown that Dart is the lowest-paying language, and even I can vouch for the fact that I would earn more if I code in Swift rather than Dart. It would also make my code much more important, as less number of people are available for Swift than Dart, and I don’t think Apple is switching to any other language any soon.</p><p><strong>So is this the beginning of the end?</strong></p><h3>Chapter 3: await Future.delayed(Flutter);</h3><p>The very next line in the above blog states that,</p><blockquote>But developers should not look at this as a sign that Flutter is going away anytime soon.</blockquote><p>New developers are puzzled by the question that what they should pick, React Native or Flutter? When they come to such surveys, they see that React has a bigger community (JavaScript), it has more stable tutorials, and courses, as it has been in the game for longer, it also pays more, and the jobs are readily available.</p><p>In contrast to this, most of the dubs Flutter has, are in the favour of the product, like the prototype can be made much faster, it would have better-looking UI and animations, and overall it is much easier to understand and code.</p><p>So this would point to the declining interest in Flutter, but there isn’t any declining interest. As mentioned by Tim Sneath,</p><blockquote>Over 600,000 apps in the Play Store alone are already written using Flutter, to say nothing of the countless apps for iOS, Windows, macOS, Linux and web. The list includes big brands like Alibaba, BMW, eBay, and SHEIN. Neither Google as a whole, nor Android in particular would be better off if Flutter didn’t continue to flourish.</blockquote><p>🔗<a href="https://news.ycombinator.com/item?id=33028259">(Disclosure: I lead PM/UX for Flutter &amp; Dart.) For sure, anything that I could s… | Hacker News (ycombinator.com)</a></p><p>Over 600,000 apps have already been built using Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*DlcgvAiRPkeSQGYb" /><figcaption><a href="https://docs.flutter.dev/resources/faq#should-i-build-my-next-production-app-with-flutter">FAQ | Flutter</a></figcaption></figure><p>Also, there is one more fact in support of Flutter compared to Stadia. It is open-source which means any developer can contribute to it, and it is not dependent on Google for functioning, even though currently they are the ones who maintain it. As in the case of many open-source projects, when one maintainer leaves, another one joins, and the legacy of such projects is carried on. There are many prominent developers such as <a href="https://twitter.com/remi_rousselet">Remi</a>, who have worked on many prominent plugins and packages for Flutter, and have even contributed to the Flutter engine code itself.</p><p>And due to the marketing efforts of Google, many big companies such as Samsung, Microsoft, Canonical (Organisation behind Ubuntu), and Sony have already started working with Flutter, i.e. developing their own cross-platform apps in it which further seals the deal. Also unlike Stadia or any other thing which has died, Flutter is not dependent on anything exclusive which is not available to the majority of people. It is available to everyone, for free, and they can run it on anything ranging from a potato PC or simple Android phone to even the best in class Mac Studio they can wish of.</p><h3>Final Boss: Conclusion</h3><p>There are many problems with Flutter, and in general how the Flutter team works, as pointed out in <a href="https://news.ycombinator.com/item?id=33028259#33030035">this comment</a>, but the fact of the matter is that it is not going anywhere, and is constantly growing, despite these. So I can firmly say that Flutter is the future, and is nowhere close to being dead it is just started to feel more alive than ever before.</p><p>Share your thoughts on this topic with me on <a href="http://twitter.com/codenameakshay">Twitter</a> @codenameakshay</p><p>If this story helped you, you can follow me on GitHub, to access codes, and examples. I also post such articles on my <a href="https://codenameakshay.github.io/blog-updated/">blog</a>; you can check it out too.</p><p>Thanks for reading, and Happy Fluttering!</p><p><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=396a6b257d16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Floating Bottom Bar How-to]]></title>
            <link>https://codenameakshay.medium.com/flutter-floating-bottom-bar-how-to-4164a9981afb?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/4164a9981afb</guid>
            <category><![CDATA[tabs]]></category>
            <category><![CDATA[bottombar]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 10:11:27 GMT</pubDate>
            <atom:updated>2021-12-26T15:37:39.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iU8wUhN16avIAOug1YuEqQ.png" /></figure><blockquote>Update — I have created a plugin for this, and you can simply use it now.</blockquote><blockquote>Link — <a href="https://pub.dev/packages/flutter_floating_bottom_bar">flutter_floating_bottom_bar | Flutter Package (pub.dev)</a></blockquote><p>In this article, I will show you how I created a floating navigation bar in Flutter. Here is the example for what we’ll be creating today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aPDMy4DZMloA09lDDi9Tkg.gif" /><figcaption>Floating Bottom Bar with tap to scroll up</figcaption></figure><h3>Step 1 — Create a new Flutter project</h3><p>First of all, I am going to create a new Flutter project. For that, simply open up BASH or Terminal and type flutter create floating_bar.</p><p>After your project has been created, open it up in your IDE of choice, and then remove all code from main.dart.</p><h3>Step 2— Create a the bottom bar widget</h3><pre>lib<br>├── pages<br>│   └── infinite_list_page.dart<br>├── provider<br>│   └── inherited_data_provider.dart<br>├── widgets<br>│   └── bottom_bar.dart<br>└── main.dart</pre><p>For this, simply create a new folder named widgets inside the lib folder and create a new file named bottom_bar.dart.</p><p>In that we are going to create a Stateful widget named BottomBar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f376f0c2ecec03594482f5b7f65852ca/href">https://medium.com/media/f376f0c2ecec03594482f5b7f65852ca/href</a></iframe><p>Then we are going to extend this class with SingleTickerProviderStateMixin, as we will be going to create an animation for the widget.</p><p>For that, create an AnimationController, and an Animation&lt;Offset&gt;, and initialise them in the initState().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8033e9a4db8c8d6f476d14a22a74928b/href">https://medium.com/media/8033e9a4db8c8d6f476d14a22a74928b/href</a></iframe><p>Also make sure to dispose the controller.</p><p>Then, we are going to create a few variables to keep track of our scrolling direction and position. For that, we will also create a ScrollController.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7c5c1a88185e232cc8679a3eeeb272/href">https://medium.com/media/fe7c5c1a88185e232cc8679a3eeeb272/href</a></iframe><p>Now we have to just add a listener to the ScrollController to keep the track of the position and direction of the scroll, and accordingly show/hide the BottomBar widget. We are going to add these listeners inside another function, but you can also write them inside <em>initState()</em>. We will then call this function from <em>initState()</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2338dccaeb1cfed9b6dbfdb5be5eeb9d/href">https://medium.com/media/2338dccaeb1cfed9b6dbfdb5be5eeb9d/href</a></iframe><p>Now, we are finally going to design the BottomBar. For that we will first create a Stack with two widgets, the page/child widget and then the actual BottomBar on top of it.</p><blockquote>For the page we are going to use an Inherited Widget using Provider. This is a topic for another article, so I won’t be going into detail of how I created this widget, which basically provides the page with the same ScrollController, we intialised, so that BottomBar can respond to the scrolling on the page.</blockquote><p>Simply create a file named inherited_data_provider.dart inside a new folder called provider inside lib folder.</p><p>In that copy paste the following code —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9ca70acd3fe38446220f96d05228a02/href">https://medium.com/media/a9ca70acd3fe38446220f96d05228a02/href</a></iframe><p>Then simply go back to the BottomBar widget and return the follwoing from the <em>build()</em> method of the widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/704ae9e64ea58be8b247e67a8d5957b1/href">https://medium.com/media/704ae9e64ea58be8b247e67a8d5957b1/href</a></iframe><p>Now, we are going to the creative part, and here I am going to create a bottom Tab Bar, but you can easily create whatever you want, inside your BottomBar.</p><p>Here’s the complete code for my BottomBar —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f7d934147b06e672ec15d4f13e0c8a6/href">https://medium.com/media/2f7d934147b06e672ec15d4f13e0c8a6/href</a></iframe><p>As you can see, I have taken the liberty to fully customise my BottomBar, and you can also do that.</p><h3>Step 3— Create the demo pages</h3><p>Now, we are going to create some tab views with infinite <em>ListView.builder()</em> list, so that we can see the demo of the BottomBar we have created.</p><p>First, I am going to create a simple page widget with infinite ListTiles, which we can use in all our tabs. For that create a new folder pages inside the lib folder, and create the <em>infinite_list_page.dart</em> file there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3e62e6df86298f1d48c9bfc072c920d/href">https://medium.com/media/b3e62e6df86298f1d48c9bfc072c920d/href</a></iframe><p>Now, we are simply going to write the code for <em>TabView</em> inside our <em>main.dart</em> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e99dcaabe9270f981c8baddde42d474f/href">https://medium.com/media/e99dcaabe9270f981c8baddde42d474f/href</a></iframe><h3>Conclusion</h3><p>So after that, when you finally hot restart your app, you’re going to see a Bottom Bar something like this. it basically floats, responds to scroll on pages, and also supports tabs, to change pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3D5-cQtYR6dIctyrA4znCg.gif" /></figure><p>Now, you can simply change a few things inside this widget to make it your own. I have shown three examples below. Also I can’t provide code for the examples below, as they aren’t open-source, but I assure you they aren’t that difficult if you get the gist of it.</p><p><a href="https://play.google.com/store/apps/details?id=com.hash.prism">Prism</a> —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*2ZkIz_Z0URKv_JGPbkuYgQ.gif" /><figcaption>Floating Bottom Bar in Prism</figcaption></figure><p><a href="https://play.google.com/store/apps/details?id=com.hash.buzzfire">BuzzFire </a>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*WownLLMXf0uUMi6npZFXww.gif" /><figcaption>Floating Bottom Bar in BuzzFire</figcaption></figure><p><a href="https://play.google.com/store/apps/details?id=com.lishash.lishash">Lishash </a>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*cOH5YHROmXDqXeLKNragew.gif" /><figcaption>Floating Bottom Bar in Lishash</figcaption></figure><p>To conclude this article, I think you are now able to create these beautiful bottom navigation bars that fit well into the new modern app user interface design that focuses on one-handed operation.</p><p>The full code can be found <a href="https://github.com/codenameakshay/flutter-floating-bottom-bar">here</a>, if you’re like me who understands more from code, rather than the blog.</p><p>If this story helped you, you can follow me on GitHub, to access more such codes, and examples. I also post such articles on my <a href="https://codenameakshay.github.io/blog-updated/">blog</a>; you can check it out too.</p><p>Thanks for reading, and Happy Fluttering!</p><ul><li><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></li><li><a href="https://github.com/codenameakshay/flutter-floating-bottom-bar">codenameakshay/flutter-floating-bottom-bar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4164a9981afb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I made my app go from 12M reads a day to 1M? (Flutter/Firestore)]]></title>
            <link>https://codenameakshay.medium.com/how-i-made-my-app-go-from-12m-reads-a-day-to-1m-flutter-firestore-83680acb01fe?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/83680acb01fe</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[read]]></category>
            <category><![CDATA[firestore]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 14:36:50 GMT</pubDate>
            <atom:updated>2021-06-23T14:36:50.253Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Context:</em></strong><em> I am the developer for Prism Wallpapers, which has 100K+ downloads on the Play Store. In the last 3 months we had seen a spike in our Cloud Firestore reads, although active users were almost the same. We actually tripled our project costs in that time, so for the first time in almost a year of the app being stable, we had no revenue.</em></p><p>Now back to the problem. Here are some graphs showing what happened and what it looks like now (after the problem has been solved).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBu49Y0Zo9UyMDg5G63-yg.png" /><figcaption>Having 12M reads on 7th June</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-4WTyRVHgnLVI-rqLNMAw.png" /><figcaption>Having constant 1M reads for 1 week.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*z0ALlPfQr44WRZY9ucaWgA.png" /><figcaption>Active Users (Watch the graph is nearly constant (Drop isn’t that much) between 30 May to 22 June)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*Kz_srmYlBKWTc3f2ZdV0gw.png" /><figcaption>The project cost graph showing cost rising linearly for May.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*zuPAgM4cz2kYEMZoFx3Mrw.png" /><figcaption>The project cost garph showing cost rising intially but then becoming constant for June.</figcaption></figure><h3>How was I able to pull this off?</h3><p>This was made possible due to four key steps we did —</p><p><strong>i) Revise user models from the ground up to curb unnecessary repetition for things like the profile photo or username.</strong></p><p>We used the Google login within our app, and we used the username/profile photo that Google provided for the user within our app. But since the profile photo or username is sometimes changed externally, we need to ensure that we retrieve the updated data ourselves to maintain consistency. For that, we were saving the updated links for profile photo and updated username in our Cloud Firestore. To fix this, we have redesigned the model to store profile photos in Firebase Storage and allow users to add a display name so there are no unnecessary read requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keVW23Xy_AgWi8UW0QbN5A.png" /><figcaption>The updated user model</figcaption></figure><p>We also wrote a function into our app that simply logs everyone out of their account on this update, so we can kill two birds with one stone. First, everyone can easily switch to a new model without any hassle, and second, unnecessary bot accounts, or like dead accounts are removed.</p><p><strong>ii) Switch from FutureBuilders to StreamBuilders.</strong></p><p>The switch to streams helps in two ways. First, we now don’t have to call a Future every day to fetch new walls, or every time the user starts the app even if there is no new wall, and it’s the same as with the local cache. The stream now does this automatically and curbs unnecessary requests. Second, the Firestore stream only fetches changes, which automatically means fewer read requests.</p><p>Streams vs Futures is a long long debate, on what you should use. I would say you first go to this <a href="https://stackoverflow.com/a/59610814/16036745">https://stackoverflow.com/a/59610814/16036745</a>, to understand their differences and then figure out the best solution for your use case.</p><p><strong>iii) Move data handling from client side to Firebase.</strong></p><p>We also used more and more of Firestore side handling (and using Cloud Functions) by using things like <a href="https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array">ArrayUnion</a> instead of first fetching that array, adding something into it, and then writing it back. So 1 read — 1 write request, becomes 1 write request.</p><p>Yeah, that’s it. It’s that simple.</p><p>Use ArrayUnion, ArrayRemove and other FieldValue provided in the package to curb these kinds of requests.</p><p>And also, I have said that you map your model intelligently so that you are able to use these kinds of things. This is another reason why we had to change the user model so we can use this in follower/following arrays.</p><p><strong>iv) Paginated the hell out of everything. Stopped automatic fetching/retrival, and made user click a button to see more.</strong></p><p>I know, I know, this is a pretty big step in terms of user experience, and we’ve already had so many messages from people wanting to bring back auto-loading walls instead of them clicking a button to see more now. But this is necessary.</p><p>Understand my situation. I was responsible for lowering the graph of reads. It was like we were taking money out of our revenue, and if we didn’t fix it, we’d have to shut down the servers, or we wouldn’t be able to pay as much (the cost prediction for that month was off the charts, and more than we’d make that month from Prism).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*P67xVJlIU6hlDw2MtqGIAQ.jpeg" /><figcaption>This is the see more button.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*PvqgDJg9FU-Einc7gOBx-Q.png" /><figcaption>Using that limit function to handle pagination</figcaption></figure><p>You can use <a href="https://morioh.com/p/5f0c0714bc09">this article</a> to achieve pagination in your app.</p><h3>Conclusion -</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FG96zgIcQn1L2xpmdxi%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Ftheoffice-the-office-peacock-tv-show-G96zgIcQn1L2xpmdxi&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FG96zgIcQn1L2xpmdxi%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/300c0bc0c57f46526011cf4a2a07e0cb/href">https://medium.com/media/300c0bc0c57f46526011cf4a2a07e0cb/href</a></iframe><p>So, this is how we pulled it off (Yes, I didn’t do this alone). Huge thanks to <a href="https://twitter.com/LiquidatorAb">LiquidatorAB</a> (my brother in crime).</p><p>Although this was difficult and took us a long long time to plan and then code everything, we were able to implement this without any major consequences to the user experience. There were a few minor UI bugs here and there, but you know we’ll fix them soon.</p><p>This was a big challenge, of course, and I learned a couple of things from it. First, how much better I am at programming now (logical aspect) than I was last year. For example, I now know what’s wrong with the code and am able to fix it. Secondly, that I never take a bug for granted. Like even the smallest things can sometimes be blown out of proportion. That’s the reason I love this and will continue to do this. Also, don’t think I won’t be cringy about this story for years to come. I will, because that’s exactly what it is. Cringy.</p><p>And also, you can check out the whole code for Prism <a href="https://github.com/Hash-Studios/Prism">here</a> (<a href="https://github.com/Hash-Studios/Prism">https://github.com/Hash-Studios/Prism</a>). Yes, it is open-source.</p><p><a href="https://github.com/Hash-Studios/Prism">Hash-Studios/Prism</a></p><p>If this story helped you, you can follow me on GitHub, to access more such codes, and examples. I also post such articles on my <a href="https://codenameakshay.github.io/blog-updated/">blog</a>; you can check it out too.</p><p>Thanks for reading, and Happy Fluttering!</p><p><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83680acb01fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Video Meets in Flutter using Jitsi Meet]]></title>
            <link>https://codenameakshay.medium.com/implementing-video-meets-in-flutter-using-jitsi-meet-5426ca37810a?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/5426ca37810a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[meet]]></category>
            <category><![CDATA[jitsi]]></category>
            <category><![CDATA[zoom]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 11:40:47 GMT</pubDate>
            <atom:updated>2021-03-23T11:40:47.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dc8YIB1FHJEc6STbDeEqsQ.png" /></figure><p>So, in this story, I will show you how to implement video meet like Zoom or Google Meet inside your own Flutter app using a package <a href="https://pub.dev/packages/jitsi_meet">jitsi_meet</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPf7Flpw3voM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPf7Flpw3voM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPf7Flpw3voM%2Fmaxresdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/446656a0898fcf22075adc5f3c0af859/href">https://medium.com/media/446656a0898fcf22075adc5f3c0af859/href</a></iframe><p>Without wasting any time, let’s start!</p><h3><strong>Step 1 — Create a new Flutter project</strong></h3><p>First, we need to create a simple demo project. For that, simply use flutter create video_demo command, and after it has been created use cd video_demo , code . to open the project in VSCode, my choice of IDE. You can open it in whatever you do code in, also Notepad if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*31PbhLmYzYq5I18fi388HA.png" /><figcaption>Create a new Flutter project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*OGs09NGU01YWCHP8wCykXw.png" /><figcaption>Open it inside VSCode or any other IDE</figcaption></figure><h3>Step 2 — Installing Jitsi Meet package</h3><p>Now, we need to install the <a href="https://pub.dev/packages/jitsi_meet">jitsi_meet</a> package. For that, simply follow these steps -</p><ol><li>First in your android/build.gradle file, set dependency of gradle tools to minimum of 3.6.3, like this</li></ol><pre>dependencies {<br>      classpath &#39;com.android.tools.build:gradle:3.6.3&#39; &lt;!-- This --&gt;<br>      classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;<br>      classpath &#39;com.google.gms:google-services:4.3.3&#39;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*4hMGLWZlNSx59rxmr8jFvA.png" /></figure><p>2. Then in your android/gradle/wrapper/gradle-wrapper.properties file, set distribution of gradle wrapper to minimum of 5.6.4, like this</p><pre>distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*54c77i53G6HalVi8Cwhk-Q.png" /></figure><p>3. Then in your android/app/build.gradle file, add these lines in android tag, to add Java 1.8 compatibility support to your project,</p><pre>compileSdkVersion 29<br>&lt;!-- Add the lines below --&gt;<br>compileOptions {<br>      sourceCompatibility JavaVersion.VERSION_1_8<br>      targetCompatibility JavaVersion.VERSION_1_8<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*6Fj3-bZpRQDOpzT9pr8GWg.png" /></figure><blockquote>Also, make sure that your targetSdkVersion &amp; compileSdkVersion are 29 or above. And your minSdkVersion is 23 or above.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*ijKi5GyDnGr5BZMC-JSurg.png" /></figure><p>4. Then add these two lines in your android/app/src/main/AndroidManifest.xml file. Also, I don’t know why these are added, I am just following what is written on pub.dev. This is what they have to say about it.</p><blockquote>Jitsi Meet’s SDK AndroidManifest.xml will conflict with your project, namely the application:label field. To counter that, go into android/app/src/main/AndroidManifest.xml and add the tools library and tools:replace=&quot;android:label&quot; to the application tag.</blockquote><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;yourpackage.com&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt; <em>&lt;!-- Add this --&gt;</em><br>    &lt;application <br>        tools:replace=&quot;android:label&quot;  <em>&lt;!-- Add this --&gt;</em><br>        android:name=&quot;your.application.name&quot;<br>        android:label=&quot;My Application&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;&gt;<br>        ...<br>    &lt;/application&gt;<br>...<br>&lt;/manifest&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*dktWjyqCEy-mnbDTtI6rhQ.png" /></figure><p>5. Add these proguard support lines too in android/app/build.gradle file.</p><pre>buildTypes {<br>      release {<br>            signingConfig signingConfigs.release<br>            &lt;!-- Add these lines --&gt;<br>            minifyEnabled true<br>            useProguard true<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android.txt&#39;), &#39;proguard-rules.pro&#39;<br>      }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuXWwo76tWc1v7GYuhBI5g.png" /></figure><p>Then add a file in the same directory called proguard-rules.pro. See the example app’s <a href="https://github.com/gunschu/jitsi_meet/blob/master/example/android/app/proguard-rules.pro">proguard-rules.pro</a> file to know what to paste in. (Copied exactly from pub.dev)</p><p>Also don’t forget to add some rules if you have Firebase in your project, as proguard needs to exclude Firebase core files. Copy/paste the following —</p><pre><em>## Flutter wrapper<br></em><strong>-keep </strong>class io.flutter.app.** {<strong> *; </strong>}<br><strong>-keep </strong>class io.flutter.plugin.**  {<strong> *; </strong>}<br><strong>-keep </strong>class io.flutter.util.**  {<strong> *; </strong>}<br><strong>-keep </strong>class io.flutter.view.**  {<strong> *; </strong>}<br><strong>-keep </strong>class io.flutter.**  {<strong> *; </strong>}<br><strong>-keep </strong>class io.flutter.plugins.**  {<strong> *; </strong>}<br><strong>-dontwarn </strong>io.flutter.embedding.**<strong>-keepattributes </strong>Signature<br><strong>-keepattributes </strong>*Annotation*<br><strong>-keepattributes </strong>EnclosingMethod<br><strong>-keepattributes </strong>InnerClasses<strong>-keep </strong>class com.lailen.edufix.viewholder.** {<br><strong>    *;<br></strong>}<strong>-keepclassmembers </strong>class com.lailen.edufix.models.** {<br><strong>    *;<br></strong>}</pre><p>More details <a href="https://medium.com/@alanpachuau/flutter-firebase-successful-release-build-configuration-34c01590ab5d">here</a>.</p><blockquote>This step is important, and failing to do this will result in errors, so beware and be alert. Also most of the errors are self-explainable, and also use</blockquote><blockquote>flutter pub cache repair<br>flutter clean</blockquote><blockquote>flutter run<br>to combat gradle cache and other errors.</blockquote><p>Final proguard-rules.pro file —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28538ec092f6cae74d57e9ba6f81f321/href">https://medium.com/media/28538ec092f6cae74d57e9ba6f81f321/href</a></iframe><p>Congratulations, if you have successfully installed the package, and your app is running, otherwise good luck from my side, see you in another article.</p><h3>Step 3 — Designing a page for Joining Meet</h3><p>Now we will be designing a page for joining the Meet. I’ m going to use Figma for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*ZZtIjeQfrSIoIC-eNQWJ8Q.png" /><figcaption>Final UI Design</figcaption></figure><p>You can check this design <a href="https://www.figma.com/file/5V1MolLAGofJv653DIqNEb/JitsiMeet?node-id=0%3A1">here</a> on Figma.</p><h3>Step 4 — Coding</h3><p>Now we will be actually converting this design into an app. For that, I will be adding the following code into a new file video_meet.dart which also includes the code from Jitsi Meet pkg.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee34c31ead4ecb9066a442690f694502/href">https://medium.com/media/ee34c31ead4ecb9066a442690f694502/href</a></iframe><p>Though this code is very simple, you may need to understand how Jitsi works. In my code there is a simple _joinMeeting() function which handles joining a meet. Now when we have joined the meet you can simply share the invite with others, and they can also join. But the problem with this is, that they have to join from the Jitsi Meet app, or Web Browser. For them to be able to join from your in app, you actually need to create a join button which asks for room name, from the user as it is the only thing required to join/create a meet.</p><p>In this example, I have also used Jitsi servers which have a limit of 25 monthly users, so if you want you can host Jitsi on your own server following this <a href="https://jitsi.github.io/handbook/docs/devops-guide/devops-guide-start">article</a>.</p><h3>Conclusion</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPf7Flpw3voM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPf7Flpw3voM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPf7Flpw3voM%2Fmaxresdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/446656a0898fcf22075adc5f3c0af859/href">https://medium.com/media/446656a0898fcf22075adc5f3c0af859/href</a></iframe><p>So, now you have a working meet app, in which users can join/create meetings, share their screens, create breakout rooms &amp; more! Though this has some caveats, I believe this is actually the best way to create/handle meetings in Flutter right now, as this is easy, offers many features &amp; can be scaled easily by shifting to your own server.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdpnfPvaCIHBrW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fboom-dpnfPvaCIHBrW&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FdpnfPvaCIHBrW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="598" frameborder="0" scrolling="no"><a href="https://medium.com/media/e41502f1a2ae78f3b9d435db3a8ff2b4/href">https://medium.com/media/e41502f1a2ae78f3b9d435db3a8ff2b4/href</a></iframe><p>I actually developed this for an internship I did with <a href="https://raahee.in/">Raahee</a>. They needed a video call method for therapists, to communicate with their clients/pateints.</p><p>If this story helped you, you can follow me on GitHub, to access more such codes, and examples. I also post such articles on my blog; you can check it out too.</p><p>Thanks for reading, and Happy Fluttering!</p><p><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></p><p><a href="https://codenameakshay.github.io/blog-updated/">codenameakshay’s Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5426ca37810a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going from Figma to Flutter in just 5 minutes]]></title>
            <link>https://medium.com/design-bootcamp/going-from-figma-to-flutter-in-just-5-minutes-8bde94f06892?source=rss-b46a5c18f171------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bde94f06892</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[resources]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Akshay Maurya]]></dc:creator>
            <pubDate>Wed, 17 Mar 2021 07:40:55 GMT</pubDate>
            <atom:updated>2021-03-20T13:13:22.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Convert Figma designs to Flutter code with this easy trick!" src="https://cdn-images-1.medium.com/max/900/1*P8W8wBZ2eFRELkDrW6hnKw.jpeg" /><figcaption>Convert Figma designs to Flutter code with this easy trick!</figcaption></figure><p>When I started developing apps with Flutter, there was this thing that one has to develop UI only using <strong>code</strong>. This makes it quite hard to visualize how the app will look beforehand. To solve this problem, <strong>Figma</strong> comes to the rescue. Using it, one can design beautiful UIs and assets for there application and then export them as images, which then can be used in Flutter using <em>Image.asset</em> objects. But there is one limitation to this that, even for like changing the color of button, you have to again export the image, import it into assets, and then rebuild the app to include those assets. But, today I will show you one trick to convert Figma components and Frames directly to Flutter code which then uses <strong>Custom Painter</strong> to draw those things in the application. So, if you need to change the properties of the asset, you can simply change them in the code.</p><p>So, let’s get started.</p><h3>Step-1 Get Figma API key</h3><p>For this step, first open you figma account on a browser, then click on your account name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/0*gbrH5L5vrJEKKKcz.jpg" /><figcaption>Open your Figma account</figcaption></figure><p>This will take you to the Account page. Then click the settings tab, to go the settings page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*nuMXIXJ7XRFAOSU8.jpg" /><figcaption>Click the Settings tab</figcaption></figure><p>Then in the Personal Access Token section click on Create a new personal token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*1K5QCyt_Vx-Axr8x.jpg" /><figcaption>Create a new personal token</figcaption></figure><p>Then generate your API key and make sure to copy it in a safe location because this is the last time Figma is letting you see it. We need it later on in this tutorial.</p><h3>Step-2 Design your assets or UI in Figma</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*moAENC6YhKrTLGkc.png" /><figcaption>Sample UI</figcaption></figure><p>In this step, you just need to draw the assets that you need. I am going to draw a button for demo purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pfdClACIuUISprqU.jpg" /><figcaption>I created this button in Figma</figcaption></figure><h3>Step-3 Open Figma to Flutter app</h3><p>Now after you have designed all your assets and converted them into <strong>components</strong>, just go to <a href="https://aloisdeniel.github.io/figma-to-flutter/">https://aloisdeniel.github.io/figma-to-flutter/</a>. Now in this website simply type up your <em>API key</em> in the authentication token section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*7i9Hq1C02QYl4BKG.jpg" /><figcaption>Open Figma to Flutter app</figcaption></figure><h3>Step-4 Getting your file code</h3><p>Now go to the file in Figma in which you have drawn your asset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aNso3PMUzQiSJzUi.jpg" /><figcaption>Open the Figma file</figcaption></figure><p>then go to the address bar and copy the highlighted text between the slashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U6uiUMwS2lhvF8GC.jpg" /><figcaption>Copy file key from the URL</figcaption></figure><p>This is your <em>file_key</em>. Now enter this <em>file_key</em> in the given section, in the Figma to Flutter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*F8OKdMYyR_p8zAvB.jpg" /><figcaption>Paste the file key here</figcaption></figure><h3>Step-5 Generating component code</h3><p>Now click <em>Load components</em> and then select the components from the list that pops up below, which you wanna import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*lZSEcQGdWAc5gWk8.jpg" /><figcaption>Select the components you want code for</figcaption></figure><p>Then click generate Dart code, to load the code in the code tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*d4Qa-9FXIgL6mcte.jpg" /><figcaption>Click generate Dart code to generate the code</figcaption></figure><p>Now just click copy to clipboard, to copy this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*oDM-xCfc1EnfUX27.jpg" /><figcaption>Copy code by clicking the copy to clipboard button</figcaption></figure><h3>Step-6 Importing code into Flutter</h3><p>Now, open your Flutter project in your editor and then create a new file in your lib folder, named <em>button.dart</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*KXvu4wqoX02Zhm_s.jpg" /></figure><p>Then simply paste your code into this file and save it. Now you just need to import this file in your <em>main.dart</em>, or wherever, you want to use it, in this case it’s <em>main.dart</em>. Then simply import the component widget by it’s name like I have in the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6cb4db9df246ba085db412252fc5b72/href">https://medium.com/media/a6cb4db9df246ba085db412252fc5b72/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e9fdf9699ec17d8c04ab47986f92d23/href">https://medium.com/media/1e9fdf9699ec17d8c04ab47986f92d23/href</a></iframe><p>Note — You may also need to include images that you used in Figma, in your assets in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*zp3V9OMI-Tp_0iaU.jpg" /><figcaption>Include assets in your pubspec.yaml</figcaption></figure><h3>Step-7 Build your app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*0Ymy2sjF1SSp5PzK.jpg" /><figcaption>Result</figcaption></figure><p>Now, as you can see this is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/0*fcyLG9lVnN9cGg51.gif" /></figure><p>This looks far from perfect, but it was an easy and fast way to simply import assets from Figma into Flutter, and with a little bit of tweaking here and there, it will be perfect.</p><h3>Conclusion</h3><p>Now this method works pretty much well with easier components like simple buttons, titles, etc. But it does have some caveats though.</p><p>First, it generates very long codes even for simple designs, and you could easily shorten it up. Second, it is not perfect, and some effects like shadows, are messed up like 99% of the time and you have to recreate them.</p><p>If this story helped you, you can follow me on GitHub, to access more such codes, and examples. I also post such articles on my blog, you can check it out too.</p><p>Thanks for reading, and Happy Fluttering!</p><p><a href="https://github.com/codenameakshay">codenameakshay - Overview</a></p><p><a href="https://codenameakshay.github.io/blog-updated/">codenameakshay’s Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bde94f06892" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/going-from-figma-to-flutter-in-just-5-minutes-8bde94f06892">Going from Figma to Flutter in just 5 minutes</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>