<?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 Ben Auer on Medium]]></title>
        <description><![CDATA[Stories by Ben Auer on Medium]]></description>
        <link>https://medium.com/@ben.auer.dev?source=rss-e63bd9c95020------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*249bM6sdqq9KFFlI7KumRw.png</url>
            <title>Stories by Ben Auer on Medium</title>
            <link>https://medium.com/@ben.auer.dev?source=rss-e63bd9c95020------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:03:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ben.auer.dev/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 Felt Like Making a “Desktop Flag Manager.”]]></title>
            <link>https://medium.com/@ben.auer.dev/i-felt-like-making-a-desktop-flag-manager-90d88dec687e?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d88dec687e</guid>
            <category><![CDATA[arch]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[hyprland]]></category>
            <category><![CDATA[wayland]]></category>
            <category><![CDATA[tiling-window-manager]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Fri, 16 May 2025 12:07:18 GMT</pubDate>
            <atom:updated>2025-05-16T12:21:27.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eks2O9hWWBiYUDfRXfdNWQ.jpeg" /></figure><h4>Here’s Why.</h4><p>If you’d asked me a week before I built this app what a <strong>Desktop Flag Manager</strong> should even be, I probably would’ve just scratched my head. But after running into the problem, figuring out a simple fix, and hacking together a tool to simplify it further, I needed a name — not some fancy marketing term, just something straightforward that explains what it does without any fuss.</p><p>After switching to Hyprland on Wayland, I started running into issues with a few apps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s0sEl4RTlIIEsCEooPWxQ.jpeg" /><figcaption>screenshot of HTOP showing CPU being used up to 99.6% by trying to run Github-Desktop</figcaption></figure><ul><li>Slack, Discord, VS Code, and GitHub Desktop would start but caused high CPU usage and occasional unresponsiveness.</li><li>1Password wouldn’t launch at all.</li></ul><h4>The Fix</h4><ul><li>For most apps, adding the --disable-gpu flag to their launch command fixed the performance issues.</li><li>For 1Password, the only way to get it working was using --ozone-platform=x11 to force it onto X11.</li></ul><h4>The Problem</h4><p>Making these changes wasn’t difficult, but it was tedious:</p><ul><li>You can’t modify system .desktop files in /usr/share/applications/.</li><li>Instead, you have to copy them to ~/.local/share/applications/, then edit the Exec= line.</li><li>Then run update-desktop-database to apply changes.</li></ul><h4>So I Built Desktop Flag Manager</h4><p>As a Flutter dev, I basically had all the tools available to solve this in a more elegant way:</p><ul><li>🔍 Search for installed applications</li><li>📄 Create a local .desktop override if one doesn’t exist</li><li>🎛️ Toggle launch flags like --disable-gpu or --ozone-platform=x11</li><li>⚙️ Automatically run update-desktop-database after changes</li></ul><p>That’s it. It just handles the repetitive bits so I don’t have to.</p><p>If you run into the same problem, feel free to try it out: <a href="https://github.com/BenAuerDev/desktop_flag_manager/releases/latest">https://github.com/BenAuerDev/desktop_flag_manager/releases/latest</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d88dec687e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where is Dash’s Penguin Fam?]]></title>
            <link>https://medium.com/@ben.auer.dev/where-is-dashs-penguin-fam-8b2590acc0de?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2590acc0de</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Sun, 04 May 2025 10:48:59 GMT</pubDate>
            <atom:updated>2025-05-05T06:10:57.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6ZXWGlNuVhptHkiKWLxBQ.png" /><figcaption>Dash and the Penguins (generated by Mr. GPT)</figcaption></figure><h4>Intro</h4><p>I’m sure it won’t come as a surprise to anyone who knows me but, I use Linux and I love it. Not just that it already had legend status in my childhood for making PCs with horrible performance on Windows decently usable. But also that it is community driven, open-source and therefore free for everyone to access.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FuyoXx0qpUWfQs%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcool-nice-thumbsup-uyoXx0qpUWfQs&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbnF4dDI1anplYWk2Z245eWhxanVwY285ZHVqNGM4c2pkNHh1cmtybyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FuyoXx0qpUWfQs%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/f40e6fc07ce674a4cba658d702bec94b/href">https://medium.com/media/f40e6fc07ce674a4cba658d702bec94b/href</a></iframe><p>And that community spirit is exactly what I love about the Dart ecosystem too. It’s impressive how, even being relatively young, it boasts frameworks like <strong>Flutter, Serverpod and Jaspr</strong> that act as real Institutions for collaboration and sharing knowledge and experiences. Beyond those, the <strong>breadth of countless valuable contributions</strong> from the community truly shows that spirit in action.</p><h4>We might not be many!</h4><p>Of course, I know most Flutter devs probably use macOS out of pure convenience, and Windows certainly has its fair share too. That actually makes me <em>even more</em> curious about those of us who love Dart/Flutter and rock Linux. <strong>Like what distro you choose and why, how you customize if you do so and if you encountered obstacles on your journey.</strong></p><p><strong>Let’s be real:</strong> Flutter aims to run everywhere, but how often have you scrolled through a Stack Overflow answer or a tutorial, only to realize the fix assumes a macOS or Windows setup? That brew install command isn&#39;t much help here, is it?</p><pre>[ERROR:flutter/shell/platform/linux/fl_window_manager_plugin.cc(150)] Failed to focus window: Gdk-CRITICAL **: 12:34:56.789: gdk_window_focus: assertion &#39;GDK_IS_WINDOW (window)&#39; failed</pre><p>And what about those services or apps you end up using in the browser, simply because there’s no native Linux version available?</p><h4>The Power of Flutter for Desktop</h4><p>On a related note, working on a cross-platform desktop app recently, I’ve seen firsthand how powerful Flutter can be for building amazing, performant desktop applications. It makes you think — with a toolkit this capable, maybe we, as the Flutter+Linux community, could tackle some of those missing tools or services ourselves? Sharing ideas or ‘wish lists’ could be the spark needed to kickstart something cool built <em>with</em> Flutter, <em>for</em> our Linux setups.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9F05QFBumusQzGzWSa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FEmpowerHQ-9F05QFBumusQzGzWSa&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcnJlMHZraWR3dXdvY3A2YW02NjN1emxmNzBxcWloMXJ5MW1ucW91eSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F9F05QFBumusQzGzWSa%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="161" frameborder="0" scrolling="no"><a href="https://medium.com/media/cac752868293bfc35112bb1baa6f7996/href">https://medium.com/media/cac752868293bfc35112bb1baa6f7996/href</a></iframe><h4>My Setup</h4><p>So, to kick things off, a bit about my setup: I’m a big fan of <a href="https://archlinux.org/">Arch Linux </a>with <a href="https://hyprland.org/">Hyprland</a> (using the <a href="https://github.com/mylinuxforwork/dotfiles">ml4w dotfiles</a>, if you’re curious!) and also really dig Pop!_OS with the Cosmic desktop. My main editor is VS Code, and I also use <a href="https://flathub.org/apps/io.github.shiftey.Desktop">Github Desktop (Community Version for Linux ❤)</a>, <a href="https://flathub.org/apps/it.mijorus.gearlever">GearLever</a> for anything regarding AppImages and my preferred mobile emulator is <a href="https://www.genymotion.com/product-desktop/download/">Genymotion</a>.</p><p>But that’s just my little corner. Now, I’d love to hear about yours! What does <em>your</em> Flutter+Linux world look like? And if you’re neither a Flutter Developer or a Linux user and made it this far, feel free to leave what OS you use.</p><h4>Connect and exchange!</h4><p>Anyway, that’s the main idea. It feels like there’s a cool niche community of Flutter Linux users out there (‘Dash Penguin Fam’ represent!), and it would be awesome to connect more deliberately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UK_nJF9BL_2hiRj4" /><figcaption>Photo by <a href="https://unsplash.com/@hannahbusing?utm_source=medium&amp;utm_medium=referral">Hannah Busing</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let me know what you think about the ideas for sharing — whether it’s comments, an X Space, regular calls, or something else entirely. Hopefully, we can start building this little corner of the Flutterverse together. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2590acc0de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing State with Bloc in a Full Stack Flutter/Serverpod App]]></title>
            <link>https://medium.com/@ben.auer.dev/managing-state-with-bloc-in-a-full-stack-flutter-serverpod-app-a403239ad301?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/a403239ad301</guid>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bloc]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 11:20:32 GMT</pubDate>
            <atom:updated>2024-07-04T11:20:32.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eAd-IaUeapXzDtmdutCnAQ.png" /><figcaption>Serverpod Banner Image</figcaption></figure><h4>With demo project</h4><h4>Prequesites</h4><p>This article is based on my talk at the <a href="https://flutternl.org/#/">Flutter Holland</a> Meetup in Amsterdam on June 27th, about managing state within a Serverpod project with Bloc. The reason why I used Bloc is, that 70% of my audience are using it.</p><p>In case you want to use Riverpod, I already published an article on that, you can find it <a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">here</a>.</p><h4>Intro</h4><p>When building an app it is good practice to use a State management solution. For many reasons but first and foremost to separate concerns, modularity and maintainability.</p><p>I created a small <strong>demo app</strong>: “Lunch Spots” that allows users to propose lunch spots to order food from and then vote on them. You can <a href="https://github.com/BenAuerDev/bloc_demo">clone it from GitHub.</a></p><p>I’m not going to cover how a project is created and authentication is set up as it is well documented and doesn’t take longer than 15 minutes. Make sure you also have integrated a provider. I’m using <a href="https://docs.serverpod.dev/concepts/authentication/providers/email">Email (Provider)</a>.</p><h4>First things first</h4><p>Before we get into the whole thing, let’s talk about the two main objects we’re going to interact with.</p><ol><li>Client — is a Singleton object generated from the server code and it is used to communicate with the server. But it’s gonna feel like you’re calling a local method.</li></ol><pre>Client(<br>  &quot;http://localhost:8080/&quot;,<br>  authenticationKeyManager: FlutterAuthenticationKeyManager(),<br>)..connectivityMonitor = FlutterConnectivityMonitor();</pre><p>2. SessionManager — Is used to manage a users credentials. When initialized it attempts to fetch the user information from the server and the locally stored key. If this fails it returns false.</p><pre>SessionManager(<br>  caller: client.modules.auth,<br>);<br><br>await sessionManager.initialize();</pre><p>That’s pretty much it. That is all you need to know in the frontend.</p><p>Let’s start by giving the user the option to sing in and handle the authentication state with a Cubit.</p><h4>Handling authentication state changes</h4><p>To do this I created is_authenticated.dart</p><pre>// bloc_demo/bloc_demo_flutter/lib/src/features/auth/application/is_authenticated.dart<br><br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>import &#39;package:bloc_demo_flutter/main.dart&#39;;<br><br>/// This cubit is used to keep track of the authentication state of the user.<br>/// It listens to the [sessionManager] and emits a new state whenever the<br>/// authentication state changes.<br>class IsAuthenticatedCubit extends Cubit&lt;bool&gt; {<br>  IsAuthenticatedCubit() : super(sessionManager.isSignedIn) {<br>    sessionManager.addListener(() {<br>      emit(sessionManager.isSignedIn);<br>    });<br>  }<br>}</pre><p>With this we now don’t need a StatefulWidget to re-render whenever the auth state changes.</p><p>So our app widget looks like</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Serverpod Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: BlocProvider&lt;IsAuthenticatedCubit&gt;(<br>        create: (_) =&gt; IsAuthenticatedCubit(),<br>        child: BlocBuilder&lt;IsAuthenticatedCubit, bool&gt;(<br>          builder: (context, state) {<br>            return state ? const HomeScreen() : const AuthScreen();<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>And our two screens look like:</p><pre>class AuthScreen extends StatelessWidget {<br>  const AuthScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: SignInWithEmailButton(<br>          caller: client.modules.auth,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre><br>class HomeScreen extends StatelessWidget {<br>  const HomeScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: ElevatedButton(<br>        onPressed: () =&gt; sessionManager.signOut(),<br>        child: const Text(&#39;Sign out&#39;),<br>    )<br>  }<br>}</pre><p>Easy right? Within a few lines of code we managed to create a Full Stack app with an elegant authentication workflow.</p><p>Let’s have a look at writing some server code</p><h4>Models</h4><p>We need a model, which we define in the server directory in lib/src/models/lunch_spot.spy.yaml. (.spy stands for ServerPodYaml).</p><pre>class: LunchSpot<br>table: lunch_spot<br>fields:<br>  name: String<br>  category: LunchSpotCategory<br>  votes: int</pre><p>For every class defined in a .spy.yaml file serverpod generates a data-class. When the table field is also passed it creates a database table that can be accessed via ORM.</p><p>The category is LunchSpotCategory which is an enum we define the same way:</p><pre>enum: LunchSpotCategory<br>serialized: byName<br>values:<br>    - burgers<br>    - pizza<br>    - sushi<br>    - tacos<br>    - thai<br>    - vegan<br>    - vegetarian</pre><p>With this we can use LunchSpotCategory both on the server and in our Flutter app.</p><h4>Endpoint</h4><p>Next we need an Endpoint. But also this is very easy:</p><pre>class LunchSpotEndpoint extends Endpoint {<br>  Future&lt;LunchSpot&gt; proposeLunchSpot(Session session, LunchSpot spot) async {<br>    return await LunchSpot.db.insertRow(session, spot);<br>  }<br><br>  Future&lt;List&lt;LunchSpot&gt;&gt; getLunchSpots(Session session) async {<br>    return await LunchSpot.db.find(session);<br>  }<br><br>  Future&lt;void&gt; voteForLunchSpot(Session session, int spotId) async {<br>    final spot = await LunchSpot.db.findById(session, spotId);<br><br>    LunchSpot.db.updateRow(session, spot!.copyWith(votes: spot.votes + 1));<br>  }<br>}</pre><p>While you don’t need to add the Endpoint suffix, it is considered best practice and the generator will remove it anyway when creating the client code.</p><h4>State</h4><p>In our Flutter app we declare a LunchSpotState:</p><pre>import &#39;package:meta/meta.dart&#39;;<br><br>import &#39;package:bloc_demo_client/bloc_demo_client.dart&#39;;<br><br>@immutable<br>abstract class LunchSpotState {}<br><br>class LunchSpotInitial extends LunchSpotState {}<br><br>class LunchSpotLoaded extends LunchSpotState {<br>  final List&lt;LunchSpot&gt; spots;<br><br>  LunchSpotLoaded({required this.spots});<br>}<br><br>class LunchSpotError extends LunchSpotState {<br>  final String message;<br><br>  LunchSpotError({required this.message});<br>}</pre><p>And handle all operations through a LunchSpotCubit.</p><pre>import &#39;package:bloc_demo_client/bloc_demo_client.dart&#39;;<br>import &#39;package:bloc_demo_flutter/src/features/lunch_spots/domain/lunch_spot_state.dart&#39;;<br>import &#39;package:bloc_demo_flutter/main.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>class LunchSpotCubit extends Cubit&lt;LunchSpotState&gt; {<br>  LunchSpotCubit() : super(LunchSpotInitial()) {<br>    getLunchSpots();<br>  }<br><br>  List&lt;LunchSpot&gt; _spots = [];<br><br>  Future&lt;void&gt; proposeLunchSpot(LunchSpot spot) async {<br>    final newSpot = await client.lunchSpot.proposeLunchSpot(spot);<br>    _spots.add(newSpot);<br>    emit(<br>      LunchSpotLoaded(<br>        spots: List.from(_spots),<br>      ),<br>    );<br>  }<br><br>  Future&lt;void&gt; getLunchSpots() async {<br>    _spots = await client.lunchSpot.getLunchSpots();<br>    emit(<br>      LunchSpotLoaded(<br>        spots: List.from(_spots),<br>      ),<br>    );<br>  }<br><br>  Future&lt;void&gt; voteForLunchSpot(int spotId) async {<br>    await client.lunchSpot.voteForLunchSpot(spotId);<br>    final updatedSpots = _spots.map((spot) {<br>      if (spot.id == spotId) {<br>        return spot.copyWith(votes: spot.votes + 1);<br>      } else {<br>        return spot;<br>      }<br>    }).toList();<br>    _spots = updatedSpots;<br>    emit(<br>      LunchSpotLoaded(<br>        spots: List.from(_spots),<br>      ),<br>    );<br>  }<br>}</pre><p>Of course this could be refined with try/catch and emitting LunchSpotError. But for simplicity sake I keep it to the essentials I need to demonstrate the functionality.</p><h4>Presentation Layer</h4><p>In our presentation-layer we can now access our LunchSpotCubit within a BlocBuilder.</p><pre>BlocBuilder&lt;LunchSpotCubit, LunchSpotState&gt;(<br>  builder: (context, state) {<br>    if (state is LunchSpotInitial) {<br>      // Empty State<br>      return const Center(child: Text(&#39;No spots proposed yet.&#39;));<br>    } else if (state is LunchSpotLoaded) {<br>      // Loaded State<br>      return ListView.builder(<br>        itemCount: state.spots.length,<br>        itemBuilder: (context, index) {<br>          final spot = state.spots[index];<br>          return ListTile(<br>            subtitle: Text(&#39;Votes: ${spot.votes}&#39;),<br>            title: Row(<br>              mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>              children: [<br>                Text(spot.name),<br>                Text(&#39;Category: ${spot.category}&#39;),<br>              ],<br>            ),<br>            trailing: IconButton(<br>              icon: const Icon(Icons.thumb_up),<br>              onPressed: () {<br>                context<br>                    .read&lt;LunchSpotCubit&gt;()<br>                    .voteForLunchSpot(spot.id!);<br>              },<br>            ),<br>          );<br>        },<br>      );<br>    } else if (state is LunchSpotError) {<br>      // Error State<br>      return Center(child: Text(&#39;Error: ${state.message}&#39;));<br>    }<br>    <br>  },<br>),</pre><p>And we propose a LunchSpot like so:</p><pre>ElevatedButton(<br>  onPressed: () {<br>    context.read&lt;LunchSpotCubit&gt;().proposeLunchSpot(<br>          LunchSpot(<br>            name: nameController.text,<br>            votes: 0,<br>            category: selectedCategoryNotifier.value!,<br>          ),<br>        );<br>    nameController.clear();<br>  },<br>  child: const Text(&#39;Propose&#39;),<br>)</pre><p>That’s it.</p><h4>Conclusion</h4><p>While it is not strictly necessary to use a state management solution within a Serverpod project it helps to enhance readability and maintainability even more by avoiding StatefulWidgets wherever possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a403239ad301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 6: How I deployed Serverpod to a VPS]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-6-how-i-deployed-serverpod-to-a-vps-cad6a9f6c1df?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad6a9f6c1df</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Mon, 13 May 2024 17:45:55 GMT</pubDate>
            <atom:updated>2024-08-28T07:26:55.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-7XTNNtdImBQVDka" /><figcaption>Photo by <a href="https://unsplash.com/@kelvin1987?utm_source=medium&amp;utm_medium=referral">Kelvin Ang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Using GitHub Actions, Docker and Traefik</h4><h4>Intro</h4><p>As Flashlist hits its MVP stage, it’s time to deploy it to a virtual private server and put it to the test. I found a <a href="https://medium.com/@markus_32812/host-serverpod-on-your-vps-with-ci-cd-6e1c56eaa027">very helpful tutorial</a> but ended up changing a few things. But make sure to also read the linked article above and if you have some claps to give, please leave them there as the dude has done pretty much all of the heavy lifting.</p><p>Also, if you spot anything I should reconsider, I’d appreciate it if you’d drop me a comment or holla at me on <a href="https://twitter.com/BenAuerDev">Twitter/X</a><em>.</em></p><p>In case you’re new to this series and want to catch up you can do that here:</p><ol><li><a href="https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f">Flashlists Journey with Cutting Edge Technology</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d">Flashlist PART 2: Let there be Users</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-3-implementing-the-crud-stream-664142cdbf51">Flashlist PART 3: Implementing the CRUD-Stream</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-4-mind-your-context-sensitivity-8c15f3d06826">Flashlist PART 4: Mind your Context Sensitivity</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-5-demystifying-false-positive-app-flags-4a5632886ffb">Flashlist PART 5: Handling False Positive Flags from AntiVirus Software</a></li></ol><p>Otherwise, just jump into it!</p><h4>Project</h4><p>I organize my project in a single repository, meaning that the .github directory is a sibling of flashlist_server.</p><pre>flashlist/<br>├── .github/<br>├── flashlist_client/<br>├── flashlist_flutter/<br>└── flashlist_server/</pre><h4>GitHub Actions</h4><p>To automate the process of building and publishing Docker images, we leverage GitHub Actions. This workflow is triggered after each push to the main branch of our repository.</p><p>Begin by creating a YAML file named build-and-publish.yaml within the .github/workflows directory.</p><pre>name: Create and publish a Docker image<br><br>on:<br>  push:<br>    branches: [&#39;main&#39;]<br><br>env:<br>  REGISTRY: ghcr.io<br>  IMAGE_NAME: ${{ github.repository }}<br><br>jobs:<br>  build-and-push-image:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: read<br>      packages: write<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br><br>      - name: Run Workflow<br>        id: write_file<br>        uses: timheuer/base64-to-file@v1.2<br>        with:<br>          fileName: &#39;passwords.yaml&#39;<br>          fileDir: &#39;./flashlist_server/config/&#39;<br>          encodedString: ${{ secrets.BASE64_PASSWORDS }}<br><br>      - name: Log in to the Container registry<br>        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9<br>        with:<br>          registry: ${{ env.REGISTRY }}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br><br>      - name: Extract metadata (tags, labels) for Docker<br>        id: meta<br>        uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}<br><br>      - name: Build and push Docker image<br>        uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc<br>        with:<br>          platforms: linux/amd64<br>          context: .<br>          file: ./flashlist_server/Dockerfile<br>          push: true<br>          tags:<br>            ghcr.io/benauerdev/flashlist:latest<br>          labels: ${{ steps.meta.outputs.labels }}</pre><p>Next, we create a GitHub Action Secret to securely store our passwords in base64 format. This step ensures that sensitive information, such as database passwords, is securely managed within our workflow.</p><p>To obtain the passwords in base64 format, we navigate to the flashlist_server/config directory of your project. From there, execute the following command:</p><pre>base64 -i passwords.yaml</pre><p>This will encode the contents of passwords.yaml into base64 format and print it in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oU-dJUl4xsPcsuRO8xEiiw.png" /></figure><p>Navigate to Settings &gt; Actions and click on “New repository secret” as shown above and copy the base64 encoded string from the terminal into the text field.</p><p>I called it “BASE64_PASSWORDS”. If you choose a different name, remember to update line 27 of the build-and-publish.yaml file accordingly.</p><h4>Dockerfile</h4><p>The Dockerfile instructs the GitHub workflow on how to build an image of our server application.</p><pre># Stage 1: Build the server application<br>FROM --platform=$BUILDPLATFORM dart:3.2.5 AS build<br><br># Resolve app dependencies.<br>WORKDIR /app<br>COPY flashlist_server /app<br><br>RUN dart pub get<br>RUN dart compile exe bin/main.dart -o bin/main<br><br># Stage 2: Create the final Docker image<br>FROM debian:buster-slim<br><br># Set environment variables<br>ENV runmode=production<br>ENV serverid=default<br>ENV logging=normal<br>ENV role=monolith<br><br># Copy the built artifacts from the previous stage<br>COPY --from=build /runtime/ /app/<br>COPY --from=build /app/bin/main /app/bin/main<br>COPY --from=build /app/config/ config/<br>COPY --from=build /app/web/ web/<br>COPY --from=build /app/migrations/ migrations/<br><br># Copy passwords file<br>COPY ./flashlist_server/config/passwords.yaml /app/config/passwords.yaml<br><br># Expose ports<br>EXPOSE 8080<br>EXPOSE 8081<br>EXPOSE 8082<br><br># Define the command to run the server application<br>CMD app/bin/main --mode $runmode --server-id $serverid --logging $logging --role $role --apply-migrations</pre><p>Note: Currently, the Dockerfile automatically applies migrations if they exist in the last line. If you intend to handle migrations differently, such as using a separate migration script or tool, you’ll need to remove --apply-migrations from the last line of the Dockerfile.</p><h4>Production Config Update</h4><p>In the flashlist_server/config/production.yaml file, adjust the publicHost values to match your own DNS configuration. This step ensures that your server endpoints are accessible via the correct host names.</p><pre># Configuration for the main API server.<br>apiServer:<br>  port: 8080<br>  publicHost: api.flashlistapp.com<br>  publicPort: 443<br>  publicScheme: https<br><br># Configuration for the Insights server.<br>insightsServer:<br>  port: 8081<br>  publicHost: insights.flashlistapp.com<br>  publicPort: 443<br>  publicScheme: https<br><br># Configuration for the web server.<br>webServer:<br>  port: 8082<br>  publicHost: app.flashlistapp.com<br>  publicPort: 443<br>  publicScheme: https</pre><p>If you push your changes and the workflow runs without an error, you should see this on your repository overview page’s right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*xOb0lHGSNAqPtYUyLR48gQ.png" /></figure><p>And when clicking on your package you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*eeGsgVOPQGUiXa8ugaWNKw.png" /></figure><p>The important part is “docker pull ghcr.io/benauerdev/flashlist:latest” with this command we can now pull an image of our server-app to our VPS.</p><h4>Configuring the VPS</h4><p>Begin by logging into your server via SSH. Once logged in, create an .env file and open it using the nano editor with the following command:</p><pre>nano .env</pre><p>This command opens the nano text editor within your terminal. There you add the environment variables required for your application like so:</p><pre>POSTGRES_PASSWORD=YOUR_POSTGRES_PASSWORD<br>REDIS_PASSWORD=YOUR_REDIS_PASSWORD<br>TRAEFIK_EMAIL=YOUR_EMAIL</pre><p>Replace YOUR_POSTGRES_PASSWORD, YOUR_REDIS_PASSWORD, and YOUR_EMAIL with the appropriate values for your PostgreSQL password, Redis password, and email, respectively.</p><h4>Docker-Compose yaml</h4><p>The Docker Compose file defines the configuration for deploying your services on the VPS. Ensure to customize the file as needed. Here’s the Docker Compose configuration:</p><pre>version: &#39;3&#39;<br>services:<br>  postgresql:<br>    image: postgres<br>    volumes:<br>      - /data/postgres:/var/lib/postgresql/data<br>      - /data/postgres:/data/postgres<br>    environment:<br>      - POSTGRES_DB=serverpod<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}<br>      - PGDATA=/data/postgres<br>    networks:<br>      - web<br><br>  redis:<br>    image: redis:6.2.6<br>    command: redis-server --requirepass ${REDIS_PASSWORD}<br>    environment:<br>      - REDIS_REPLICATION_MODE=master<br>    volumes:<br>      - /data/redis:/redis/data<br><br>    networks:<br>      - web<br><br>  flashlist-api:<br>    image: ghcr.io/benauerdev/flashlist:latest<br>    container_name: flashlist-api<br>    restart: always<br>    security_opt:<br>      - no-new-privileges:true<br>    networks:<br>      - web<br>    labels:<br>      - &quot;traefik.enable=true&quot;<br><br>      # For API<br>      - &quot;traefik.http.routers.myapi.entrypoints=websecure&quot;<br>      - &quot;traefik.http.routers.myapi.rule=Host(`api.flashlistapp.com`)&quot;<br>      - &quot;traefik.http.routers.myapi.tls=true&quot;<br>      - &quot;traefik.http.routers.myapi.tls.certresolver=myresolver&quot;<br>      - &quot;traefik.http.services.myapi.loadbalancer.server.port=8080&quot;<br><br>      # For Insights<br>      - &quot;traefik.http.routers.myapi.entrypoints=websecure&quot;<br>      - &quot;traefik.http.routers.myapi.rule=Host(`insights.flashlistapp.com`)&quot;<br>      - &quot;traefik.http.routers.myapi.tls=true&quot;<br>      - &quot;traefik.http.routers.myapi.tls.certresolver=myresolver&quot;<br>      - &quot;traefik.http.services.myapi.loadbalancer.server.port=8081&quot;<br><br>      # For Webserver<br>      - &quot;traefik.http.routers.myapi.entrypoints=websecure&quot;<br>      - &quot;traefik.http.routers.myapi.rule=Host(`app.flashlistapp.com`)&quot;<br>      - &quot;traefik.http.routers.myapi.tls=true&quot;<br>      - &quot;traefik.http.routers.myapi.tls.certresolver=myresolver&quot;<br>      - &quot;traefik.http.services.myapi.loadbalancer.server.port=8082&quot;<br><br>  traefik:<br>    image: &quot;traefik:v2.5&quot;<br>    container_name: &quot;traefik&quot;<br>    command:<br>      - &quot;--log.level=DEBUG&quot;<br>      - &quot;--providers.docker=true&quot;<br>      - &quot;--providers.docker.exposedbydefault=true&quot;<br>      - &quot;--entrypoints.web.address=:80&quot;<br>      - &quot;--entrypoints.websecure.address=:443&quot;<br>      - &quot;--certificatesresolvers.myresolver.acme.httpchallenge=true&quot;<br>      - &quot;--certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web&quot;<br>      # uncomment this line to test ssl generation first<br>      # - &quot;--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory&quot; <br>      - &quot;--certificatesresolvers.myresolver.acme.email=${TRAEFIK_EMAIL}&quot;<br>      - &quot;--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json&quot;<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - &quot;/var/run/docker.sock:/var/run/docker.sock:ro&quot;<br>      - &quot;./letsencrypt:/letsencrypt&quot;<br>    networks:<br>      - web<br><br>networks:<br>  web:<br>    external: true</pre><p><strong>Note:</strong> Within the Traefik configuration in the Docker Compose file (docker-compose.yaml), there&#39;s a line commented out that relates to the Let&#39;s Encrypt staging environment for certificate generation:</p><p>Uncommenting the specified line enables the use of Let’s Encrypt’s staging environment, ideal for testing purposes. It allows you to generate test certificates without hitting production rate limits. Once testing is complete, comment out the line to switch to Let’s Encrypt’s production environment for real certificates.</p><h4>Create external network</h4><p>For our Docker Services and Traefik to be able to communicate we need to create an external network.</p><pre>docker network create web</pre><p>Also pull your docker image by running the ghcr pull command:</p><pre>docker pull ghcr.io/benauerdev/flashlist:latest</pre><p>With this in place you now run</p><pre>docker compose up -d</pre><p>To ensure that your containers stay up-to-date with the latest versions, you can use Watchtower. Run the following command to start Watchtower:</p><pre>docker run -d - name watchtower -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower</pre><h4>Set up Flutter app</h4><p>In your flutter app all you need to change is the address your client targets:</p><pre>Client(<br>  &quot;https://api.flashlistapp.com/&quot;,<br>  authenticationKeyManager: FlutterAuthenticationKeyManager(),<br>)..connectivityMonitor = FlutterConnectivityMonitor();</pre><h4>Conclusion</h4><p>Congratulations! Now you have a GitHub Actions workflow that builds a docker image after a push to your repository. You can pull it to your server by running the docker pullcommand and deploy it using docker-compose up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad6a9f6c1df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 5: Handling False Positive Flags from AntiVirus Software]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-5-demystifying-false-positive-app-flags-4a5632886ffb?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5632886ffb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 16:55:48 GMT</pubDate>
            <atom:updated>2024-04-30T13:06:38.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nHYfp3Zm-_hh_qsH" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A quick and easy way to identify and resolve a False Positive on your app file</h4><h4>Intro</h4><p>Welcome back, Code Ninjas! Today, we’re taking a slight detour from our usual coding adventures to delve into a topic that often lurks in the shadows of app development. While we love crafting beautiful apps with Dart, Flutter, and Serverpod, let’s shine a light on something equally important but less glamorous: navigating the realm of false positive virus flags.</p><p>In case you’re just joining us on this journey, feel free to catch up on what we’ve covered so far in this series:</p><ol><li><a href="https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f">Flashlists Journey with Cutting Edge Technology</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d">Flashlist PART 2: Let there be Users</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-3-implementing-the-crud-stream-664142cdbf51">Flashlist PART 3: Implementing the CRUD-Stream</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-4-mind-your-context-sensitivity-8c15f3d06826">Flashlist PART 4: Mind your Context Sensitivity</a></li></ol><p>But hey, if you’ve landed here straight from Google because your app got flagged and you couldn’t care less about any of that, don’t worry — I’ve got you covered!</p><h4>What might be ailing you</h4><p>So you’re probably here because you uploaded an .<strong>apk</strong> or .<strong>ios</strong> file to your google drive, dropbox or iCloud that you can’t download and/or you got an email telling you that your file violates the <strong>malware guidelines</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6EhKn9VGku2R2Gsg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fgame-of-thrones-3o6EhKn9VGku2R2Gsg&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYWdiYTd3cGwyaWl1YmtueHFkZHR5ZWMxc243cG1zang3YTAzZ2x4OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o6EhKn9VGku2R2Gsg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/90f04d082176fce41d43e99457e70df9/href">https://medium.com/media/90f04d082176fce41d43e99457e70df9/href</a></iframe><p>In this case, I’m really sorry to hear that, mate. Been there, done that!</p><h4>Why the flag?</h4><p>When you upload a file to any cloud service worth its money, your file undergoes a <strong>series of scans</strong> conducted by security software provided by various companies. These scans are designed to ensure the safety of the files before they are made available for download. However, sometimes a coding pattern used in the app can trigger a false alarm. In my case, it was the custom Sliding Panel I built for the Edit Mode of Flashlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*2WlnvbWCbDfNVPMxyH1o7A.gif" /></figure><p>Don’t worry; I’m still going to tell you how I came to know that and how I resolved that issue. I’m just letting you know, to kill any suspense that might have built up during the read… this is a tech-blog, not a murder mystery. Except the question is: “Who killed Ben’s weekend by unnecessarily investigating code that’s fine?” Well, the answer is himself…</p><p>To save you some time, I’m only going to share the steps that actually helped solve this.</p><h4>Scan</h4><p>If you haven’t already, use <a href="https://www.virustotal.com/">VirusTotal</a> or <a href="https://metadefender.opswat.com/">MetaDefender</a> to scan your file. This will confirm the flag and also show you the company whose algorithm applied it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XLQsI_MTPbzrfzU5aCmDw.png" /></figure><p>Another scan (that I have no screenshot of) also returned the following <strong>“Trojan.AndroidOS.Agent”</strong>. That information wasn’t much to go on either but sounded quite disturbing when I said it aloud for the first time.</p><h4>Travel back in time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*ZKmzUvY0ntMwF5cN35lAbw.png" /></figure><p>To pinpoint when the issue first appeared, you can follow these steps:</p><ol><li>Create a branch from a commit further back.</li><li>Run dart pub get to ensure all dependencies are up to date.</li><li>Build the app using flutter build for either APK or iOS.</li><li>Scan the generated file with VirusTotal or MetaDefender.</li></ol><p><strong>Note: Even if you would encounter difficulties running the app due to breaking changes between commits or other factors, you can still proceed with the scanning process.</strong></p><p>Repeat this until you have a build that is not flagged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*GjamEAhbZqUXhTK5Eux-Iw.png" /></figure><p>From this point on you can go further ahead until the app is flagged again, but don’t worry this time you’ll be like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FHgIGe1b8O8prK72g5B%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcomspace-reaction-villain-sharky-HgIGe1b8O8prK72g5B&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdGI0dnNzaHJmaHFqcTJpd3NpMnh4ZmJjNnk0M3p0cmViYWN5aTludCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FHgIGe1b8O8prK72g5B%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/159f18983c8d684b13cb3e78c416fa19/href">https://medium.com/media/159f18983c8d684b13cb3e78c416fa19/href</a></iframe><p>(I have the same shark on my sofa ❤)</p><p>Now, you can examine the code introduced in the commit that reintroduced the flag. While I can’t predict the specifics of your case, I’m confident that you now have the knowledge to investigate further on your own.</p><p>In my case it was <a href="https://github.com/BenAuerDev/flashlist/commit/b8de9a35fb74adcbe39bf435d88df55776a0765b">this commit</a> which is not the cleanest but pretty straight forward in what code triggered the alarm as it only introduces the EditModeOverlay.</p><p>This ensured me that it was a false-positive, which brings me to the last step.</p><h4>Let them know</h4><p>As the scan of your file shows you which company provides the software that flagged your app, simply google for information on how their process for false-positive works or call them. In my case it was Ikarus which was funny because it’s an Austrian company (and I’m an Austrian Developer living abroad).</p><p>So what everything came down to was me having a nice chat in my native language where they explained to me that I can just send them an email to ask for an evaluation. Which i immediately did.</p><p>Within less than 24 hours, I received an automatically generated email confirming the false positive. It also assured me that after the next database update, my file would no longer be flagged.</p><p>I scanned the file again a few days later and everything was normal.</p><h4>Conclusion</h4><p>When writing custom solutions with a bold approach, unexpected challenges like a virus flag can pop up. While it’s not the most enjoyable experience, it’s all part of the game when you’re pushing boundaries. So, don’t let it get you down. Keep pushing forward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5632886ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 4: Mind your Context Sensitivity]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-4-mind-your-context-sensitivity-8c15f3d06826?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c15f3d06826</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 11:25:30 GMT</pubDate>
            <atom:updated>2024-04-01T14:44:12.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Jopgi8EWnCMgVtp" /><figcaption>Photo by <a href="https://unsplash.com/@robinne?utm_source=medium&amp;utm_medium=referral">Robs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Enabling Real-Time Collaboration with Serverpod and Riverpod</h4><h4>Intro</h4><p>Now that we’ve established a system where CRUD operations are seamlessly updated via stream, it’s time to explore how users can grant access to this stream to other users. Our stream is already built to update data for multiple users, so let’s see how we can extend this functionality to facilitate collaboration among users.</p><p>But before we dive into that, if you missed last week’s post or want to catch up on what we’ve covered in this series so far, you can click on one of these links:</p><ul><li><a href="https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f">Flashlists Journey with Cutting Edge Technology</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d">Flashlist PART 2: Let there be Users</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-3-implementing-the-crud-stream-664142cdbf51">Flashlist PART 3: Implementing the CRUD-Stream</a></li></ul><p>Okay, everybody who is still here can follow me on today&#39;s quick tour through a simplified version of the Flashlist Stream. No Photos please!</p><h4>The Flashlist Stream</h4><p>In the backend our stream starts when a client connects to it, then the streamOpened method is called.</p><pre>// ..._server/lib/src/endpoints/flashlist_endpoint.dart<br><br>class FlashlistEndpoint extends Endpoint {<br>  // CRUD logic goes before<br><br>  ...<br>  @override<br>  Future&lt;void&gt; streamOpened(StreamingSession session) async {<br>    try {<br>      // get all Flashlists from the database<br>      final flashlistsForUser = await getFlashlistsForUser(session);<br>      <br>      // send list-collection <br>      sendStreamMessage(session, FlashlistBatch(collection: flashlistsForUser));<br><br>      // add a listener to a channel associated with user<br>      session.messages.addListener(&#39;channel-user-${currentUser.id}&#39;, (message) {<br>        sendStreamMessage(session, message);<br>      });<br><br>      // loop over the list of lists and add a listener to a channel per list<br>      for (final flashlist in flashlists) {<br>        session.messages.addListener(&#39;flashlist-channel-${flashlist.id}&#39;,<br>            (message) {<br>          sendStreamMessage(session, message);<br>        });<br>      }<br><br>    } catch (e) {<br>      // throw Exception or just print<br>    } <br>  }<br>...</pre><p>Every message received from the client will call handleStreamMessage:</p><pre>@override<br>Future&lt;void&gt; handleStreamMessage(<br>  StreamingSession session,<br>  SerializableEntity message,<br>) async {<br>  if (message is Flashlist) {<br>    // Use the data-class &quot;Flashlist&quot; to create a db entity<br>    // It&#39;s important to await this db entity and send otherwise the flashlist won&#39;t know it&#39;s ID in the UI<br>    final flashlist = await createFlashlist(session, message);<br><br>    // Send the list via the user channel<br>    session.messages.postMessage(&#39;channel-user-$userId&#39;, flashlist);<br><br>    // Add a listener to this lists channel<br>    session.messages.addListener(&#39;flashlist-channel-$listId&#39;, (message) {<br>      sendStreamMessage(session, message);<br>    });<br>  }<br><br>  if (message is DeleteFlashlist) {<br>    // Delete the flashlist from DB<br>    await flashlistHelper.deleteFlashlist(session, message.flashlistId);<br><br>    // Send the delete-message via list channel<br>    session.messages.postMessage(<br>      &#39;flashlist-channel-$listId&#39;,<br>      message,<br>    );<br><br>    // Remove listener from list channel<br>    session.messages.removeListener(<br>      &#39;flashlist-channel-${message.flashlistId}&#39;,<br>      (message) {<br>        sendStreamMessage(session, message);<br>      },<br>    );<br>   }<br><br>  if (message is UpdateFlashlist) {<br>    // Update DB row<br>    await flashlistHelper.updateFlashlist(session, message);<br><br>    // Send update-message via list channel <br>    session.messages.postMessage(<br>      &#39;flashlist-channel-${message.id},<br>      message,<br>    );<br>  }<br>}</pre><p>And when these messages are sent through either the user- or the list-channel, they have to be applied to the list that the user has checked out on his phone.</p><pre>// ..._flutter/lib/src/endpoints/flashlist_endpoint.dart<br><br>@riverpod<br>Stream&lt;List&lt;Flashlist?&gt;&gt; flashlistsForUser(FlashlistsForUserRef ref) async* {<br>  final client = ref.watch(clientProvider);<br>  <br>  // To ensure a new session<br>  client.flashlist.resetStream();<br><br>  // Triggers `streamOpened`<br>  await client.openStreamingConnection();<br>  <br>  // Close connection when ref is no longer used<br>  ref.onDispose(() async {<br>    await client.closeStreamingConnection();<br>  });<br><br>  var streamItems = &lt;Flashlist&gt;[];<br><br>  // loop over the messages sent via streaming endpoint<br>  await for (final message in client.flashlist.stream) {<br>    // &quot;Unpack&quot; the initial Batch<br>    if (message is FlashlistBatch) {<br>      streamItems = [...message.collection];<br>    }<br><br>    // Add Flashlist when one is sent<br>    if (message is Flashlist) {<br>      streamItems.add(message);<br>    }<br><br>    // Deletes Flashlist when id == message.flashlistId<br>    if (message is DeleteFlashlist) {<br>      streamItems.removeWhere((element) =&gt; element!.id == message.flashlistId);<br>    }<br><br>    // Removes old Item and replaces with new one <br>    if (message is UpdateFlashlist) {<br>      final indexToRemove =<br>          streamItems.indexWhere((element) =&gt; element!.id == message.id);<br>      final itemToRemove = streamItems[indexToRemove];<br>  <br>      streamItems.removeAt(indexToRemove);<br>      streamItems.insert(<br>        indexToRemove,<br>        itemToRemove!.copyWith(<br>          title: message.title,<br>          color: message.color,<br>        ),<br>      );<br>    }<br>    <br>    // Yield streamItems on the end of every iteration<br>    yield streamItems;<br>  }<br>}</pre><p>Of course, this is not everything, as we also handle FlashlistItems and reordering. You can review the code here: <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_server/lib/src/endpoints/flashlist_endpoint.dart">Server</a> and <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_flutter/lib/src/features/flashlist/application/flashlist_stream_message_handler.dart">Flutter</a>.</p><h4>Adding users</h4><p>Flashlist will have two ways of adding a user to a Flashlist:</p><ol><li>Instant join: If users are connected/friends, they can be added via a tap on the connection’s avatar in the share dialog, and the invitee should be added to the list instantly.</li><li>Via email: Similarly to connection requests, a request is added for the invitee and the list, and the invitee will join the list upon confirming the request.</li></ol><p>This means, <strong>when a user connects to the Websocket</strong>:</p><ul><li>We <strong>read the database </strong>and send lists associated with the current user.</li><li>We <strong>attach listeners </strong>to the user- and list channels.</li></ul><p>Now, when a message <strong>arrives from the client</strong> side:</p><ul><li>We process the incoming message and <strong>determine</strong> the corresponding <strong>operation</strong>.</li><li>We <strong>apply</strong> the operation to the <strong>database.</strong></li><li>We send the <strong>message</strong> to the <strong>client</strong>.</li></ul><p>Upon receiving this message on the client, it will update the UI by either adding a Flashlist to the streamItems yielded by our stream or replacing an item by its ID with the newly sent item.</p><p>These operations are the same for every user. However, when a user is added to a list, we are not creating a new list; instead, we are sharing an existing one along with its items and other editors. Additionally, we have to update Flashlist.authors so that existing authors see the new author in their list.</p><p>In technical terms this means we:</p><ul><li>Create a <strong>new FlashlistPermission</strong> for the invitee and the list</li><li>Post the <strong>message</strong> to the channel associated with the <strong>list</strong></li></ul><p>Moreover, this ensures that when the invitee opens a new session, the list will be included in the initial FlashlistBatch, allowing for seamless integration into their user experience. Additionally, all users subscribed to the list-channel will receive a real-time update of a new co-author being added to the list.</p><p>BUT in the case of our main Invitation method (instant-join) we are sending the message to add the invitee from the inviters client. Meaning we can’t access the invitees session in handleStreamMessage.</p><p>Or Can we? Spoiler alert: yeah we can. While searching on google and harassing every AI that wants to talk to me, I got a few suggestions like using the Dio http client to send a HTTP request to the same endpoint checking if the invitee has an active session. This might definitely work but in my opinion that’s more of a hack than clean streaming workflow.</p><p>So, I decided to take a different approach: Splitting the process into two events and sending the event JoinFlashlist when handling AddUserToFlashlist on the server.</p><p>And here is how that looks in code:</p><pre>if (message is AddUserToFlashlist) {<br>  // Create new permission<br>  await flashlistPermissionHelper.createFlashlistPermission(<br>    session,<br>    message.flashlistId,<br>    message.user.id!,<br>    message.accessLevel,<br>  );<br><br>  // Post add-user to the list-channel<br>  session.messages.postMessage(<br>    &#39;flashlist-channel-${message.flashlistId}&#39;,<br>    message,<br>  );<br><br>  // posts JoinFlashlist-Event to the invitees user channel<br>  session.messages.postMessage(<br>    &#39;channel-user-${message.user.id!}&#39;,<br>    JoinFlashlist(<br>      user: message.user,<br>      flashlistId: message.flashlistId,<br>      accessLevel: message.accessLevel,<br>    ),<br>  );<br>}<br><br><br>if (message is JoinFlashlist) {<br>  // Retrieves the flashlist with items and co-authors<br>  final flashlist = await flashlistHelper.getFlashlistByIdWithAttachments(<br>    session,<br>    message.flashlistId,<br>  );<br><br>  // Posts the list to the user-channel<br>  session.messages.postMessage(<br>    &#39;channel-user-${message.user.id!}&#39;,<br>    flashlist!,<br>  );<br><br>  // And as this is the invitees session we add a listener to the list-channel<br>  session.messages.addListener(<br>    &#39;flashlist-channel-${message.flashlistId}&#39;,<br>    (message) {<br>      sendStreamMessage(session, message);<br>    },<br>  );<br>}</pre><p>And to make this work in our messageStreamHandler, we need:</p><pre>// Sent to everybody that listens to the list-channel<br>if (message is AddUserToFlashlist) {<br>  // Get list<br>  final flashlistToUpdate =<br>      getFlashlistByFromStream(streamItems, message.flashlistId);<br><br>  // Add user to Flashlist.authors <br>  if (flashlistToUpdate!.authors == null) {<br>    flashlistToUpdate.authors = &lt;AppUser&gt;[message.user];<br>  } else {<br>    flashlistToUpdate.authors?.add(message.user);<br>  }<br>}<br><br>// Only posted to the invitees channel<br>if (message is JoinFlashlist) {<br>  final client = ref.read(clientProvider);<br><br>  // Sends the JoinFlashlist event back to the server <br>  // IF the invitee has an active session<br>  client.flashlist.sendStreamMessage(message);<br>}<br></pre><p>In short: AddUserToFlashlist adds permission, informs co-authors of new editor and sends a JoinFlashlist message to the invitees user-channel to be bounced back to the server.</p><p>If no message is received or bounced back, it indicates that the user has no active session. In this case, the next time the user connects to the WebSocket, the streamOpened function will read the new permission and add a listener accordingly.</p><p>However, if the message is sent back, it means that the invitee has an active session. In this scenario, we access the invitee’s session in our message handler for JoinFlashlist and attach a listener. This ensures that the invitee’s UI is updated promptly whenever changes are made to the list.</p><p>And this is how it looks when compiled:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F929480968%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F929480968&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1825545974-791a548d696cf6a0a24915f3a7a22022837b11bfe928a38ce76a6c47273923b2-d_640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="864" height="630" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f2c641e09ef69f1db5545a616ddc74/href">https://medium.com/media/e4f2c641e09ef69f1db5545a616ddc74/href</a></iframe><h4>Removing users</h4><p>Like mentioned in the intro, a user should also have the option to leave a list or be removed from it. This is where it becomes a little bit tricky. I tried an approach comparable to the others, in which I send an event to the user that is to be removed, removing the list from his streamItems, and an event to remove a user. This worked fine until the user was invited a second time within the same session, which broke the app on the invitee’s side. This is why I decided that when a user leaves, I reset the stream and invalidate its reference. This still allows for seamless updates on the user’s side but guarantees that the departing user does not receive any messages that could break the app on his side.</p><p>Here is how it looks like in code:</p><pre>if (message is RemoveUserFromFlashlist) {<br>  // Delete list permission<br>  await flashlistPermissionHelper.deleteFlashlistPermission(<br>    session,<br>    message.flashlistId,<br>    message.userId,<br>  );<br><br>  // Post remove-message to the list-channel<br>  session.messages.postMessage(<br>   &#39;flashlist-channel-${message.flashlistId}&#39;,<br>    message,<br>  );<br><br>  /// When received in the frontend, LeaveFlashlist will reset the stream<br>  /// and invalidate the ref, which will trigger a re-fetch of the flashlists<br>  session.messages.postMessage(<br>    &#39;channel-user-${message.userId}&#39;,<br>    LeaveFlashlist(<br>      flashlistId: message.flashlistId,<br>      userId: message.userId,<br>    ),<br>  );<br>}</pre><p>And in the frontend:</p><pre>if (message is RemoveUserFromFlashlist) {<br>  // Gets list from streamItems<br>  final flashlistToUpdate =<br>      getFlashlistByFromStream(streamItems, message.flashlistId);<br><br>  // Removes the user from Flashlist.authors<br>  flashlistToUpdate?.authors!<br>      .removeWhere((currentAuthor) =&gt; currentAuthor!.id == message.userId);<br>}<br><br>/// [LeaveFlashlist] is a message that is sent to a user that is removed from a list.<br>/// It resets the stream and invalidates the ref.<br>if (message is LeaveFlashlist) {<br>  final client = ref.read(clientProvider);<br><br>  client.flashlist.resetStream();<br><br>  ref.invalidateSelf();<br>}</pre><h4>Conclusion</h4><p>When empowering users to collaborate it is important to understand that an event may need different actions for the involved users based on their roles within the collaboration. Additionally, when users conclude their collaboration on a specific element, it is important to ensure that this does not introduce the potential for unhandled exceptions or other adverse outcomes.</p><p>Thanks for reading my update on Flashlist, Happy remaining Easter holidays and “May the pods have mercy on your code!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c15f3d06826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 3: Implementing the CRUD Stream]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-3-implementing-the-crud-stream-664142cdbf51?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/664142cdbf51</guid>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 09:59:08 GMT</pubDate>
            <atom:updated>2024-05-01T20:25:39.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JOhPja5P2pApllLI" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>8</figcaption></figure><h4>It’s like playing “throw and catch” with Serverpod and Riverpod</h4><h4>Intro</h4><p>With users now able to sign up and connect with each other on Flashlist, our attention turns to enhancing the app’s core functionality. To achieve this, I intend to leverage Websockets to facilitate real-time transfer of lists and their updates, unlocking the full collaborative potential of Flashlist.</p><p>In case you’re new to this series and never heard about Flashlist, no worries basically nobody did XD. But if you’re curious or bored you can catch up here:</p><ol><li><a href="https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f">Flashlists Journey with Cutting Edge Technology</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d">Flashlist PART 2: Let there be users</a></li></ol><p>In this post I’d like to share the way I interpret streaming CRUD operations from Serverpod to Riverpod.</p><p>Serverpod’s WebSocket streaming workflow already functions effectively within a StatefulWidget. However, when integrating Riverpod to cache and optimize functionality, it enables a highly satisfying user experience. Additionally, it promotes clean architecture principles by separating business logic from the presentation layer, thus fostering a very calm developer experience.</p><h4>Define the models</h4><p>To transmit data effectively, we need to define classes that extend SerializableEntity. In our case, the first ones will be:</p><pre>class: Flashlist<br>table: flashlist<br>fields:<br>  title: String<br>  color: String<br>  items: List&lt;FlashlistItem?&gt;?, !persist<br>  authors: List&lt;AppUser?&gt;?, !persist</pre><p>and</p><pre>class: FlashlistItem<br>table: flashlist_item<br>fields:<br>  name: String<br>  parentId: int, relation(parent = flashlist, onUpdate = CASCADE, onDelete = CASCADE)<br>  orderNr: int</pre><p>The use of !persist for items and authors indicates they are separate entities stored independently in the database, only attached before transmission via stream message.</p><h4>StreamMessages</h4><p>To transmit stream messages via WebSocket in Serverpod, our messages also must extend SerializableEntity. The initial message we require is FlashlistBatch, defined as follows:</p><pre>class: FlashlistBatch<br>fields:<br>  collection: List&lt;Flashlist&gt;</pre><p>As we define a class without table we only create a data class extending SerializableEntity that will be sent to the to the client when a streaming session starts. This way, even when there are no lists, we have an item telling the frontend that it is no longer loading.</p><h4>Streaming Endpoint</h4><p>Before delving into streaming capabilities, it’s essential to establish an endpoint with CRUD operations. You can explore my endpoint <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_server/lib/src/endpoints/flashlist_endpoint.dart">here</a>.</p><p>As you might have seen on Serverpod’s documentation it’s streaming workflow works by overriding two methods: streamOpened and handleStreamMessage.</p><pre>// ..._server/lib/src/endpoints/flashlist_endpoint.dart<br><br>class FlashlistEndpoint extends Endpoint {<br>  // CRUD logic goes before<br><br>  ...<br>  @override<br>  Future&lt;void&gt; streamOpened(StreamingSession session) async {<br>    try {<br>      // get all Flashlists from the database<br>      final flashlistsForUser = await getFlashlistsForUser(session);<br>      <br>      // send list-collection <br>      sendStreamMessage(session, FlashlistBatch(collection: flashlistsForUser));<br><br>      // add a listener to a channel associated with user<br>      session.messages.addListener(&#39;channel-user-$userId&#39;, (message) {<br>        sendStreamMessage(session, message);<br>      });<br><br>      // loop over the list of lists and add a listener to a channel per list<br>      for (final flashlist in flashlists) {<br>        session.messages.addListener(&#39;flashlist-channel-$listId&#39;,<br>            (message) {<br>          sendStreamMessage(session, message);<br>        });<br>      }<br><br>    } catch (e) {<br>      // throw Exception or just print<br>    <br>  } <br>}</pre><p>Alright! Now that we’ve covered what to do when the client connects to the stream, we want to handle what should happen when a user sends something: like a Flashlist, commands to update or delete one, or in our case a FlashlistItem which is to be displayed in the body of the Flashlist within the UI.</p><pre>@override<br>Future&lt;void&gt; handleStreamMessage(<br>  StreamingSession session,<br>  SerializableEntity message,<br>) async {<br>  if (message is Flashlist) {<br>    // Use the data-class &quot;Flashlist&quot; to create a db entity<br>    // It&#39;s important to await this db entity and send otherwise the flashlist won&#39;t know it&#39;s ID in the UI<br>    final flashlist = await createFlashlist(session, message);<br><br>    // Send the list via the user channel<br>    session.messages.postMessage(&#39;channel-user-$userId&#39;, flashlist);<br><br>    // Add a listener to this lists channel<br>    session.messages.addListener(&#39;flashlist-channel-$listId&#39;, (message) {<br>      sendStreamMessage(session, message);<br>    });<br>  }<br><br>}</pre><p>Sticking to the metaphor from the start, this the throwing part and now we need to…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVmlVxZnAm7wvm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdog-ball-catch-VmlVxZnAm7wvm&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOXo3cjc5bjgxZzZwb2tvOHI3ZmM2aXE2NzNsaHgxaG9kbTBpd2g0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FVmlVxZnAm7wvm%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/985fd337e59992a3869d07a1082a849a/href">https://medium.com/media/985fd337e59992a3869d07a1082a849a/href</a></iframe><h4>StreamProvider</h4><p>To “catch” our Flashlist and provide it to the Flutter app when loaded, we need a StreamProvider (among other methods, which you can find <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_flutter/lib/src/features/flashlist/application/flashlist_controller.dart">here</a>).</p><pre>// ..._flutter/lib/src/endpoints/flashlist_endpoint.dart<br><br>@riverpod<br>Stream&lt;List&lt;Flashlist?&gt;&gt; flashlistsForUser(FlashlistsForUserRef ref) async* {<br>  final client = ref.watch(clientProvider);<br>  <br>  // To ensure a new session<br>  client.flashlist.resetStream();<br><br>  // Triggers `streamOpened`<br>  await client.openStreamingConnection();<br>  <br>  // Close connection when ref is no longer used<br>  ref.onDispose(() async {<br>    await client.closeStreamingConnection();<br>  });<br><br>  var streamItems = &lt;Flashlist&gt;[];<br><br>  // loop over the messages sent via streaming endpoint<br>  await for (final message in client.flashlist.stream) {<br>    // &quot;Unpack&quot; the initial Batch<br>    if (message is FlashlistBatch) {<br>      streamItems = [...message.collection];<br>    }<br><br>    // Add Flashlist when one is sent<br>    if (message is Flashlist) {<br>      streamItems.add(message);<br>    }<br><br>    yield streamItems;<br>  }<br>}</pre><p>With this logic in place we can use the resulting provider within an AsyncValuein our presentation layer:</p><pre>// Somewhere in your WidgetTree<br><br>ref.watch(flashlistForUserProvider).when(<br>  data: (flashlists) {<br>    <br>    // Handle empty state<br>    if (flashlists.isEmpty) {<br>      return const Center(<br>        child: Text(&#39;No flashlists yet&#39;),<br>      );<br>    }<br>  <br>     <br>    return ListView.builder(<br>      itemCount: flashlists.length,<br>      itemBuilder: (context, index) {<br>        final flashlist = flashlists[index];<br>        return FlashlistCard(<br>          ...<br>        );<br>      },<br>    );<br>  },<br>  loading: () =&gt; const Center(<br>    child: CircularProgressIndicator(),<br>  ),<br>  error: (e, st) =&gt; Center(<br>    child: Text(e.toString()),<br>  ),<br>);</pre><p>This ensures that the UI updates seamlessly when a user creates a Flashlist via client.flashlist.sendStreamMessage(Flashlist(…));, effectively covering the creation and reading aspects of our list management.</p><h4>Update and Delete</h4><p>Utilizing a WebSocket and subscribing to a list enables us to mirror backend operations to our frontend list. When a Flashlist is sent to the client and a user is subscribed to it, the list should consistently reflect any updates, facilitating the management of updates and deletions.</p><p>First we need messages representing update and delete to wrap the data we want to send.</p><pre>class: UpdateFlashlist<br>fields:<br>  id: int<br>  title: String?<br>  color: String?</pre><pre>class: DeleteFlashlist<br>fields: <br>  flashlistId: int</pre><p>And when a user sends one of them to the server, we run the operation on the db, and post the message to the list channel.</p><pre>// ..._flutter/lib/src/endpoints/flashlist_endpoint.dart<br><br>if (message is DeleteFlashlist) {<br>  // Delete Flashlist from db<br>  await deleteFlashlist(session, message.flashlistId);<br>   <br>  // Post message to listChannel<br>  session.messages.postMessage(<br>    &#39;list-channel-${message.flashlistId}&#39;,<br>    message,<br>  );<br><br>  // Unsubscribe listChannel<br>  session.messages.removeListener(<br>    &#39;list-channel-${message.flashlistId}&#39;,<br>    (message) {<br>      sendStreamMessage(session, message);<br>    },<br>  );<br>}<br><br><br><br>if (message is UpdateFlashlist) {<br>  // Update Flashlist<br>  await updateFlashlist(session, message);<br><br>  // Post message to listChannel<br>  session.messages.postMessage(<br>    list-channel-${message.id}&#39;,<br>    message,<br>  );<br>}</pre><p>In our StreamProvider we now add cases handling our message and also change streamItems accordingly.</p><pre>// ..._flutter/lib/src/endpoints/flashlist_endpoint.dart<br><br>...<br>if (message is DeleteFlashlist) {<br>  // Remove list from the <br>  streamItems.removeWhere((element) =&gt; element!.id == message.flashlistId);<br>}<br><br>if (message is UpdateFlashlist) {<br>  // Find item to update/remove<br>  final indexToRemove =<br>      streamItems.indexWhere((element) =&gt; element!.id == message.id);<br>  final itemToRemove = streamItems[indexToRemove];<br>  <br>  // Remove old item <br>  streamItems.removeAt(indexToRemove);<br>  <br>  // Insert updated item ensuring the UI updates<br>  streamItems.insert(<br>    indexToRemove,<br>    itemToRemove!.copyWith(<br>      title: message.title,<br>      color: message.color,<br>    ),<br>  );<br>}<br>...</pre><p>With this implementation, we’ve achieved a functional CRUD Stream that automatically synchronises our UI whenever an item is added, updated, or deleted. By mirroring our database operations to the list on the user’s device, we ensure real-time data updates.</p><p>In case you only have one list, that’s all you need. If you need a list of nested lists like my humble self, you better stay tuned.</p><p>But you should take a short break, while writing this I also got up, stretched my back and made myself this cappuccino.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8JL0DA0fq3tDk_VcYNoRw.jpeg" /></figure><h4>FlashlistItem</h4><p>The FlashlistItem has a field parentId which makes it easy for us to retrieve a List’s items by its ID,</p><pre>/// Returns all items where [parentId] == [flashlistId].<br>/// Also sorts them<br>Future&lt;List&lt;FlashlistItem?&gt;&gt; getFlashlistItemsByFlashlistId(<br>  Session session,<br>  int flashlistId,<br>) async {<br>  final items = await FlashlistItem.db.find(<br>    session,<br>    where: (currentItem) =&gt; currentItem.parentId.equals(flashlistId),<br>  );<br><br>  if (items.isNotEmpty) {<br>    items.sort((a, b) =&gt; a.orderNr.compareTo(b.orderNr));<br>  }<br>  return items;<br>}</pre><p>and also catch the Event in the Frontend and update the List our subscribed user checked out when the Session started or he added the list.</p><pre> /// FlashlistItem is a message that contains a single [FlashlistItem] entity.<br>if (message is FlashlistItem) {<br>  final flashlistToUpdate = streamItems.firstWhere((streamItem) =&gt; streamItem!.id == flashlistId);<br><br>  if (flashlistToUpdate!.items == null) {<br>    flashlistToUpdate.items = &lt;FlashlistItem&gt;[message];<br>  } else {<br>    flashlistToUpdate.items!.add(message);<br>  }<br>}</pre><p>Of course we also need messages representing at least the deletion of a FlashlistItem which you can find here: <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_flutter/lib/src/features/flashlist/application/flashlist_stream_message_handler.dart">frontend</a> and <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_server/lib/src/endpoints/flashlist_endpoint.dart">backend</a></p><p>And for good measure I want to add the option to reorder them…</p><h4>Reorder Listitems</h4><p>To enable the reordering of list items, we must first establish their initial order. This is achieved by assigning each item an order number using the ‘orderNr’ field, which we define as ‘list.length + 1’. It’s important to note that this approach necessitates updating the order number of a FlashlistItem whenever a preceding item is deleted or when an item is moved ahead of it.</p><p>I tried to cover both cases with one method that works great but is not comfortable to look at XD. But anyway to give you an idea, I’m sharing it here.</p><pre>Future&lt;void&gt; updateOrderNumbers(<br>  Session session,<br>  FlashlistItem flashlistItem,<br>  int? newOrderNr,<br>) async {<br>  final flashlistItems = await FlashlistItem.db.find(session,<br>      where: (currentItem) =&gt;<br>          currentItem.parentId.equals(flashlistItem.parentId));<br><br>  if (newOrderNr == null) {<br>    // Item is being deleted, reduce orderNr for all siblings coming after<br>    for (var currentItem in flashlistItems) {<br>      if (currentItem.orderNr &gt;= flashlistItem.orderNr &amp;&amp;<br>          currentItem.id != flashlistItem.id) {<br>        await FlashlistItem.db.updateRow(<br>          session,<br>          currentItem.copyWith(orderNr: currentItem.orderNr - 1),<br>        );<br>      }<br>    }<br>  } else {<br>    // Item is being moved<br>    int oldOrderNr = flashlistItem.orderNr;<br>    for (var currentItem in flashlistItems) {<br>      if (currentItem.id != flashlistItem.id) {<br>        if (oldOrderNr &lt; newOrderNr &amp;&amp;<br>            currentItem.orderNr &gt; oldOrderNr &amp;&amp;<br>            currentItem.orderNr &lt;= newOrderNr) {<br>          // Item is moving down the list, decrease the orderNr of every following item by 1<br>          await FlashlistItem.db.updateRow(<br>            session,<br>            currentItem.copyWith(orderNr: currentItem.orderNr - 1),<br>          );<br>        } else if (oldOrderNr &gt; newOrderNr &amp;&amp;<br>            currentItem.orderNr &lt; oldOrderNr &amp;&amp;<br>            currentItem.orderNr &gt;= newOrderNr) {<br>          // Item is moving up the list, increase the orderNr of every preceding item by 1<br>          await FlashlistItem.db.updateRow(<br>            session,<br>            currentItem.copyWith(orderNr: currentItem.orderNr + 1),<br>          );<br>        }<br>      }<br>    }<br>    // Finally, update the orderNr of the moved item<br>    await FlashlistItem.db.updateRow(<br>      session,<br>      flashlistItem.copyWith(orderNr: newOrderNr),<br>    );<br>  }<br>}</pre><p>Of course these changes also need to be applied to any copy of the list a user currently is looking at on his phone, which you can also find <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_flutter/lib/src/features/flashlist/application/flashlist_stream_message_handler.dart">here</a>.</p><h4>Conclusion</h4><p>By using a WebSocket to transfer data, we ensure that the user’s data is always up to date as long as there is an internet connection. We send the most recent state when the session starts and subscribe to any changes while it lasts, enabling real-time updates without the need for manual refreshes. This approach enhances the user experience by providing seamless and responsive interaction with the application.</p><p>Thanks for reading this one. As this is the core functionality of Flashlist, it was important for me to share it in a little more detail than most readers might have required. However, I wanted to ensure it was understandable for everyone.</p><p>Make sure to subscribe to not miss anything. And of course don’t forget to clap, either on medium or in real life while sitting in front of your computer. I swear! I will hear it ❤.</p><p>Have a great day, and “May the Pods have mercy on your code”.</p><p><a href="https://medium.com/@ben.auer.dev/flashlist-part-4-mind-your-context-sensitivity-8c15f3d06826">Next: Flashlist PART 4: Mind your Context Sensitivity</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664142cdbf51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 2: Let there be users]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/a69cfd7ea97d</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[serverpod]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 10:21:21 GMT</pubDate>
            <atom:updated>2024-04-01T10:46:55.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6_hboSY8nx6RAvuR" /><figcaption>Photo by <a href="https://unsplash.com/@papaioannou_kostas?utm_source=medium&amp;utm_medium=referral">Papaioannou Kostas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Empowering User Interactions: Leveraging Serverpod and Riverpod Providers</h4><h4>Intro</h4><p>In my previous post, I discussed setting up ServerRiverPodPod and how to gracefully handle authentication state changes. However authentication is just the beginning when it comes to app interactions. After a user confirms their identity, we need an object to represent them that holds no sensitive information.</p><p>In case you missed the first part or want to know why I’m building Flashlist, you can follow the links below:</p><ol><li><a href="https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f">Flashlists Journey with Cutting Edge Technology</a></li><li><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></li></ol><h4>AppUser</h4><p>Within the models directory, we add an ‘AppUser’ class that represents the user within the application.</p><pre>class: AppUser<br>table: flashlist_app_user<br>fields:<br> userId: int, relation(parent=serverpod_user_info, onUpdate=Cascade, onDelete=Cascade)<br> username: String<br> email: String<br> imageSrc: String?</pre><p>After running serverpod generate we then add the onUserCreated method to the auth config.</p><pre>// ...server/lib/server.dart<br>auth.AuthConfig.set(<br> auth.AuthConfig(<br>   sendValidationEmail: (session, email, validationCode) async {<br>     // Handle code sending validation email<br>     return true;<br>   },<br>   sendPasswordResetEmail: (session, userInfo, validationCode) async {<br>     // Send the password reset email to the user.<br>     return true;<br>   },<br>   onUserCreated: (session, userInfo) {<br>    // Create a AppUser object with the information of the created auth-user<br>     return AppUser.db.insertRow(<br>       session,<br>       AppUser(<br>         userId: userInfo.id!,<br>         email: userInfo.email!,<br>         username: userInfo.userName,<br>       ),<br>     );<br>   },<br> ),<br>);</pre><p>We also need 3 other models: Notification, UserRequest and UserRelation. You can look at them <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_server/lib/src/endpoints/app_user_endpoint.dart">here</a>, but in case you couldn’t be bothered I’ll brush over them quickly:</p><p><strong>Notification</strong> — A notification about an event that the user should be informed about.</p><p><strong>UserRequest</strong> — A request from one user to another, such as a friend request or invitation.</p><p><strong>UserRelation</strong> — A connection between two users.</p><h4>Endpoint</h4><p>Next, we declare the AppUserEndpoint, from which we plan on dealing with user-specific logic.</p><pre>// ...server/lib/src/endpoints/app_user_endpoint.dart<br>class AppUserEndpoint extends Endpoint {<br> Future&lt;AppUser?&gt; getCurrentUser(Session session) async {<br>   final currentUserId = await session.auth.authenticatedUserId;<br><br><br>   return await AppUser.db.findFirstRow(<br>     session,<br>     where: (appUser) =&gt; appUser.userId.equals(currentUserId),<br>   );<br> }<br><br><br> Future&lt;AppUser?&gt; getUserByEmail(Session session, String email) async {<br>   return await AppUser.db.findFirstRow(<br>     session,<br>     where: (appUser) =&gt; appUser.email.equals(email),<br>   );<br> }<br>}</pre><p>Note: The Endpoint quickly got very large, so I won’t be sharing it in full here, but you can take a look at it <a href="https://github.com/BenAuerDev/flashlist/blob/main/flashlist_server/lib/src/endpoints/app_user_endpoint.dart">here</a>.</p><h4>UserController</h4><p>Our UserController serves as a Single Source of Truth (SOT) for all methods exposed by the AppUserEndpoint to the frontend.</p><pre>// ...flutter/lib/src/features/users/application/user_controller.dart<br><br>part &#39;user_controller.g.dart&#39;;<br><br><br>class UserController {<br> /// Controller for user related actions.<br> UserController(this.ref);<br><br><br> final Ref ref;<br><br><br> Future&lt;AppUser?&gt; getCurrentUser() async {<br>   final client = ref.read(clientProvider);<br>   return await client.appUser.getCurrentUser();<br> }<br><br><br> Future&lt;AppUser?&gt; getUserById(int id) async {<br>   final client = ref.read(clientProvider);<br>   return await client.appUser.getUserById(id);<br> }<br><br><br> Future&lt;void&gt; sendConnectionRequestByEmail(String email) async {<br>   final client = ref.read(clientProvider);<br>   await client.appUser.sendConnectionRequestByEmail(email);<br> }<br><br><br> Future&lt;void&gt; acceptConnectionRequest(int requestId) async {<br>   final client = ref.read(clientProvider);<br>   await client.appUser.acceptConnectionRequest(requestId);<br> }<br><br><br> Future&lt;void&gt; removeRequest(int requestId) async {<br>   final client = ref.read(clientProvider);<br>   await client.appUser.removeRequest(requestId);<br> }<br><br><br> Future&lt;List&lt;AppUser&gt;&gt; getConnections() async {<br>   final client = ref.read(clientProvider);<br>   return await client.appUser.getConnections();<br> }<br><br><br> Future&lt;List&lt;UserRequest?&gt;&gt; getPendingRequests() async {<br>   final client = ref.read(clientProvider);<br>   return await client.appUser.getRequestsForUser();<br> }<br>}<br><br><br>@riverpod<br>UserController userController(Ref ref) =&gt; UserController(ref);<br><br><br>@riverpod<br>Future&lt;AppUser?&gt; currentUser(CurrentUserRef ref) =&gt;<br>   ref.watch(userControllerProvider).getCurrentUser();<br><br><br>@riverpod<br>Future&lt;List&lt;AppUser?&gt;&gt; connections(ConnectionsRef ref) =&gt;<br>   ref.watch(userControllerProvider).getConnections();<br><br><br>@riverpod<br>Future&lt;List&lt;UserRequest?&gt;&gt; pendingRequests(PendingRequestsRef ref) =&gt;<br>   ref.watch(userControllerProvider).getPendingRequests();<br><br><br>@riverpod<br>Future&lt;AppUser?&gt; userById(UserByIdRef ref, int id) =&gt;<br>   ref.watch(userControllerProvider).getUserById(id);</pre><p>By following this pattern we’ve established a solid foundation for managing users, user requests, user relations, and notifications within the app.</p><h4>Conclusion</h4><p>Properly managing user data is fundamental for any developer. By separating the authentication user from the app user, we can safeguard sensitive data, ensuring it’s only exposed when a user authenticates or engages with the platform.</p><p>Clap if you agree! 👏👏👏👏</p><p><a href="https://medium.com/@ben.auer.dev/flashlist-part-3-implementing-the-crud-stream-664142cdbf51">Next: Flashlist PART 3: Implementing the CRUD Stream</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69cfd7ea97d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod]]></title>
            <link>https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e99819996b</guid>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[serverpod]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 11:37:50 GMT</pubDate>
            <atom:updated>2024-03-24T19:23:55.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UEMvmTg16HGWUa5u" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Leverage the power of Serverpod and Riverpod</h4><h4>Intro</h4><p>In this post, I’ll share how I integrate Serverpod into my frontend, leveraging Riverpods functionality for a reactive layout and explore caching on both sides.</p><p>Also before we get into this whole thing, the irony is by far not lost on me, that two of the core technologies I am basing my app on both end in “pod”. Rather than repeatedly mentioning ‘Serverpod and Riverpod’, I’ve decided to dub this combined integration ‘ServerRiverPodPod&#39; as it is way more satisfying to say and write.</p><p>If you’re not a fan of ‘ServerRiverPodPod’ well, I’m sorry, but you should have come up with a “better” name before me then. (Unless you happen to be Remy or Viktor, in which case, I’m all ears if you have any suggestions).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6nUL6IQuZpy4fHNK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fheyarnold-hey-arnold-nick-splat-3o6nUL6IQuZpy4fHNK&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbXJlbjRncnl2bDltZWM5N2Q3bW5uY3EyanYyZmZpbXU4b2Y3OGhkdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o6nUL6IQuZpy4fHNK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/80363472b0f0b33d4b6b427b8302fa74/href">https://medium.com/media/80363472b0f0b33d4b6b427b8302fa74/href</a></iframe><h4>Prerequisites</h4><p>I won’t be covering the setup of Serverpod authentication as it is well-documented on their <a href="https://docs.serverpod.dev/">docs</a> or <a href="https://medium.com/serverpod/getting-started-with-serverpod-authentication-part-1-72c25280e6e9">here</a>. Ensure you have the setup for ServerpodAuth and an Authentication-Provider (Email, Google, Apple, Firebase). I am using SignInWithEmailButton as it provides (almost) everything I need for now.</p><p>All set? Awesome, let’s continue :)</p><p>In the Serverpod documentation, you probably already saw an option on how to declare the Client and initialize the SessionManager in a StatefulWidget. However, I want something a little different as I am going to use Riverpod. I aim to encapsulate both Client and SessionManager into a Provider for Riverpod to cache.</p><h4>Caching</h4><p>Additionally, it’s worth noting that Serverpod features its own caching mechanism, complementing Riverpods caching capabilities. Below, I’ve outlined some points showcasing how powerful the product of this “fusion” is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*EVir3Lm3MShOYOtpZVbcWw.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTbYgHMnICI1A4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdragon-ball-z-dbz-TbYgHMnICI1A4&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExY2Myem4wajM0NXJpZzR4bGxlOHduNWFuYnNuazMwYjFzanF2ZzZoZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FTbYgHMnICI1A4%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="122" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f949954ea380e2b6ca450813a6a278/href">https://medium.com/media/43f949954ea380e2b6ca450813a6a278/href</a></iframe><p>To summarise, with ServerRiverPodPod we leverage two caching systems to optimise performance, effectively reducing the strain on the internet connection, which serves as the bridge between them. All we have to do is handle the life cycle of our Client and SessionManager instance within a Provider and follow the riverpod-pattern.</p><h4>Let’s provide ourselves with a Client instance</h4><p>All we need to do for that, is declaring an instance of the Client inside a provider, which looks in my case like:</p><pre>// ...flutter/lib/src/utils/serverpod/serverpod_helper.dart<br><br>@riverpod<br>Client client(ClientRef ref) =&gt; Client(<br>     &quot;10.0.2.2:8080/&quot;,<br>     authenticationKeyManager: FlutterAuthenticationKeyManager(),<br>   )..connectivityMonitor = FlutterConnectivityMonitor();</pre><p>If you’re not familiar with or don’t use riverpod_annotation and build_runner you would just do something like this:</p><pre>final clientProvider = Provider&lt;Client&gt;(<br>  (ref) =&gt; Client(<br>    &quot;10.0.2.2:8080/&quot;,<br>    authenticationKeyManager: FlutterAuthenticationKeyManager(),<br>  )..connectivityMonitor = FlutterConnectivityMonitor(),<br>);</pre><h4>SessionManager</h4><p>With our Client now ready, it’s time to tend to the SessionManager, which we can declare like so:</p><pre>// ...flutter/lib/src/utils/serverpod/serverpod_helper.dart<br><br>@riverpod<br>SessionManager sessionManager(SessionManagerRef ref) =&gt;<br>   SessionManager(caller: ref.watch(clientProvider).modules.auth,<br>);</pre><p>Just like this we can declare our SessionManager and connect it to the auth module associated our clientProvider.</p><h4>ServerpodHelper</h4><p>It is important to note, that the SessionManager needs to be initialised which I do in a ServerpodHelper class and set up a provider to manage the life cycle and make the properties accessible like so:</p><pre>// ...flutter/lib/src/utils/serverpod/serverpod_helper.dart<br><br>class ServerpodHelper {<br> ServerpodHelper(this.client, this.sessionManager) {<br>   sessionManager.initialize();<br> }<br><br><br> final Client client;<br> final SessionManager sessionManager;<br>}<br><br><br>@riverpod<br>ServerpodHelper serverpodHelper(ServerpodHelperRef ref) =&gt;<br>   ServerpodHelper(<br>     ref.watch(clientProvider),<br>     ref.watch(sessionManagerProvider),<br>   );</pre><p>This way we declare ServerpodHelper, which expects Client and SessionManager as parameters. And initialize the SessionManager within the constructor of the ServerpodHelper.</p><p>Note: While it’s possible to achieve a similar result by passing the Ref to the ServerpodHelper and declare Client and SessionManager as instance variables with their own getters, I chose the current approach for mainly two reasons:</p><ol><li>Modularity — It’s possible to access the properties individually, thereby separating concerns and promoting a modular design. This enhances code maintainability and readability.</li><li>Testing — In scenarios where we need to set up tests that require mocking the behaviour of either the Client or SessionManager, this approach allows for comfortable overrides.</li></ol><p>Now that the initial setup is done, it’s time to take a deep breath (maybe also grab a coffee) before we reflect on what we’ve accomplished. We can now effortlessly call upon the Client and SessionManager individually or combined within our providers, be it a Consumer, ConsumerWidget, or ConsumerStatefulWidget.</p><h4>isAuthenticatedProvider</h4><p>But before we dive into building Widgets and Screens, let’s leverage our SessionManager to construct a StreamProvider. This StreamProvider will gracefully handle the authentication state, seamlessly transitioning between the auth-screen and home-screen based on the user’s authentication status.</p><pre>@riverpod<br>Stream&lt;bool&gt; isAuthenticated(IsAuthenticatedRef ref) async* {<br>  // access the SessionManager<br>  final SessionManager sessionManager = ref.watch(sessionManagerProvider);<br>  <br>  // Add a listener to the SessionManager that invalidates the IsAuthenticatedRef<br>  // whenever the session state changes, ensuring that the isAuthenticated stream<br>  // reflects the latest authentication status.<br>  sessionManager.addListener(() {<br>     ref.invalidateSelf();<br>  });<br>  <br>  // Yield a boolean value reflecting the authentication state.<br>  // If the signed-in user is not null, the user is authenticated.<br>  // Otherwise, the user is not authenticated.<br>  yield sessionManager.signedInUser != null;<br>}</pre><p>If you haven’t already it’s now time to navigate to your flutter directory in your terminal and run:</p><pre>dart run build_runner build</pre><h4>Handling Authentication State with isAuthenticatedProvider</h4><p>Now that we have all our providers set up, it’s time to build something tangible. With the isAuthenticatedProvider returning true or false, we can seamlessly integrate it into our widget tree. This can be achieved within the main or home widget, provided that the widget extends ConsumerWidget or ConsumerStatefulWidget.</p><p>In my case, I opt for using go_router. Coming from a background in JavaScript frameworks, I appreciate having a centralised SOT when it comes to possible routes and how they relate to each other.</p><p>So within my app_router.dart file I:</p><pre>// ...flutter/lib/src/features/routing/app_router.dart<br><br>...<br>GoRoute(<br>  path: &#39;/&#39;,<br>  name: AppRoute.home.name,<br>  builder: (context, state) {<br>    return Consumer(<br>      builder: (context, ref, child) {<br>        // Uses the ref provided by Consumer to get isAuthenticatedProvider<br>        final isAuthenticated = ref.watch(isAuthenticatedProvider);<br>  <br>        <br>        return isAuthenticated.when(<br>          data: (user) {<br>            if (!user) {<br>              return const AuthScreen();<br>            } else {<br>              return const HomeScreen();<br>            }<br>          },<br>          loading: () =&gt; const Center(<br>            child: CircularProgressIndicator(),<br>          ),<br>          error: (error, stackTrace) =&gt; Center(<br>            child: Text(&#39;Error: $error&#39;),<br>          ),<br>        );<br>      },<br>    );<br>...</pre><p>Note: In this implementation, the isAuthenticatedProvider resides higher up in the WidgetTree. As a reminder, the SessionManager needs to be initialized to function properly. Therefore, it’s essential to ensure that the SessionManager is initialized by calling ServerpodHelperProvider either in the AuthScreen or HomeScreen to enable the authentication process. However, once initialized, we can seamlessly use the Client and SessionManager individually throughout the application without any concerns.</p><h4>AuthScreen</h4><p>Our current AuthScreen, is straightforward yet effective. At present, it only contains the SignInWithEmailButton. This button initiates a modal that handles user authentication.</p><pre>// ..._flutter/lib/src/features/authentication/presentation/auth_screen.dart<br><br>class AuthScreen extends ConsumerWidget {<br> const AuthScreen({super.key});<br><br><br> @override<br> Widget build(BuildContext context, WidgetRef ref) {<br>   // calling the client via the serverpodHelperProvider here <br>   // ensures that the sessionManager will be instantiated at the right time<br>   final client = ref.watch(serverpodHelperProvider).client;<br><br><br>   return Scaffold(<br>     body: Center(<br>         child: Column(<br>       mainAxisSize: MainAxisSize.min,<br>       children: [<br>         SignInWithEmailButton(<br>           caller: client.modules.auth,<br>         )<br>       ],<br>     )),<br>   );<br> }<br>}</pre><h4>HomeScreen</h4><p>Our HomeScreen is as simple, it only features a Text saying welcome! And also holding a sign-out button to let us try out the functionality that we just built.</p><pre>// ..._flutter/lib/src/features/home/presentation/home_screen.dart<br><br>class HomeScreen extends ConsumerWidget {<br> const HomeScreen({super.key});<br><br><br> @override<br> Widget build(BuildContext context, WidgetRef ref) {<br>   final sessionManager = ref.read(sessionManagerProvider);<br><br><br>   return Scaffold(<br>     appBar: AppBar(<br>       title: const Center(<br>         child: Text(&#39;Home&#39;),<br>       ),<br>     ),<br>     body: Column(<br>       children: [<br>         const Center(<br>           child: Text(&#39;Welcome!&#39;),<br>         ),<br>         ElevatedButton(<br>           child: const Text(&#39;Sign Out&#39;),<br>           onPressed: () {<br>             sessionManager.signOut();<br>           },<br>         ),<br>       ],<br>     ),<br>   );<br> }<br>}</pre><h4>Recap and Props</h4><p>Nice Job making it this far, let’s sum up what we achieved here.</p><ol><li>Created Client and ClientProvider.</li><li>Established SessionManager and SessionManagerProvider.</li><li>Implemented ServerpodHelper and ServerpodHelperProvider to manage the life cycle of our Client and SessionManager.</li><li>Built ourselves an isAuthenticatedProvider, which utilizes SessionManager to listen for changes in authentication state and trigger rerenders when necessary.</li><li>Set up Screens (HomeScreen and AuthScreen) to facilitate user authentication and navigation.</li></ol><h4>Conclusion</h4><p>With these foundational elements in place, you’re now all set to explore ServerRiverPodPod. Once an Endpoint has been established, it can be called using the following pattern:</p><p>ref.read(clientProvider).endpoint-name.method()</p><p>or</p><p>ref.watch(clientProvider).endpoint-name.method()</p><p>So when my Endpoint is:</p><pre>class FlashlistEndpoint extends Endpoint {<br>  ...<br>  <br>  Future&lt;List&lt;Flashlist&gt;&gt; getFlashlistsForUser(Session session) {<br>    // code that retrieves the Flashlists<br>    // asociated with the current User <br>  }<br><br>  ...<br>}</pre><p>I would call it like:</p><pre>final List&lt;Flashlist&gt; =  ref.watch(clientProvider).flashlist.getFlashlistsForUser();</pre><p>It’s important to recognize that the UserInfo object provided by the serverpod_auth package contains sensitive information and should not be shared with other users.</p><p>In the next post, I’ll introduce a separate Database entity called AppUser. Subscribe if you want to tag along on the journey ahead, if you couldn’t be bothered, that’s also fine :)</p><p>Thanks for reading my first technical blog post and “May the pods have mercy on your code”.</p><p><a href="https://medium.com/@ben.auer.dev/flashlist-part-2-let-there-be-users-a69cfd7ea97d">Next: Flashlist PART 2: Let there be users</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e99819996b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashlist’s Journey with Serverpod, Riverpod and other Cutting-Edge Technologies]]></title>
            <link>https://medium.com/@ben.auer.dev/powering-innovation-flashlists-journey-with-serverpod-riverpod-and-other-cutting-edge-02937565e28f?source=rss-e63bd9c95020------2</link>
            <guid isPermaLink="false">https://medium.com/p/02937565e28f</guid>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[serverpod]]></category>
            <dc:creator><![CDATA[Ben Auer]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 11:37:04 GMT</pubDate>
            <atom:updated>2024-05-26T18:42:29.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcQEw-kFRAzganfHuQNhOA.png" /></figure><p>To whoever is reading this, I’m sure you’ve heard this one before: “I’m building an app”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpadRS0HKJ7Irh150L%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fnickcannon-nick-cannon-BpadRS0HKJ7Irh150L&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExODk4YWM3dDZ4djZjNm9vMzN0cW4wdzUyMHU4aXZrNWV6b3ZvdWxhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FBpadRS0HKJ7Irh150L%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a8bcd7e82a08d2a4080394ccb286ef8/href">https://medium.com/media/9a8bcd7e82a08d2a4080394ccb286ef8/href</a></iframe><p>However, I’m building it with Serverpod and as of writing this, there are not enough documented use cases. That’s why I’ve decided to start documenting and sharing my journey, including the solutions and experiences I encounter along the way, on a regular basis.</p><h3><strong>A short Intro</strong></h3><p>My goal is to build an open-source app that allows users to manage and share lists. Many times, it’s useful to have a shared shopping list, a to-do for the team building prep or a place to share any kind of information in real time. My proposed solution to this is called Flashlist. <a href="https://drive.google.com/file/d/19qlnejTbCVUutHFeHxvmQBcmexVGAGsb/view?usp=sharing">I wrote a short case study explaining its functionality and potential in detail (and I also asked a friend of mine to give it a nice look for people to read it more comfortably).</a></p><h3>Technologies</h3><p>For a collaborative solution to excel, it must be accessible across multiple platforms while offering a reactive interface, real-time updates across multiple devices and push notifications. That’s why, in terms of technology, I am working with the following:</p><h4><a href="https://flutter.dev/">Flutter</a></h4><p>No explanation needed…</p><h4><a href="https://riverpod.dev/">Riverpod</a></h4><p>State management, caching and data binding framework. Like the description says it’s more than just state management</p><h4><a href="https://firebase.google.com/docs/flutter/setup?platform=ios">Firebase (Honorable Mention)</a></h4><p>I used Firebase for the POC and really liked the developer experience, because of great modules, already existing packages like <a href="https://firebase.flutter.dev/">Flutterfire</a>, a vast amount of documented use cases and a large community.</p><p>However, for the next version I am working with <a href="https://serverpod.dev/">Serverpod</a>. Why? The first lines on their website sum it up well:</p><p><em>“Serverpod is an open-source, scalable app server written in Dart for the Flutter community. Serverpod automatically generates your model and client-side code by analyzing your server. Calling a remote endpoint is as easy as making a local method call.”</em></p><h4><a href="https://serverpod.dev/">Serverpod</a></h4><p>They honestly had me at “open-source and scalable”. But looking into Serverpod for a few months while I was exploring how to provide the desired functionality, I really grew to like it. Snazzy comic mascots and version names like ‘cyberpunk’ inject a playful energy into their brand, which does resonate with me. Despite this playful vibe, I am confident that the tech they provide is solid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eAd-IaUeapXzDtmdutCnAQ.png" /></figure><p>Also, the improvements in workflow that came with the upgrade from version 1.1 to 1.2 give a good hint on how it will impact the future building of flutter apps. I am looking forward to seeing what else they are going to do, and will continue to explore Serverpod functionalities.</p><h4>Conclusion</h4><p>If you are considering using Serverpod and Riverpod or are intrigued by these emerging technologies, join me as I share my experiences developing Flashlist. By exploring the application of these tools, you can gain insights and practical knowledge. Or how my man Marcus Aurelius used to say:</p><blockquote>”The impediment to action advances action. What stands in the way becomes the way.“</blockquote><p><a href="https://medium.com/@ben.auer.dev/flashlist-part-1-serverpod-riverpod-serverriverpodpod-f3e99819996b">Next: Flashlist PART 1: Flashlist PART 1: Serverpod + Riverpod = ServerRiverPodPod</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02937565e28f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>