<?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 Алексей Попков on Medium]]></title>
        <description><![CDATA[Stories by Алексей Попков on Medium]]></description>
        <link>https://medium.com/@alexey.yu.popkov?source=rss-d0002ac9fea2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HVh_gBtlLcPALwzZ</url>
            <title>Stories by Алексей Попков on Medium</title>
            <link>https://medium.com/@alexey.yu.popkov?source=rss-d0002ac9fea2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:19:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexey.yu.popkov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter Navigation Is an Information Expert Problem]]></title>
            <link>https://medium.com/@alexey.yu.popkov/flutter-navigation-is-an-information-expert-problem-98041be4b80a?source=rss-d0002ac9fea2------2</link>
            <guid isPermaLink="false">https://medium.com/p/98041be4b80a</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Алексей Попков]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 18:38:22 GMT</pubDate>
            <atom:updated>2026-09-23T09:36:10.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOEi9OK8hAYgGeRBvqFBZw.png" /></figure><p><em>This is not a comparison of routing libraries — it’s about who should own navigation decisions, and why.</em></p><h3>The guidelines lead the wrong way</h3><p>A standard example from the go_router documentation:</p><p><strong>Listing 1.</strong> A transition defined inside widget code.</p><pre>TextButton(<br>  onPressed: () =&gt; context.go(&#39;/users/123&#39;),<br>)</pre><p>auto_route goes further and adds the extensions context.router.push(...) and context.pushRoute(...), which make such a call even shorter. Neither the Flutter documentation nor the guides of these packages mention that a transition defined inside widget code is an architectural problem. On the contrary, it is presented as the normal way.</p><p>This is not specific to Flutter. In iOS, the guidelines from Apple configure the next screen — and often create it — in the code of the previous one: this is true for storyboard segues, for pushViewController, and for the early NavigationLink(destination:). For this reason the Coordinator pattern [1], [2] remains common practice there. Android came to the opposite conclusion from another direction: the official Jetpack Compose guide requires developers not to pass navController into a composable, but to pass callbacks instead, so that screens stay reusable and testable [3].</p><h3>The resulting design errors</h3><p>A screen that knows where it leads introduces four errors at once:</p><ul><li><strong>Two responsibilities in one class.</strong> The screen is now responsible for the user interface, for reactions to user actions, and for navigation, including the creation of other screens and passing dependencies to them.</li><li><strong>Poor reusability.</strong> A screen that decides where to go next is difficult to place into another context, where the transition must be different.</li><li><strong>Tight coupling.</strong> Every screen knows about the next screens, so a change in one of them requires changes in others.</li><li><strong>Low testability.</strong> The reaction of a screen to a user action cannot be checked without navigation: the screen requires a configured router, and the result of a tap is not the fact of a request, but a transition that has actually happened. A unit test turns into an integration test.</li></ul><h3>The principle</h3><p>The problem appears because the previous screen owns information about the next one. The implementation of the transition has to be moved out of the screen code — and the question is where to move it.</p><p>The answer is given by <strong>Information Expert</strong>, one of the GRASP principles described by Craig Larman [4]: a responsibility is assigned to the class that has the information necessary to fulfil it.</p><p>This information is not the screen’s own. Which tab it belongs to, which stack is below it, whether the next screen must be opened above the current one or the whole section must be switched — none of this is decided by the screen. It is decided in the place where the application is assembled from screens.</p><p>So the screen declares an abstract contract for a transition and reports a user request through it. Nothing beyond this contract is known to the screen:</p><p><strong>Listing 2.</strong> The screen depends on a contract, not on a destination.</p><pre>abstract interface class UserListScreenCoordinator {<br>  Future&lt;T?&gt; onUserRoute&lt;T extends Object?&gt;(<br>    BuildContext context, {<br>    required String userId,<br>  });<br>}<br><br>final class UserListScreen extends StatelessWidget {<br>  const UserListScreen({<br>    super.key,<br>    required this.users,<br>    required this.coordinator,<br>  });<br><br>  final List&lt;User&gt; users;<br>  final UserListScreenCoordinator coordinator;<br><br>  @override<br>  Widget build(BuildContext context) =&gt; ListView(<br>    children: [<br>      for (final user in users)<br>        ListTile(<br>          title: Text(user.name),<br>          onTap: () =&gt; coordinator.onUserRoute(context, userId: user.id),<br>        ),<br>    ],<br>  );<br>}</pre><p>The handler now reports what the user did, and not where the application should go. The name of the method says the same thing: onUserRoute is a request about a user, not a command to open a route.</p><p>Suppose this list is used twice. It is the root of the contacts tab, and it is also the list of followers opened from the profile of the current user. A tap means the same thing in both places — show me this user — and it has to lead to different places: in the contacts tab the profile belongs to the stack of that tab, and among the followers it belongs to the profile stack, so that going back returns to the list of followers and not to the contacts.</p><p>The screen, the list and the user request are identical. The answers are not, and each of them is written where the screen is constructed:</p><p><strong>Listing 3.</strong> Two implementations of the same contract, each next to the place where the screen is built.</p><pre>final class ContactsUserListCoordinator implements UserListScreenCoordinator {<br>  const ContactsUserListCoordinator();<br><br>  @override<br>  Future&lt;T?&gt; onUserRoute&lt;T extends Object?&gt;(<br>    BuildContext context, {<br>    required String userId,<br>  }) =&gt; context.push&lt;T&gt;(&#39;/contacts/users/$userId&#39;);<br>}<br><br>final class FollowersUserListCoordinator implements UserListScreenCoordinator {<br>  const FollowersUserListCoordinator();<br><br>  @override<br>  Future&lt;T?&gt; onUserRoute&lt;T extends Object?&gt;(<br>    BuildContext context, {<br>    required String userId,<br>  }) =&gt; context.push&lt;T&gt;(&#39;/profile/followers/$userId&#39;);<br>}</pre><p>Neither destination can be chosen inside the screen — not because the information is out of reach there, but because reaching for it is the error itself. A widget can always ask GoRouter.of(context), or its auto_route counterpart, where it currently is. Having asked, the screen would then have to enumerate the places it can be opened from, that is, to know the structure of the whole application; every new place of use would mean editing the screen again, and the coupling that was just removed would be back. The information is available to the screen, but it is not the screen&#39;s own.</p><p>The choice of the implementation is made at the only point that knows the context — where the screen is constructed. This point is not a property of go_router:</p><p><strong>Listing 4.</strong> The same choice, expressed with three different tools.</p><pre>// go_router<br>GoRoute(<br>  path: &#39;/contacts/users&#39;,<br>  builder: (context, state) =&gt; UserListScreen(<br>    users: allUsers,<br>    coordinator: const ContactsUserListCoordinator(),<br>  ),<br>)<br><br>// auto_route: the same choice is made in the page that wraps the screen<br>@RoutePage()<br>final class ContactsUserListPage extends StatelessWidget {<br>  const ContactsUserListPage({super.key});<br>  @override<br>  Widget build(BuildContext context) =&gt; UserListScreen(<br>        users: allUsers,<br>        coordinator: const ContactsUserListCoordinator(),<br>      );<br>}<br><br>// the built-in Navigator: the same choice is made where the route is created<br>MaterialPageRoute(<br>  builder: (_) =&gt; UserListScreen(<br>    users: allUsers,<br>    coordinator: const ContactsUserListCoordinator(),<br>  ),<br>)</pre><p>Nothing has been added to the application. The call that stood inside the widget in Listing 1 is still a single context.push, and it has only moved to the object that has the right to make this decision.</p><h3>Where the implementation belongs</h3><p>The implementation of the contract belongs where the screen is created, not where the screen is declared. The object that creates the screen is the one that knows the context — the tab, the stack, the flow the screen was opened in — and keeping the implementation there puts the request and the answer to it in one place. Keeping it next to the screen would only return the same knowledge to the screen through a longer path.</p><p>In practice this means a different place for every tool, and the same rule in each of them. With the built-in Navigator, the implementation goes where the route is created — into the object that owns the stack. With go_router, it goes next to the GoRoute whose builder passes it to the screen. With auto_route, it goes into the page that wraps the screen, because that page is where the screen is finally assembled and where the generated route leads.</p><p>The principle itself is indifferent to this choice. Only the address of “the place where the screen is constructed” changes from tool to tool; which object is allowed to decide does not.</p><h3>A callback instead of an interface</h3><p>An abstract interface is not the only possible form of the contract. The screen can take a callback instead — Future&lt;T?&gt; Function&lt;T extends Object?&gt;(BuildContext context, String userId) onUserRoute — and the handler is then written directly at the point where the screen is constructed. A callback reads well when the tree of transitions is assembled by hand; an interface reads better when the library already shows that tree, as the GoRouter(routes: [...]) constructor does. The choice is a matter of syntax, not of responsibility.</p><h3>It does not have to be adopted at once</h3><p>This is the practical part. Transitions are moved out of screens one screen at a time, without changing the navigation library and without changes in the rest of the application. Each step is complete in itself: the processed screen stops depending on where it leads and becomes suitable for reuse in another context, while the rest of the navigation continues to work as before. As a side effect, such a screen can be tested without a router, because a stub is passed to it instead of a real implementation.</p><p>For the same reason the approach applies to existing code, not only to a new project. And it does not depend on a specific library: the form of the contract and the mechanics of a transition are defined by the selected tool, but the distribution of responsibilities stays the same.</p><p>The approach is not new. In iOS it is known as the Coordinator pattern [1], [2], and a simplified version of it is described in [5]; for Flutter a similar approach is described in [6]. What is worth repeating is the reason behind it: the screen is not the one who knows.</p><p>This article describes a principle, and the listings above are the shortest way to state it, not a recommended layout of files. One possible illustration of it is a sample application with two tabs, their own stacks and one profile screen that behaves differently in each tab: its navigation is implemented three times — with the built-in Navigator, with go_router and with auto_route. The code is in the repository [7], and a separate article examines it in detail [8].</p><h3>References</h3><ol><li><a href="https://khanlou.com/2015/01/the-coordinator/">Khanlou, “The Coordinator” (2015)</a> — the article that introduced the Coordinator pattern.</li><li><a href="https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps">Hudson, “How to use the coordinator pattern in iOS apps”</a> — a detailed description of the Coordinator in practice.</li><li><a href="https://developer.android.com/develop/ui/compose/navigation">Navigation with Compose</a> — the official Android guide: do not pass navController into a composable, pass callbacks instead.</li><li>Larman, <em>Applying UML and Patterns</em> (1997) — the book that describes the GRASP principles, including Information Expert.</li><li><a href="https://medium.com/@alexey.yu.popkov/ios-navigation-a-compact-router-approach-46cffa04a6ef">Popkov, “iOS Navigation: A Compact Router Approach”</a> — a simplified version of the Coordinator approach for iOS.</li><li><a href="https://medium.com/flutter-community/navigation-done-right-a-case-for-hierarchical-routing-with-flutter-ca0aac1275ad">Shevchuk, “Navigation done right: a case for hierarchical routing with Flutter” (2020)</a> — a similar approach in Flutter: the decision about a transition is passed from a screen to its parent.</li><li><a href="https://github.com/AlexeyYuPopkov/example_routing_coordinator_flutter">example_routing_coordinator_flutter</a> — one possible illustration of the approach: a sample application whose navigation is implemented three ways.</li><li><a href="https://dev.to/alexeyyupopkov/flutter-navigation-moving-transitions-out-of-screens-l1a">Popkov, “Flutter Navigation: Moving Transitions Out of Screens”</a> — a detailed walkthrough of the sample application: the same navigation implemented with Navigator, go_router and auto_route.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98041be4b80a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nostr as a backend out of the box: where it fits and where it doesn’t]]></title>
            <link>https://medium.com/@alexey.yu.popkov/nostr-as-a-backend-out-of-the-box-where-it-fits-and-where-it-doesnt-d52bace91c25?source=rss-d0002ac9fea2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52bace91c25</guid>
            <category><![CDATA[nostr]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Алексей Попков]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 13:45:47 GMT</pubDate>
            <atom:updated>2026-09-11T07:53:23.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBbu_gRjz55RtK43eYqE1w.jpeg" /></figure><blockquote><strong><em>TL;DR.</em></strong><em> Nostr is a ready-to-use, decentralized backend: it gives you an event model, signatures, encryption, and sync through relays. For notes, private chats, and simple feeds it covers almost everything — with no server of your own. But once you need a smart feed, roles, hierarchies, or complex moderation, the protocol hits one basic limit: only the owner of a key can change an event. After that, the extra workarounds quickly cost more than they save. Below I look at real cases: where Nostr works well, and where it is better to think about a separate backend.</em></blockquote><h3>Introduction</h3><p>For a long time I wanted to build a simple cross-platform notes app.<br> The most important use case for me was storing sensitive information, such as passwords, crypto wallet addresses, and so on. Another key requirement was reliable sync between devices, in particular iOS, Android, and macOS.</p><p>But there was one big problem: for a long time I could not find a secure way to sync notes that did not depend on one specific provider.</p><p>Some time ago I happened to join a project built around the <a href="https://github.com/nostr-protocol/nips">Nostr</a> protocol — that is how I first learned about it. For that project Nostr was, to be honest, not a great fit (you will see why later in the article). But for my notes task it turned out to be an almost perfect solution.</p><p>The goal of this article is to review the good and the bad cases of using the <a href="https://github.com/nostr-protocol/nips">Nostr</a> protocol that I ran into myself. I also want to describe the tasks it is worth using for, and the tasks where you should look for other solutions.</p><h3>What the Nostr protocol is and how it works</h3><p>The <a href="https://github.com/nostr-protocol/nips">Nostr</a> protocol presents itself as a backend for building decentralized social networks that are hard to censor. But, as you will see below, it can be used for a wider range of tasks. That said, building a social network in the usual sense (with complex feed ranking and filtering, and good performance on complex post models) is, in my personal opinion, hard.</p><p>The <a href="https://github.com/nostr-protocol/nips">Nostr</a> protocol is a set of rules (NIPs) for talking to a decentralized network of servers (relays). You talk to them over WebSockets. Each server keeps a database of events. An event is a record with a fixed structure; the client and the relay exchange it as a JSON object with a defined schema. A user can read and publish such events from one or more relays (and to one or more relays). Each event has an id — a hash of the event itself (more precisely, a SHA-256 of a serialized set of fields: pubkey, created_at, kind, tags, and content), not just of its content. So when you get the same event from different relays, the id is used to remove duplicates. Each event also has a signature. The signature is made from the event id and the sender&#39;s private key, and the JSON event has a field with the sender&#39;s public key. So to publish an event to one or more relays you need this key pair. (To read events you do not need any keys.)</p><p>It is easy to see that a key pair can also be used for asymmetric encryption. The spec describes common ways to encrypt chat messages — for example, the current <a href="https://github.com/nostr-protocol/nips/blob/master/44.md">Encrypted Payloads (NIP-44)</a>, which the <a href="https://github.com/nostr-protocol/nips/blob/master/17.md">Private Direct Messages (NIP-17)</a> feature is built on. There is also an older <a href="https://github.com/nostr-protocol/nips/blob/master/04.md">Encrypted Direct Message (NIP-04)</a>: it is officially marked as deprecated and is not recommended for public, decentralized use (it uses unauthenticated encryption and leaks metadata).</p><p>Still, it is important to understand that NIP-44 is not the only option. The protocol does not force a specific algorithm: clients are free to agree on any compatible way to encrypt content. So for practical tasks — say, if you run your own private relay or solve a specific business task — NIP-04 with plain AES, or any other scheme you like, can be a good fit.</p><h3>Data model: events, kind, and tags</h3><blockquote><em>If you already know Nostr (events, </em><em>kind, tags, the </em><em>REQ subscription model), feel free to skip this section and go straight to the cases.</em></blockquote><p>Before we get to the cases, it makes sense to look a bit closer at how an event is built — we will keep coming back to it.</p><p>Any Nostr event is JSON that looks roughly like this:</p><p>The kind field is an integer that sets the <em>rough</em> meaning of an event, rather than a strict type. For example, kind:0 is a user profile, kind:1 is a short text note (a post), kind:7 is a reaction (a like). It is important that this is an agreement, not a strict schema: the meaning of each kind is described in its NIP, and most NIPs have <em>draft</em> status - so these are conventions, not a fixed standard. The relay does not validate the structure of the content: the clients that agreed with each other are fully responsible for how a kind and the event format are read. You could say a kind is something like a &quot;table&quot; in a normal database, but without a strict schema and without server-side validation.</p><p>Besides meaning, kind also sets how the relay stores the event. The exact behavior depends on the number range (the ranges are defined in <a href="https://github.com/nostr-protocol/nips/blob/master/01.md">NIP-01</a>). In simple terms, events fall into:</p><ul><li><strong>regular</strong> — range 1000-9999 (also kind:1, kind:4-44); they just pile up and overwrite nothing;</li><li><strong>replaceable</strong> — range 10000-19999 (also kind:0 for a profile, kind:3 for a contact list); the relay keeps only the newest version for a given author, and a new event replaces the old one;</li><li><strong>addressable</strong> (also called parameterized replaceable) — range 30000-39999; the same as replaceable, but the &quot;coordinates&quot; for replacing also include the value of the d tag (see below). This is how updatable things with an identifier work - a long note (kind:30023), a community definition (kind:34550);</li><li><strong>ephemeral</strong> — range 20000-29999; the relay does not have to store them at all (useful for signaling).</li></ul><p>For addressable events the “coordinates” are the triple kind:pubkey:d, where d is the value of a special [&quot;d&quot;, &quot;...&quot;] tag - a stable identifier of the thing. The a tag points to such events using the kind:pubkey:d format (we will see this below).</p><p>The tags field is an array of arrays: the first item of each inner array is the tag name, and the rest are its values ([&quot;e&quot;, &quot;&lt;event id&gt;&quot;], [&quot;p&quot;, &quot;&lt;pubkey&gt;&quot;], and so on). Tags with single-letter names ( e, p, a, g, d, ...) are indexed by the relay, and you can filter queries by them - in a filter this is written as #e, #p, #g (this will be useful in the feed section).</p><p>Finally, about how events are requested. To get events, the client opens a subscription with a message like this:</p><p>A filter is a JSON object with fields like authors, kinds, since, until, limit, #e, #g. The relay returns all events that match at least one filter, and keeps the subscription open - it sends new matching events as they appear, until the client closes it with a CLOSE message. We will come back to filters and their limits.</p><h3>Notes</h3><p>While I was building my app, I did not really think about what the word Nostr stands for. Nostr is an acronym: Notes and Other Stuff Transmitted by Relays.</p><p>So the idea of a notes app on top of this protocol was obvious. Nostr gives you sync, and it offers recommendations for strong asymmetric encryption — <a href="https://github.com/nostr-protocol/nips/blob/master/44.md">Encrypted Payloads (Versioned)</a>.</p><p>So Nostr is a very good fit for this task.</p><p>This is how my pet project appeared — <strong>Private Notes (Nostr)</strong>: a cross-platform notes app with end-to-end encryption on the device (NIP-44), signing with secp256k1, and storage on relays the user picks. No server, no accounts — just a key pair. You can try it right now:</p><p>🍎 iOS: <a href="https://apps.apple.com/bg/app/private-notes-nostr/id6757975921">App Store</a></p><p>🌐 Web: <a href="https://alexeyyupopkov.github.io/">alexeyyupopkov.github.io</a></p><p>🤖 Android: <a href="https://play.google.com/store/apps/details?id=com.alekseii.yu.popkov.nostrNotes">Google Play</a></p><p>💻 Source code: <a href="https://github.com/AlexeyYuPopkov/nostr_notes">github.com/AlexeyYuPopkov/nostr_notes</a></p><p>The repository is open — if you find a bug or have an idea, feel free to open an <a href="https://github.com/AlexeyYuPopkov/nostr_notes/issues">Issue</a>, I will be glad to hear from you.</p><h3>Chats</h3><p>Many small mobile apps have a chat feature. For most such projects the chat backend is a third-party service like <a href="https://www.twilio.com/">Twilio</a>, <a href="https://quickblox.com/">Quickblox</a>, or a cloud database such as <a href="https://firebase.google.com/docs/database/">Firebase Realtime Database</a> or <a href="https://firebase.google.com/docs/firestore/">Cloud Firestore</a>. But this means extra costs for these subscriptions. In the second case you also need to design the database for chat data, and that means extra work and bugs. Nostr, on the other hand, gives you a ready backend that fits chats well. You can either use the many public relays that already work, or run your own on your own backend by downloading a popular implementation from GitHub.</p><p>One more thing worth mentioning is media content in chat messages. A Nostr event is always JSON with a fixed schema, and the protocol does not expect you to store binary data (images, files) inside an event. To solve this there is <a href="https://github.com/nostr-protocol/nips/blob/master/96.md">NIP-96</a> — a standard that describes HTTP File Storage: a spec for file hosts compatible with Nostr. The client uploads a file to a NIP-96 server, gets a URL, and puts it in the event content. Public NIP-96 servers exist, and in general this works.</p><p>But in practice, if a project already uses central infrastructure (AWS S3, Firebase Cloud Storage, and so on), it is simpler and safer to store media there and just put a link in the Nostr event. It is a plain approach, but for most products it is a reasonable one.</p><p>For one-on-one (one2one) chats Nostr gives you everything out of the box. But for group chats there are limits in practice, and getting around them needs extra logic.</p><p>I would point out two such problems:<br> 1) the performance of message encryption<br> 2) group moderation</p><p>The first one is this. To use asymmetric encryption ( <a href="https://github.com/nostr-protocol/nips/blob/master/04.md">Encrypted Direct Message</a> or <a href="https://github.com/nostr-protocol/nips/blob/master/44.md">Encrypted Payloads (Versioned)</a>), you have to encrypt the message separately for each user. As the number of group members grows, this can hurt both performance and the overall reliability of the approach. That said, from my own experience, for groups of 20 people or fewer I did not see real performance problems. I have read that up to 100 people should also be fine. At the same time, for extra reliability I would rather use central solutions outside the Nostr protocol to encrypt message content (even though that is less secure).</p><p>The second problem is moderating the group and adding or removing members. The existing solution, <a href="https://github.com/nostr-protocol/nips/blob/master/17.md">Private Direct Messages</a>, is basically a group conversation without a separate, managed group object. The group’s metadata (name, and so on) is not stored as one thing; it is computed from the tags of the messages themselves, and the tags of the newest message “win”. As a result, you cannot “hard” add or remove members, and in fact any member can redefine the group metadata — just by sending a new message with the tags they want. The root of the problem is in the base of the Nostr protocol: only the creator of an event can change it. So if you create an event — a chat room model — and link messages to it by a reference to the room, then only its creator can moderate that event. That means there is only one moderator. And even this solution is a bit artificial — I have not seen a NIP (a Nostr standard) for it.</p><p>There is also a solution to this problem — <a href="https://github.com/nostr-protocol/nips/blob/master/29.md">NIP-29</a>. It means running your own, separate relay for group moderation (though public relay-29 servers exist too, for example wss://relay.groups.nip29.com). The relay itself checks whether a moderator is allowed to change the group state. Such a relay is responsible only for the group state, not for the users&#39; messages, which are stored on normal relays. But this is, rather, a central solution (otherwise you lose the single source of truth and risk getting out of sync).</p><p>Overall, relay-29 is a good central solution for group chats with roles and moderation, and it really works.</p><h3>Feed, posts</h3><p>In my view, a social network is first of all posts, likes, comments, and reposts.</p><p>Let’s try to figure out how well the Nostr protocol fits these goals and what the limits are. We already know that relays store event models and can return their JSON over WebSockets.<br> For clarity, here is an example of a possible post JSON:</p><p>All tags are optional. Let’s go over the ones in the example:</p><ul><li>e - a reference to another event by its id; used for threads, quotes, and replies</li><li>a - a reference to an addressable (replaceable) event in the kind:pubkey:d format; in the example above these are references to kind:30023 events (long posts / articles per <a href="https://github.com/nostr-protocol/nips/blob/master/23.md">NIP-23</a>) by different authors</li><li>g - a <a href="https://en.wikipedia.org/wiki/Geohash">geohash</a> of the location the post is linked to; the longer the string, the more precise the coordinate (u4pr is a rough region, u4pru is a bit more precise)</li></ul><p>Now, to understand the limits of Nostr, let’s look at a few cases:<br> 1) To show, for example, posts (usually kind:1) by specific authors (see authors) in a feed, you send a request:</p><p>So far so good. With until + limit it is easy to set up time-based pagination here, and it will work reliably.</p><p>2) Now let’s make it harder. Say we need to build a feed that shows posts by specific authors OR posts by users with a nearby location:</p><p>And here a problem shows up right away. Inside one filter object all conditions work as AND — that is, authors + kinds + until must all match for one event. But to get OR between “posts by the authors we want” and “posts with the geohash we want”, you have to use two separate filters in an array. The relay then returns the union of both results.<br> And this is exactly where reliable until+limit pagination breaks. Each filter in the array is limited on its own: in a typical implementation the relay applies limit: 20 to each of the two filters separately (the exact behavior when merging results from several filters depends on the relay implementation), and then mixes the results. So imagine the first filter (by authors) collected 20 newer posts, and the second (by geohash) also collected 20, but older ones. The final output - after sorting by time and cutting to a common limit on the client - may take only part of one source and miss part of the other. On the next request the new until is computed from the oldest post you received. For one of the filters this until will be wrong: it will either cover already shown posts again, or skip part of the events that never reached the client. You get holes in the feed, and they add up with each new load.</p><p>A working but more time-consuming way is pagination through a time window ( since + until) that grows step by step - it widens if too few events fall into it. This approach has its own downsides: an unpredictable number of requests to the relay for one feed page, trouble showing a loading indicator, and the risk of a long &quot;freeze&quot; during quiet periods.</p><p>A third problem comes up at the level of the geohash filter itself: matching the g tag works by exact string equality, not by prefix. If an event has only [&quot;g&quot;, &quot;u4pr&quot;] (a rough location), and the filter asks for &quot;#g&quot;: [&quot;u4pruyd&quot;] (a more precise one), the relay will not return that event - even though u4pruyd is physically inside u4pr. People get around this by publishing several geohash tags of different length (all the prefixes) on one event. But then the client that makes the request has to list all the prefixes of the area it wants - this scales poorly and bloats the filter when you try to cover a wide area.</p><p>In the event model above you can see the a and e tags. With them you can link a post to some other event (for example, to another post, if the post is a comment on it - usually through an e tag, or a comment on some changeable event - through an a tag). The e and a tags are described in more detail in <a href="https://github.com/nostr-protocol/nips/blob/master/01.md">NIP-01</a>. A post can also have likes, which are usually done through kind=7 events, and comments ( e). To get the number of likes and comments and show them in the feed, you need to open subscriptions to the matching events and then count them. So after you get the post and learn its id, you send a request:</p><p>But likes and comments are far from the only things that can reference (or be referenced by) a given post. Through e/ a tags, a post can be pointed to by reposts ( kind=6/16), zap receipts ( kind=9735), reactions with custom content besides likes, quotes inside other posts, and so on. For each kind of link you basically need a separate subscription with its own kinds filter, or a wider filter with no kinds limit, which you then have to filter and parse on the client. Already at this stage you can see that to fully show one post card in a feed you may need not one but a whole set of parallel requests to the relay.<br> There is also a less obvious danger here. Since e/ a links are not limited by the protocol in any way, nothing stops events from referencing each other in a cycle - post A comments on post B, which itself is marked as a comment on post A (by accident, a client bug, or on purpose, as spam or an attack). A client that naively walks the tree of linked events (for example, to build a full thread) can fall into an endless loop if it does not add protection in advance - tracking the ids it has already visited, or limiting the recursion depth.</p><p>So while Nostr is a good fit for simple feeds, more complex ones can run into trouble: very greedy content loading and, as a result, a very large number of requests and poor performance.</p><p>As for the features we are used to in top social networks — a smart feed and many flexible filters — it seems you cannot build them with Nostr alone, without custom add-ons and without losing decentralization.</p><p>Then again, maybe it is better without a smart feed: it is not great that you often cannot find a post you liked a second time.</p><h3>Community</h3><p>One of the features built on Nostr that I had to work with is <a href="https://github.com/nostr-protocol/nips/blob/master/72.md">NIP-72</a>.<br> In short, <a href="https://github.com/nostr-protocol/nips/blob/master/72.md">NIP-72</a> is a NIP that describes moderated topic communities on top of normal Nostr events. A community is defined by an addressable event ( kind:34550), which lists its moderators. Any user can publish a post that links to this community - that is, propose a publication in the community. But for a post to actually count as part of the community and show up in its feed, one of the moderators must publish a separate approval event ( kind:4550). This event contains the original post in full and is signed by the moderator&#39;s key. When building the community feed, clients rely on these approval events, not on the posts with the tag. So selection and moderation here are fully on the side of public, verifiable signatures.</p><p>In principle, this works. But when a manager comes and says that any moderator should be able to moderate the community without the creator’s approval, a problem appears. <a href="https://github.com/nostr-protocol/nips/blob/master/72.md">NIP-72</a> does not assume that someone from the moderator list can edit the community definition itself. The moderator list in kind:34550 is just p tags listed inside an event signed by its owner. Only the holder of the private key that originally signed it can change this event (and therefore the moderator list) - that is, the community creator, not any of the listed moderators. This is a direct result of a base Nostr limit: only the holder of the key that is authoritative for an event&#39;s state can edit or redefine that state, and the protocol does not split this authority into roles at all. Trying to solve this with Nostr alone, without going beyond the protocol, leads nowhere good in the end. In practice the problem was solved with a central add-on - an extra service that adds extra signatures to events on top of the protocol model. But even with this solution I was very unhappy both with the <em>communities</em> feature itself and with the final implementation.</p><h3>One more similar use case — organizations</h3><p>I had to deal with this case too. Here is a short description of the task. There are organizations and sub-organizations, and posts and other similar events are published on their behalf. Only members can publish on behalf of an organization or sub-organization. Members have roles, and depending on the role they can invite other members.</p><p>Building this with Nostr alone is a doubtful idea. The protocol has no built-in model for roles, for an “organization → sub-organization” hierarchy, or for invitations; all it has is signing with one key as the only way to authorize. Here it is worth mentioning that Nostr did have a “native” way to delegate signing — <a href="https://github.com/nostr-protocol/nips/blob/master/26.md">NIP-26 (Delegated Event Signing)</a>, but it never caught on and is now marked as deprecated. So even the protocol’s own delegation mechanism was, in the end, seen as a failure, and in practice the task is solved centrally — for example, with <a href="https://github.com/erskingardner/keycast">keycast</a>, a service for delegating signing in Nostr, made specially for team work with keys. But even keycast does not fully solve the task, in particular the problem of roles. To give teams control over who can sign what, its authors had to build their own system of policies and permissions around keys — something the protocol does not have. This says a lot: even a tool made specially for delegating signing ends up coming down to writing a full backend from scratch. So managing roles and an organization hierarchy will also need central solutions — and not only for delegating signing, but also separately for managing roles. The amount of such work is comparable to writing a separate backend for this task, and using Nostr as the backend, or even as part of it, looks unjustified here.</p><h3>Conclusions</h3><p>If you go through all these cases — from notes and one2one chats to groups, feeds, and organizations — a fairly clear pattern appears.</p><p>Nostr really is a ready backend out of the box, and in two forms at once. It can be a fully decentralized solution based on a network of public relays. Or it can be a central one — if you run your own private relay and use the protocol just as a handy, ready format for data, sync, and authentication on top of your own infrastructure. The second option, by the way, is not as much of a compromise as it may seem: even if you give up decentralization, you still get a ready event model, signatures, encryption, and many ready client libraries. That is, you save time not only on infrastructure, but also on designing the communication protocol itself.</p><p>And for a number of tasks this solution really fits well — notes, chats (especially one2one), simple post feeds without claims to a complex feed. Here Nostr closes the classic problems (sync, encryption, identity) with almost no need to write your own backend at all.</p><p>But along the way I also collected a few lessons for myself.</p><p><strong>Do not try to build a full social network on the level of Facebook, or any top social network, on Nostr.</strong> As soon as a smart feed, flexible filtering, role models with hierarchy, and other features long standard for top social networks come into play, the protocol starts to fall apart. Not because the NIP authors missed something, but because the model itself (a relay as a dumb store of signed events, with no server that has the full and sole right to complex business logic) is not made for this.</p><p><strong>Do not try to get around the protocol’s limits.</strong> The temptation to “stretch” Nostr to the business logic you need with custom add-ons — be it a synthetic moderator model, extra signatures on top of events, or third-party delegation services — is strong, and almost always technically possible. But, as the NIP-72 and organizations cases show, at some point these add-ons start to weigh more than the protocol they were meant to make simpler. And, more importantly, getting around the limits is not free. Besides losing decentralization and compatibility with the rest of the Nostr ecosystem (other clients, relays, NIPs), such add-ons are always one more surface for bugs — bugs in code that no one but you has tested at scale.</p><p><strong>Before you start building, weigh both paths honestly: use Nostr with add-ons, or think about a separate backend for the specific task.</strong> Your own backend for roles, hierarchy, and moderation is written without looking back at someone else’s protocol limits like “one key owner”. It is often faster than building workarounds around Nostr — especially if the task fits the “signed events + relay” model poorly from the start.</p><p>The bottom line: Nostr is a great tool when the task lands in its “native” niche — and surprisingly awkward when you try to stretch it onto something it was not meant for. As with any tool, the main thing is to understand in advance which of these two groups your task falls into, instead of finding out after a month of work.</p><h3>The app from this article</h3><p><a href="https://github.com/AlexeyYuPopkov/nostr_notes">Private Notes (Nostr)</a> is open source — you can look through the code to see the approach in practice.</p><p><em>A Russian version of this article is available on Habr: </em><a href="https://habr.com/ru/articles/1050348/"><em>habr.com/ru/articles/1050348</em></a></p><p><em>Originally published at </em><a href="https://dev.to/__3c035ebd65/nostr-as-a-backend-out-of-the-box-where-it-fits-and-where-it-doesnt-465e"><em>https://dev.to</em></a><em> on June 23, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52bace91c25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Tip: Organize Your Localization with Multiple ARB Files Per Language]]></title>
            <link>https://medium.com/@alexey.yu.popkov/flutter-tip-organize-your-localization-with-multiple-arb-files-per-language-52606e5dbf25?source=rss-d0002ac9fea2------2</link>
            <guid isPermaLink="false">https://medium.com/p/52606e5dbf25</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[i10n]]></category>
            <dc:creator><![CDATA[Алексей Попков]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 13:20:56 GMT</pubDate>
            <atom:updated>2024-08-15T10:55:37.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMYvIGARZ6IySLaZMhN5pQ.png" /></figure><p>As your Flutter app grows, so does the complexity of managing its localization. Typically, translations are stored in a single Application Resource Bundle (*.arb) file, but this approach can become unwieldy as more content is added. The challenges of navigating a large ARB file, coupled with the risk of merge conflicts when multiple developers work on translations simultaneously, can slow down your development process.</p><p>One solution is to split your ARB file into smaller, more manageable files, is to break your project to several modules. However, if localization is the sole reason you’re considering breaking your app into multiple modules, this method might be overengineering. In such cases, simpler alternatives may be more appropriate.</p><p>In this article, we’ll explore how to effectively split ARB files in case of single module application.</p><h3>The Goal</h3><p>To demonstrate this approach, we’ll create a simple Flutter application with two tabs in the bottom navigation bar: “Home” and “Settings”. Since it’s logical to organize localization by feature, we’ll split the localization files accordingly. This means creating separate ARB files for each feature, resulting in the following structure:</p><pre>- l10n<br>  - home<br>    - home_en.arb<br>    - home_ru.arb<br>  - settings<br>    - settings_en.arb<br>    - settings_ru.arb</pre><p>This organization makes it easier to manage translations for each feature independently, reducing potential conflicts and simplifying navigation within the localization files.</p><h3>Step 2: Configuring Localization</h3><p>Typically, the next step, as outlined in the <a href="https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization">Flutter documentation</a>, involves adding a l10n.yamlfile to the root of your project. This file configures the gen-l10n tool, which generates the necessary Dart localization files.</p><p>However, instead of using a l10n.yaml file, we’ll use a Bash script. This approach allows us to generate the localization files for each feature-related ARB folder separately, keeping the process aligned with our folder structure. Create a Bash script with the following content:</p><pre>flutter gen-l10n --arb-dir ./lib/l10n/home --template-arb-file home_en.arb --output-localization-file home_localizations.dart --output-class HomeLocalizations &amp;&amp;<br><br>flutter gen-l10n --arb-dir ./lib/l10n/settings --template-arb-file settings_en.arb --output-localization-file settings_localizations.dart --output-class SettingsLocalizations</pre><p>This script runs the gen-l10n command for each ARB folder corresponding to the &quot;Home&quot; and &quot;Settings&quot; tabs, generating the appropriate Dart files. Once the script is created, run it to generate the necessary localization files.</p><h3>Step 3: Demonstrating the Result</h3><p>To showcase the outcome, I’ve created a playground application that allows users to switch the app’s language in Flutter. You can watch a brief demonstration in this <a href="https://youtube.com/shorts/dn_6lMnLmUM?feature=share">video</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fdn_6lMnLmUM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2Fdn_6lMnLmUM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fdn_6lMnLmUM%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6f62674478dc5d071422cec75ae63e/href">https://medium.com/media/dc6f62674478dc5d071422cec75ae63e/href</a></iframe><p>The source code for this example can be found on GitHub <a href="https://github.com/AlexeyYuPopkov/multi_arb_example">here</a>. Now, let’s break down how it works:</p><pre>final class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final locale = View.of(context).platformDispatcher.locale;<br>// 1<br>    return ChangeNotifierProvider(<br>      create: (_) =&gt; LanguageProvider(locale: locale),<br>      child: Consumer&lt;LanguageProvider&gt;(<br>        builder: (context, state, child) {<br>          return MaterialApp(<br>            home: const TabbarScreen(),<br>            locale: state.currentLanguage,<br>// 2<br>            localizationsDelegates: const [<br>              GlobalMaterialLocalizations.delegate,<br>              GlobalWidgetsLocalizations.delegate,<br>              GlobalCupertinoLocalizations.delegate,<br>              HomeLocalizations.delegate,<br>              SettingsLocalizations.delegate,<br>            ],<br>// 3<br>            supportedLocales: const [<br>              Locale(&#39;en&#39;),<br>              Locale(&#39;ru&#39;),<br>            ],<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Explanation:</h3><ol><li><strong>LanguageProvider:</strong> This class manages the language-switching logic.</li><li><strong>Localizations Delegates:</strong> Here, we add the necessary localization delegates to the app, including the delegates generated from the ARB files for the “Home” and “Settings” tabs.</li><li><strong>Supported Locales:</strong> We specify the locales supported by the app, in this case, English and Russian.</li></ol><h3>Step 4: Usage Example</h3><p>To retrieve localized titles for the “Home” and “Settings” screens, you can use the following code:</p><pre>import &#39;package:flutter_gen/gen_l10n/home_localizations.dart&#39;;<br>import &#39;package:flutter_gen/gen_l10n/settings_localizations.dart&#39;;<br><br>extension Localization on BuildContext {<br><br>// 1<br>  String get homeScreenTitle =&gt; HomeLocalizations.of(this)!.home_screen_title;<br><br>// 2<br>  String get settingsScreenTitle =&gt; SettingsLocalizations.of(this)!.settings_screen_title;<br>}</pre><h3>Explanation:</h3><ol><li><strong>Home Screen Title:</strong> This extension method retrieves the localized title for the “Home screen” using the HomeLocalizations class.</li><li><strong>Settings Screen Title:</strong> Similarly, this method retrieves the localized title for the “Settings screen” using the SettingsLocalizations class.</li></ol><h3>Conclusion</h3><p>Splitting your ARB files by feature, as demonstrated in this article, offers a more organized and scalable approach to managing localization in your Flutter application. By separating the localization data for different features, you reduce the likelihood of merge conflicts, simplify navigation within your ARB files, and align your localization structure more closely with your app’s architecture.</p><p>However, there is one trade-off with this approach: the Bash script described in Step 2 must be run manually whenever you update your localization files. This contrasts with the standard approach using l10n.yaml, which automatically regenerates localization files during a hot restart. While this additional step introduces a slight inconvenience, the benefits of a more maintainable and conflict-free localization system can far outweigh this minor drawback, especially in larger projects.</p><p>In summary, if you’re working on a growing Flutter app with multiple features, splitting your ARB files can streamline your localization process and improve collaboration within your team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52606e5dbf25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Navigation: A Compact Router Approach]]></title>
            <link>https://medium.com/@alexey.yu.popkov/ios-navigation-a-compact-router-approach-46cffa04a6ef?source=rss-d0002ac9fea2------2</link>
            <guid isPermaLink="false">https://medium.com/p/46cffa04a6ef</guid>
            <category><![CDATA[uik]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation-stack]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Алексей Попков]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 20:13:17 GMT</pubDate>
            <atom:updated>2024-07-29T20:13:17.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7FGREFcgL6AQB1onpBZbw.png" /></figure><p>In iOS navigation APIs, whether using UIKit or SwiftUI, the current screen is typically responsible for creating the subsequent screen. This approach has several disadvantages:</p><ul><li><strong>Increased Complexity and Violation of the Single Responsibility Principle (SRP):</strong> The screen (view controller or view) now handles not only its primary responsibility of managing the UI and user interactions but also the navigation logic, including creating other screens with their dependencies. This dual responsibility increases complexity, making the screen harder to understand at a glance.</li><li><strong>Limited Reusability:</strong> When a screen is responsible for its navigation, it becomes challenging to reuse that screen in different contexts where different navigation behavior is needed. This reduces the flexibility and reusability of the screen across the app.</li><li><strong>Tight Coupling:</strong> This approach creates tight coupling between screens, as each screen needs to know about the subsequent screens it can navigate to. This can lead to a fragile architecture where changes in one screen might necessitate changes in others.</li></ul><p>The existing approach to mitigate these issues is the Coordinator pattern, which significantly improves the architecture of iOS applications. However, it often introduces a lot of boilerplate code and can be hard to read. Additionally, understanding a complex navigation scenario involving multiple screens across several levels may require reviewing the code of multiple coordinators, which can be time-consuming.</p><p>The approach described below is, in my opinion, more straightforward and requires less boilerplate code. It has been thoroughly tested and is used in several iOS applications based on UIKit. As for SwiftUI, it leverages APIs introduced in iOS 16 and later, making its adoption a topic of discussion.</p><p>Let’s dive in. The approach that I am using is based on the idea that screens with transitions to other screens should include a closure to describe these transitions:</p><pre>protocol OnRouteProtocol {<br>    associatedtype Route<br>    var onRoute: ((Route) -&gt; Void)? { get set }<br>}</pre><p>Here’s an example of how to use this:</p><pre>final class ViewController: UIViewController, OnRouteProtocol {<br>    var onRoute: ((Route) -&gt; Void)?<br><br>    // ... layout is ommited<br><br>    @objc func onFeature1ButtonAction(sender: UIButton) {<br>        onRoute?(.onFeature1(self))<br>    }<br><br>    @objc func onFeature2ButtonAction(sender: UIButton) {<br>        onRoute?(.onFeature2(self))<br>    }<br>}<br><br>extension ViewController {<br>    enum Route {<br>        case onFeature1(UIViewController, /* parameters */)<br>        case onFeature2(UIViewController, /* parameters */)<br>    }<br>}</pre><p>In this example, to perform a transition to another screen, we call the onRoute closure with the relevant Route case. If necessary, this case can include any parameters needed by the next screen. Notably, ViewController does not contain any navigation logic and does not know anything about the screens it transitions to.</p><p>Now, let’s dive into the Router implementation. The video bellow demonstrates the behavior we aim to achieve.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3PR5E1s7Xr0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F3PR5E1s7Xr0%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3PR5E1s7Xr0%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c35cd9ed63c1fa670dbd1c1a0b638f8/href">https://medium.com/media/0c35cd9ed63c1fa670dbd1c1a0b638f8/href</a></iframe><p>Let’s start with the SceneDelegate:</p><pre>class SceneDelegate: UIResponder, UIWindowSceneDelegate {<br>    var window: UIWindow?<br><br>    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>        guard let windowScene = (scene as? UIWindowScene) else { return }<br><br>        let window = UIWindow(windowScene: windowScene)<br> // 1<br>        let router = HomeRouter()<br> // 2        <br>        let vc = router.initialScreen()<br> // 3<br>        window.rootViewController = vc<br>        self.window = window<br>        window.makeKeyAndVisible()<br>    }<br>}</pre><p>Here we are:</p><ol><li>Creating an instance of HomeRouter, which is responsible for managing navigation.</li><li>Using the router to get the initial view controller that should be displayed.</li><li>Setting the rootViewController of the window to the initial view controller.</li></ol><p>Next, let’s implement HomeRouter:</p><pre>final class HomeRouter {<br>    // 1<br>    func initialScreen() -&gt; UIViewController {<br>        let vc = createInitialScreen()<br>        let nc = UINavigationController(rootViewController: vc)<br>        return nc<br>    }<br>}<br><br>extension HomeRouter {<br>    private func createInitialScreen() -&gt; UIViewController {<br>        // 2<br>        let vc = HomeVC(nibName: nil, bundle: nil)<br>        // 3<br>        vc.onRoute = {<br>            switch $0 {<br>            case .pushTestScreenUIKit(let sender):<br>                self.pushTestScreenUIKit(sender)<br>            case .presentTestScreenUIKit(let sender):<br>                self.presentTestScreenUIKit(sender)<br>            case .onPushTestScreenSwiftUI(let sender):<br>                self.pushTestScreenSwiftUI(sender)<br>            case .onPresentTestScreenSwiftUI(let sender):<br>                self.presentTestScreenSwiftUI(sender)<br>            }<br>        }<br><br>        return vc<br>    }<br>}<br><br>// MARK: - Push and Present Test Screen UIKit<br>// 4<br>extension HomeRouter {<br>    private func pushTestScreenUIKit(_ sender: UIViewController) {<br>        let vc = TestScreenUIKit(nibName: nil, bundle: nil)<br>        sender.navigationController?.pushViewController(vc, animated: true)<br>    }<br>    <br>    private func presentTestScreenUIKit(_ sender: UIViewController) {<br>        let vc = TestScreenUIKit(nibName: nil, bundle: nil)<br>        sender.navigationController?.present(vc, animated: true)<br>    }<br>}<br><br>// MARK: - Push SwiftUI Test Screen<br>extension HomeRouter {<br>    private final class Box {<br>        weak var vc: UIViewController!<br>    }<br>    <br>    private func pushTestScreenSwiftUI(_ sender: UIViewController) {<br>        let box = Box()<br>        <br>        let view = TestScreenSwiftUI(<br>            isModal: false,<br>            onRoute: {<br>                switch $0 {<br>                case .onPushAnotherTestScreen:<br>                    self.pushPushAnotherTestScreen(sender: box)<br>                case .onPresentAnotherTestScreen:<br>                    self.presentAnotherTestScreen(sender: box)<br>                case .onBack:<br>                    break<br>                }<br>            }<br>        )<br>        <br>        let vc = UIHostingController(rootView: view)<br>        <br>        // 5<br>        box.vc = vc<br>        <br>        sender.navigationController?.pushViewController(vc, animated: true)<br>    }<br>    <br>    private func pushPushAnotherTestScreen(sender: Box) {<br>        let vc = UIHostingController(rootView: AnotherTestScreenSwiftUI())<br>        sender.vc.navigationController?.pushViewController(vc, animated: true)<br>    }<br>    <br>    private func presentAnotherTestScreen(sender: Box) {<br>        let vc = UIHostingController(rootView: AnotherTestScreenSwiftUI())<br>        sender.vc.present(vc, animated: true)<br>    }<br>}<br><br>// MARK: - Present SwiftUI Feature<br>extension HomeRouter {<br>    private func presentTestScreenSwiftUI(_ sender: UIViewController) {<br>        // 6<br>        let router = SwiftUIRouter()<br>        <br>        // 7<br>        let vc = router.initialScreen()<br>        vc.modalPresentationStyle = .fullScreen<br>        <br>        router.onRoute = { [weak vc] in<br>            switch $0 {<br>            case .onBack:<br>                vc?.dismiss(animated: true)<br>            }<br>        }<br>        <br>        sender.present(vc, animated: true)<br>    }<br>}</pre><p>Explanation:</p><ol><li><strong>Get the root screen:</strong> Only one public method here, providing the initial view controller.</li><li><strong>Assembly of the initial screen:</strong> The router serves as a good place to assemble new screens and set up their dependencies. Alternatively, a separate class with factory methods can be used for screen assembly and dependency injection.</li><li><strong>Setting up transitions to other screens:</strong> The router handles transitions based on the onRoute cases. It can pass the sender UIViewController and any required parameters to the next screen. Note that we do not use [weak self] here; the Router is captured as a strong reference because the screen implicitly owns it.</li><li><strong>Push or present new screens:</strong> The router assembles and sets up dependencies for the new screens, then displays them using the sender’s navigationController.</li><li><strong>SwiftUI screen transition:</strong> This demonstrates transitioning to a screen implemented in SwiftUI, including a workaround to access the UIHostingController sender.</li><li><strong>Transition to another </strong><strong>Router:</strong> This example shows how to transition to another router implemented in the SwiftUI style.</li><li><strong>Getting the root screen of the new Router:</strong> We can present the initial screen of the new router, but we cannot push it into the navigation stack. This is because UIKit and SwiftUI navigation stacks cannot be mixed directly; they must be managed separately.</li></ol><p>The transition to navigation in SwiftUI style is demonstrated below:</p><pre>// 1<br>final class SwiftUIRouter: ObservableObject, OnRouteProtocol {<br>    enum Route {<br>        case onBack<br>    }<br>    <br>    var onRoute: ((Route) -&gt; Void)?<br>    <br>    @Published var path = NavigationPath()<br>    <br>    // 2<br>    func initialScreen() -&gt; UIViewController {<br>        return UIHostingController(rootView: InitialView(router: self))<br>    }<br>}<br><br>extension SwiftUIRouter {<br>    // 3<br>    struct InitialView: View {<br>        @StateObject var router: SwiftUIRouter<br>        @State var modalView: TestScreenSwiftUI.Route?<br>        <br>        var body: some View {<br>            NavigationStack(path: $router.path) {<br>                TestScreenSwiftUI(<br>                    isModal: true,<br>                    onRoute: {<br>                    switch $0 {<br>                    case .onPushAnotherTestScreen:<br>                        router.path.append($0)<br>                    case .onPresentAnotherTestScreen:<br>                        modalView = $0<br>                    case .onBack:<br>                        self.router.onRoute?(.onBack)<br>                    }<br>                }<br>                )<br>                .navigationDestination(for: TestScreenSwiftUI.Route.self, destination: showScreen)<br>                .sheet(item: $modalView, // or .fullScreenCover<br>                       onDismiss: { modalView = nil },<br>                       content: showScreen)<br>            }<br>        }<br>    }<br>}<br><br>extension SwiftUIRouter.InitialView {<br>    @ViewBuilder func showScreen(_ route: TestScreenSwiftUI.Route) -&gt; some View {<br>        switch route {<br>        case .onPushAnotherTestScreen:<br>            AnotherTestScreenSwiftUI()<br>        case .onPresentAnotherTestScreen:<br>            AnotherTestScreenSwiftUI()<br>        case .onBack:<br>            fatalError(&quot;Impossible case&quot;)<br>        }<br>    }<br>}</pre><p>Explanation:</p><ol><li>Since SwiftUIRouter in current example isn&#39;t the root router, it have to be able to return control to previous Router. Therefore, OnRouteProtocol must be implemented to provide the appropriate option. Moreover, SwiftUIRouter must be an ObservableObject and must have a NavigationPath @Published var to use the SwiftUI navigation approach introduced in iOS 16.</li><li>To transist from UIKit API to SwiftUI API, initial view should be wrapped in UIHostingController</li><li>The following is a typical implementation of navigation using SwiftUI API introduced in iOS 16.</li></ol><h3>Conclusions</h3><p>The approach outlined here simplifies navigation management in iOS applications by separating navigation logic from UI components, adhering to the Single Responsibility Principle, and reducing boilerplate code. It enhances code readability and maintainability by using closures for handling screen transitions.</p><p>For best practices, it’s recommended to keep the number of screens managed by a single router balanced — neither too many, which would reduce readability, nor too few, which would unnecessarily increase the number of routers. The router should ideally describe a holistic business scenario, ensuring the code remains understandable and maintainable.</p><p>This compact and efficient approach to navigation can significantly enhance the architecture of iOS applications, making them more robust and scalable. For a complete example of this implementation, <a href="https://github.com/AlexeyYuPopkov/swift_router_example">click here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46cffa04a6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>