<?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 Leo Wong on Medium]]></title>
        <description><![CDATA[Stories by Leo Wong on Medium]]></description>
        <link>https://medium.com/@gnowoel?source=rss-cdf967ae0623------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gl41Yv-hb5_it83Jhkj3vQ.jpeg</url>
            <title>Stories by Leo Wong on Medium</title>
            <link>https://medium.com/@gnowoel?source=rss-cdf967ae0623------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:00:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gnowoel/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[The Challenges of Building a Simple Chat App with Flutter and Firebase]]></title>
            <link>https://itnext.io/the-challenges-of-building-a-simple-chat-app-with-flutter-and-firebase-b9f0a2f0f889?source=rss-cdf967ae0623------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9f0a2f0f889</guid>
            <category><![CDATA[realtime-database]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[anonymous-chat-app]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Leo Wong]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 14:34:55 GMT</pubDate>
            <atom:updated>2024-08-21T09:21:01.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZxjwStnd2owtSSdBKAJkA.png" /><figcaption><a href="https://www.flaticon.com/free-icons/expressions">Expressions icons created by Freepik — Flaticon</a></figcaption></figure><p>To satisfy my own needs, I built an <a href="https://github.com/gnowoel/talktive">anonymous chat app</a>. Since I’ve been learning Flutter and Firebase recently, using this tech stack felt like a natural choice. However, what seemed like a two or three week project ended up taking more than two months. Why was that?</p><p>My requirements were pretty simple:</p><ul><li>No login</li><li>Group chat</li><li>No records</li></ul><p>But as I started working on it, I encountered numerous small challenges, including:</p><ul><li>Choosing a database</li><li>Presenting anonymous users</li><li>Discovering rooms</li><li>Auto-scrolling to view new messages</li><li>Purging old messages</li><li>Handling disconnections</li><li>Writing tests</li></ul><p>As a result, the development became a series of exploratory steps. Now that the app is <a href="https://open.talktive.app/">online</a>, I see this process as a meaningful experience. Like any other endeavor, we achieve our goals by constantly adapting.</p><p>I want to write down the most important parts of this journey — both for my own reference and for anyone who might find it helpful. As a beginner with Flutter and Firebase, I must have made some mistakes along the way. So please feel free to correct me, and I’d appreciate any insights you might have.</p><p>Before diving in, you may want to take a look at the <a href="https://github.com/gnowoel/talktive">source code</a>, or even <a href="https://open.talktive.app/">try it out</a>. This will give you a better understanding of the topics I’ll be discussing below.</p><h4>Choosing the database</h4><p>The project originally started with Cloud Firestore, which seemed like the newer and better option. However, I came across the <a href="https://firebase.google.com/docs/database/rtdb-vs-firestore">documentation</a> which stated:</p><blockquote>Realtime Database charges only for <strong>bandwidth and storage</strong> …</blockquote><p>Then I realized that Realtime Database was the more cost effective choice, as a chat app sends a lot of messages but takes up very little space. Also, in our app, all expired messages are permanently deleted.</p><p>Switching to Realtime Database did come with some trade-offs: the web app lacks offline support, and the query capabilities are less powerful. We’ll deal with those issues later.</p><h4>Development environment</h4><p>You can use the <a href="https://firebase.google.com/docs/emulator-suite">Local Emulator Suite</a> to run Firebase services locally. However, I found it necessary to create a second Firebase project - the Local Emulator Suite can not replicate all features, and we still need a staging server.</p><p>For instance, the following features only work on the live server:</p><ul><li><a href="https://firebase.google.com/docs/auth/flutter/anonymous-auth">Anonymous authentication</a></li><li><a href="https://firebase.google.com/docs/functions/schedule-functions?gen=2nd">Scheduled functions</a></li><li><a href="https://firebase.google.com/docs/reference/node/firebase.database.ServerValue">Server-side increment</a></li></ul><p>So, when using the Local Emulator Suite, you’ll have to find ways to work around these limitations, which I’ll cover in the following sections.</p><p>You’ll also need two local projects in different folders, each connected to its own Firebase backend. I develop in the first project and test it on the staging server. When it’s time to deploy, I sync the code to the second project via GitHub.</p><h4>Anonymous authentication</h4><p>With <a href="https://firebase.google.com/docs/auth/flutter/anonymous-auth">Firebase Authentication</a>, you only need to call a single method to create an anonymous user:</p><pre>FirebaseAuth.instance.signInAnonymously();</pre><p>However, signInAnonymously() doesn&#39;t work reliably in the Local Emulator Suite, so I decided to simulate this feature locally by using a random email and password:</p><pre>FirebaseAuth.instance.createUserWithEmailAndPassword(<br>  email: randomEmail,<br>  password: randomPassword,<br>);</pre><p>You can check the kDebugMode constant to distinguish between the two running environments:</p><pre>if (kDebugMode) {<br>  // localhost<br>} else {<br>  // server<br>}</pre><p>To easily get a random string, one way is to use Random().nextInt() to generate a few numbers, and then use them as indices for picking characters in the alphabet.</p><h4>User avatars</h4><p>Each anonymous user is a unique individual, so they shouldn’t all look the same in the chat room. However, adding a large number of avatar images would significantly increase the size of the app, which is especially undesirable for a web app.</p><p>How about emojis? They’re universally supported, offering a wide range of images for free without additional installation. Also, since emojis are essentially fonts, selecting an avatar is as simple as generating a random code point.</p><p>This worked, but I realized that not all emojis make great avatars. For example, smiley faces and country flags aren’t the best choices.</p><p>There are several ready-made packages on <a href="https://pub.dev/">pub.dev</a> that can help with filtering. I chose <a href="https://pub.dev/packages/unicode_emojis">unicode_emojis</a>, which groups the entries in categories, making it easy to pick the appropriate ones:</p><pre>const categories = &lt;Category&gt;[<br>  Category.peopleAndBody,<br>  Category.animalsAndNature,<br>  Category.foodAndDrink,<br>  // ...<br>];</pre><p>After that, every avatar appears to be unique and appealing!</p><h4>Device language detection</h4><p>Not all users speak English, but I want everyone to be able to join the chat. My idea was to group chat rooms based on the device language, so that all users in the same chat room share the same language.</p><p>Detecting the device language appears to be easy since the <a href="https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization">Flutter documentation</a> already gives a solution:</p><blockquote>You can always look up an app’s current locale with Localizations.localeOf().</blockquote><p>But I quickly discovered that this method always returns en, regardless of the device&#39;s actual language.</p><p>I later knew that this method is intended to determine the interface language, which only works when the corresponding translation files exist.</p><p>I didn’t want to change the interface language or provide a translation file for every possible language. I needed an alternative way.</p><p>The approach I finally settled on is simple and it involves two different scenarios.</p><p>For non-web apps, we can use <a href="https://api.dart.dev/stable/3.4.4/dart-io/Platform/localeName.html">Platform.localeName</a> from the dart:io package:</p><pre>Platform.localeName.split(&#39;_&#39;).first;</pre><p>The split() method is necessary because the returned locale may contain additional information, such as the country code.</p><p>For web apps, we use <a href="https://api.flutter.dev/flutter/dart-ui/FlutterView/platformDispatcher.html">FlutterView.platformDispatcher</a> from dart:ui instead:</p><pre>View.of(context).platformDispatcher.locale.languageCode;</pre><p>In this case, we get the current FlutterView with View.of(context).</p><p>The kIsWeb constant can be used to check if it&#39;s a web app:</p><pre>if (kIsWeb) {<br>  // for web app<br>} else {<br>  // for non-web app<br>}</pre><p>Now we can get the language code, like en or de, in each supported platform.</p><h4>Time synchronization</h4><p>All chat rooms expire after a period of time. In order to keep the clients informed of the status of a chat room, it’s best to have the device time as accurate as possible.</p><p>Fortunately, Firebase provides a time synchronization service. By listening to a specific path in the Realtime Database, we can obtain a time offset:</p><pre>int offset = 0;<br><br>final ref = FirebaseDatabase.instance.ref(&#39;.info/serverTimeOffset&#39;);<br><br>ref.onValue.listen((event) {<br>  offset = (event.snapshot.value as num? ?? 0.0).toInt();<br>});</pre><p>This offset, given in milliseconds, can be either positive or negative. By adding it to the local time, you get the more accurate server time:</p><pre>final now = DateTime.now().millisecondsSinceEpoch + offset;</pre><h4>Selecting a chat room</h4><p>Users do not choose chat rooms themselves. Instead, we choose the next one for them based on the following two criteria:</p><ul><li>The room language matches the device language.</li><li>The room is the least active among the options.</li></ul><p>The Realtime Database only supports sorting by a single field. We can work around this by combining data from multiple fields. For example, we can create a filter field, for saving values like this:</p><pre>en-1234</pre><p>Here, en represents the language code, and 1234 indicates the room&#39;s activity level. To filter rooms based on both conditions, we can use startAt() and endAt() in the query:</p><pre>FirebaseDatabase.instance.ref(&#39;rooms&#39;)<br>  .orderByChild(&#39;filter&#39;)<br>  .startAt(&#39;$languageCode-0000&#39;)<br>  .endAt(&#39;$languageCode-9999&#39;);</pre><p>This ensures the returned rooms have the correct language code and are ranked by the activity level. But how exactly do we measure the activity level?</p><p>It’s not ideal to use the timestamp of the last message, as it would prioritize rooms that are about to expire. Similarly, relying on the message count could lead to prioritizing less engaging rooms.</p><p>I decided to use the timestamp of the last visitor, which resolved both issues:</p><ul><li>New rooms don’t have to wait for too long.</li><li>Unpopular rooms won’t maintain a high priority.</li></ul><p>This even eliminates the need to flag inappropriate rooms. If a topic is uninteresting, we simply skip it.</p><p>We still need to exclude the rooms that have already been visited, which can’t be done with the Realtime Database queries alone. My solution is to try multiple times until a new room is found.</p><h4>Manual retry</h4><p>Anonymous login attempts will fail if there’s no network connection. In such cases, we can easily redirect to an error page with FutureBuilder:</p><pre>FutureBuilder(<br>  future: FirebaseAuth.instance.signInAnonymously(),<br>  builder: (context, snapshot) {<br>    if (snapshot.hasError) {<br>      return ErrorPage();<br>    }<br><br>    if (!snapshot.hasData) {<br>      return const Text(&#39;Loading...&#39;);<br>    }<br><br>    return const HomePage();<br>  },<br>)</pre><p>On the error page, I wanted to add a “Retry” button to refresh the page using setState().</p><p>However, I noticed that the “Retry” button never worked as expected, even after the network connection was restored. Users might have to click it many times, and they might even encounter an internal-error message.</p><p>The reason, as I understand it, is that when the widget tree remains unchanged, FutureBuilder retains as many the previous State values as possible, which includes the error property. This behavior is evident from a comment in the <a href="https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/async.dart">source code</a>:</p><blockquote>The data, error, and stackTrace fields persist unmodified...</blockquote><p>As a result, before the second attempt begins, the snapshot.hasError condition is already met, sending users back to the error page.</p><p>While FutureBuilder doesn&#39;t reset the error, it does reset the ConnectionState from done to none:</p><pre>_snapshot = _snapshot.inState(ConnectionState.none);</pre><p>By leveraging this, we can implement a simple solution by checking snapshot.connectionState before evaluating snapshot.hasError:</p><pre>builder: (context, snapshot) {<br>  if (snapshot.connectionState != ConnectionState.done) {<br>    return const Text(&#39;Loading...&#39;);<br>  }<br><br>  if (snapshot.hasError) {<br>    return ErrorPage();<br>  }<br><br>  return const HomePage();<br>}</pre><p>It may seem like just switching the order of the conditions, but this little tweak effectively resolves the issue.</p><h4>Continuously updating widgets</h4><p>There are several time-sensitive widgets that I want to update continuously, such as the heart-shaped icons representing a room’s health. Typically, this can be done with Timer.periodic():</p><pre>Timer.periodic(duration, () {<br>  // `setState()` based on time<br>});</pre><p>In the callback function, we perform calculations based on the current time and then call setState() to rebuild the widget.</p><p>Since Flutter apps refresh 60 times per second, setting duration to Duration(milliseconds: 16) would make the callback be invoked about once per frame.</p><p>It might be good enough, but 16ms is still an approximation. For a more precise frame-by-frame refresh, I prefer to use a Ticker:</p><pre>createTicker((_) {<br>  // `setState()` based on time<br>});</pre><p>A Ticker is essentially a timer for animations, and we don&#39;t typically interact with it directly. So before we can create one, some additional setup is necessary:</p><pre>class _HealthState extends State&lt;Health&gt;<br>  with SingleTickerProviderStateMixin {<br>  late Ticker ticker;<br><br>  @override<br>  void initState() {<br>    ticker = createTicker((_) {<br>      // `setState()` based on time<br>    });<br>    ticker.start();<br>  }<br><br>  @override<br>  void dispose() {<br>    ticker.dispose();<br>    super.dispose();<br>  }<br><br>  // ...<br>}</pre><p>Although this approach adds some complexity, it offers more accurate refresh timing. In addition, a Ticker automatically stops when the widget is not visible, helping to conserve system resources.</p><h4>Auto-scrolling</h4><p>When a message list exceeds the screen size, users have to manually scroll down to see new messages. This can be frustrating and disrupt the user experience. To improve this, we can implement auto-scrolling for the message list.</p><p>First, let’s create a custom ScrollController to manage the scrolling behavior of the message list:</p><pre>final controller = ScrollController();</pre><p>Apply this controller to the ListView:</p><pre>ListView.builder(<br>  controller: controller,<br>  // ...<br>)</pre><p>Next, we need to decide when to auto-scroll. If the user is browsing earlier messages, we don’t want the list view to suddenly jump to the bottom when a new message arrives.</p><p>To manage this, we can set a flag to true when the user scrolls to the bottom, and change it to false when the user scrolls away. This helps us determine when to trigger auto-scrolling:</p><pre>bool _shouldScroll = false;</pre><p>By listening to the ScrollNotification, we can track whether the list view is currently scrolled to the bottom:</p><pre>NotificationListener&lt;ScrollNotification&gt;(<br>  onNotification: _handleScrollNotification,<br>  child: ListView.builder(<br>    // ...<br>  ),<br>)</pre><p>Wrapping the ListView widget with a NotificationListener allows us to capture scrolling events as they occur.</p><p>In the event handler, we update the _shouldScroll flag based on the scroll position provided by the notification:</p><pre>void _handleScrollNotification(ScrollNotification notification) {<br>  final metrics = notification.metrics;<br><br>  if (metrics.extentAfter == 0) {<br>    setState(() =&gt; _shouldScroll = true);<br>  } else {<br>    setState(() =&gt; _shouldScroll = false);<br>  }<br>}</pre><p>Finally, we need to listen for ScrollMetricsNotification events as well, which requires wrapping another layer of the NotificationListener widget. Note that this is a different type of event, which is triggered when the size of the list view changes, such as when new messages are received or the on-screen keyboard is opened.</p><pre>NotificationListener&lt;ScrollMetricsNotification&gt;(<br>  onNotification: _handleScrollMetricsNotification,<br>  // ...<br>)</pre><p>In the event handler, we use the _shouldScroll flag to determine whether auto-scrolling is needed. If so, we use the previously defined controller to scroll the list view to the bottom:</p><pre>void _handleScrollMetricsNotification(<br>  ScrollMetricsNotification notification) {<br>  final bottom = controller.position.maxScrollExtent;<br><br>  if (_shouldScroll) {<br>    controller.jumpTo(bottom);<br>  }<br>}</pre><p>With these steps, we’ve successfully addressed one of the key interface challenges in our chat app!</p><h4>Cleaning up users</h4><p>Our app does not require a login; instead, it automatically creates an anonymous user at launch. Most of these users are likely to be temporary visitors who use the app once and never return. To prevent the accumulation of inactive users, it’s necessary to periodically purge them.</p><p>Firebase does not enforce a timeout for anonymous users. But we can set our own, such as deleting users who were created more than a month ago via a scheduled task. However, this approach presents two challenges:</p><ul><li>Firebase Authentication doesn’t support complex queries, so we have to retrieve all records before filtering.</li><li>Users who have timed out might not be temporary visitors; they could still be actively using the app.</li></ul><p>To solve the first problem, we can synchronize records from Firebase Authentication to Realtime Database, which would enable us to perform more advanced queries.</p><p>For the second issue, we need to define a criterion to differentiate temporary visitors and permanent users. A simple approach is to base this on whether the user has posted messages — users who have posted are considered permanent.</p><p>So here’s our solution:</p><ul><li>When a user logs in anonymously, their record is synced to the Realtime Database and marked as temporary.</li><li>When the user posts for the first time, their status is updated to permanent.</li></ul><p>With the Cloud Functions, we can create a scheduled task to periodically delete old temporary users, for records in both the Realtime Database and Firebase Authentication.</p><h4>Triggering scheduled tasks locally</h4><p>The Cloud Functions supports scheduled tasks. We can use scheduler.onSchedule() to define a function that runs repeatedly. For example, to run a cleanup task every hour, we can implement it as follows:</p><pre>import { onSchedule } from &#39;firebase-functions/v2/scheduler&#39;;<br><br>export const scheduledCleanup = onSchedule(<br>  &#39;every hour&#39;,<br>  async (event) =&gt; {<br>    await cleanup();<br>  }<br>);</pre><p>However, scheduled functions cannot be triggered in the Local Emulator Suite. To simulate this functionality, we need to use a locally supported trigger method.</p><p>I found HTTP requests convenient since they only require accessing a URL. Therefore, after defining the previous function, I created another one with the same functionality using https.onRequest():</p><pre>import { onRequest } from &#39;firebase-functions/v2/https&#39;;<br><br>export const requestedCleanup = onRequest(<br>  async (req, res) =&gt; {<br>    await cleanup();<br>    res.send(&#39;success&#39;);<br>  }<br>);</pre><p>Both functions perform the same task, so if one works properly, the other should work as well. If you’re unsure, you can always deploy it to the staging server for verification.</p><p>We get the necessary URL when starting the Local Emulator Suite. To trigger the function, simply run a curl command like this:</p><pre>$ curl <a href="http://127.0.0.1:5001/talktive-12345/us-central1/requestedCleanup">http://127.0.0.1:5001/.../requestedCleanup</a></pre><p>This command only run once, but you can easily set up a shell script for periodic execution.</p><p>HTTP requests are not the only way to manually trigger functions; you might also want to explore <a href="https://firebase.google.com/docs/functions/pubsub-events?gen=2nd">Pub/Sub</a> or the <a href="https://firebase.google.com/docs/functions/local-shell">Cloud Functions shell</a>.</p><h4>Atomic increment</h4><p>In this project, I’d like to keep track of various statistical numbers, such as the message count in a room. However, there can be race conditions in the calculations. If two messages are posted at the same time, the message count may end up being incremented by 1 instead of the intended 2.</p><p>To help address this issue, Firebase provides <a href="https://firebase.google.com/docs/reference/node/firebase.database.ServerValue">ServerValue</a>, which ensures that the calculation is an atomic server-side operation. Let&#39;s use it in our Cloud Functions:</p><pre>roomRef.update({<br>  messageCount: admin.database.ServerValue.increment(1);<br>});</pre><p>Unfortunately, ServerValue is not supported in the Local Emulator Suite. As a workaround, you can first retrieve the current value and then manually increment it:</p><pre>roomRef.update({<br>  messageCount = room.messageCount + 1;<br>});</pre><p>To determine whether a function is running with the Local Emulator Suite or on the server, we can check the FUNCTIONS_EMULATOR environment variable, as shown below:</p><pre>if (process.env.FUNCTIONS_EMULATOR === &quot;true&quot;) {<br>  // localhost<br>} else {<br>  // server<br>}</pre><p>This is equivalent to the kDebugMode constant in Dart code.</p><h4>Security rules</h4><p>In Realtime Database Security Rules, permissions at each level are closed by default. If a certain level grants a permission, all its sub-levels inherit that permission as well.</p><p>For example, in the following case, setting .read permission on $messageId is redundant because the parent level has already set the appropriate permission:</p><pre>&quot;$roomId&quot;: {<br>  &quot;.read&quot;: &quot;auth !== null&quot;<br>  &quot;$messageId&quot;: {<br>    &quot;.read&quot;: &quot;auth !== null&quot;<br>  }<br>}</pre><p>At first, I found this concept difficult to understand and prone to errors, but now it makes sense. If you have permission to view a particular node, this certainly implies that you have permission to view all of its contents, which happen to be the child nodes.</p><h4>Writing tests</h4><p>While Flutter’s built-in flutter_test package makes it easy to run unit, widget, and integration tests alongside the Local Emulator Suite, I encountered two challenges specific to our app.</p><p>The first issue arose when I was testing the infinite animations.</p><p>Typically, we use pumpAndSettle() to wait for the interface to be ready and then verify the content displayed on the screen. However, animations implemented with a Ticker are infinite, so they never actually &quot;settle&quot;.</p><p>To work around this, we can use pump() to manually specify a ready time, like this:</p><pre>tester.pump(const Duration(seconds: 2));</pre><p>The downside is that pump() only triggers one frame at a time, and the delay can make the animation look choppy. To avoid this, we can use pumpFrames() instead:</p><pre>tester.pumpFrames(const App(), const Duration(seconds: 2));</pre><p>As the name suggests, pumpFrames() triggers every frame, resulting in a much smoother animation.</p><p>The second problem is how to unit test functions that interact with the Realtime Database.</p><p>For external services, it’s best to use a Fake package to simulate the functionality locally, avoiding unpredictable issues. I found a Fake package on <a href="https://pub.dev/">pub.dev</a> called firebase_database_mocks, but unfortunately, it&#39;s outdated and can&#39;t be installed with flutter pub add.</p><p>This left me with two options:</p><ul><li>Only do integration tests</li><li>Try to upgrade the package</li></ul><p>I didn’t want to miss the opportunity to practice unit testing, so I chose the latter. But the development of the package has been inactive for a while, and it’s unclear if the author would accept pull requests.</p><p>So, I decided to take a temporary approach. I downloaded the project and added it as a local dependency in pubspec.yaml.</p><pre>dev_dependencies:<br>  firebase_database_mocks:<br>    path: ./packages/firebase_database_mocks</pre><p>This way, the third-party code is fully integrated into my project, and I could fix any errors that arise just as I would with my own code.</p><h4>Color themes</h4><p>For a simple Flutter app like this, we only need to provide a seed to generate a set of matching colors:</p><pre>ThemeData(<br>  colorScheme: ColorScheme.fromSeed(<br>    seedColor: Colors.lightGreen,<br>  ),<br>)</pre><p>We can view the generated color palette in the <a href="https://material-foundation.github.io/material-theme-builder/">Material Theme Builder</a>. Since each color has a name, it’s easy to apply the desired colors in our app:</p><pre>Theme.of(context).colorScheme.surfaceContainerLow</pre><p>If you need to support both light and dark themes, you can add an additional property to ThemeData:</p><pre>ThemeData(<br>  colorScheme: ColorScheme.fromSeed(<br>    // ...<br>    brightness: MediaQuery.platformBrightnessOf(context),<br>  ),<br>)</pre><p>Now the app will automatically switch themes based on the system settings.</p><h4>Web apps</h4><p>Flutter makes building a web app easy, allowing you to export a PWA (Progressive Web App) with a single command. However, it’s worth making a few enhancements before releasing it.</p><p>Our app already supports both light and dark themes, but the PWA’s title bar doesn’t automatically adjust to match the theme, leading to color inconsistencies.</p><p>This can be easily fixed. Open web/index.html, and add the following code inside the &lt;head&gt; tag:</p><pre>&lt;meta<br>  name=&quot;theme-color&quot;<br>  media=&quot;(prefers-color-scheme: light)&quot;<br>  content=&quot;#f3f4e9&quot;<br>/&gt;<br>&lt;meta<br>  name=&quot;theme-color&quot;<br>  media=&quot;(prefers-color-scheme: dark)&quot;<br>  content=&quot;#1a1c16&quot;<br>/&gt;</pre><p>These two &lt;meta&gt; tags specify the title bar colors for the light and dark themes, which are chosen from the previously generated color palette.</p><p>Another concern is that Flutter web apps take some time to load, during which a blank page is displayed. To make the loading screen more user friendly, we can add a circular loading spinner.</p><p>Still in the web/index.html file, add the following two &lt;div&gt; tags inside the &lt;body&gt;:</p><pre>&lt;div class=&quot;centered&quot;&gt;<br>  &lt;div class=&quot;loader&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Then, apply CSS styles to customize the appearance:</p><pre>.centered {<br>  position: fixed;<br>  top: 50%;<br>  left: 50%;<br>  transform: translate(-50%, -50%);<br>}<br><br>body {<br>  background-color: #f3f4e9; /* light:surfaceContainerLow */<br>}<br><br>.loader {<br>  width: 50px;<br>  aspect-ratio: 1;<br>  border-radius: 50%;<br>  border: 8px solid #b1d18a; /* light:inversePrimary */<br>  border-right-color: #344e16; /* dark:primaryContainer */<br>  animation: l2 1s infinite linear;<br>}<br>@keyframes l2 {<br>  to {<br>    transform: rotate(1turn);<br>  }<br>}</pre><p>Here, we set the background color, implemented a simple spinner animation using CSS, and centered it on the screen.</p><p>This is just the light version. To create a dark version, you can add a media query, similar to what we did with the title bar colors:</p><pre>@media (prefers-color-scheme: dark) {<br>  body {<br>    background-color: #1a1c16; /* dark:surfaceContainerLow */<br>  }<br><br>  .loader {<br>    border: 8px solid #4b662c; /* dark:inversePrimary */<br>    border-right-color: #cceda4; /* light:primaryContainer */<br>  }<br>}</pre><p>While these are some simple tweaks, they significantly improve the overall user experience of the web app.</p><h4>Programming languages</h4><p>As a Flutter project, most of the code is written in Dart. One exception is Cloud Functions, which uses TypeScript.</p><p>In Dart, I’m used to using the for...in statement to iterate over arrays. When I applied the same structure in Cloud Functions, it resulted in an error! Instead of returning the array items, I got keys like 0, 1, and 2.</p><p>In TypeScript, to iterate over the items in an array, you should use the for...of statement. It took me quite a while to figure out what was going wrong.</p><h4>Conclusion</h4><p>Like the project itself, this article ended up being longer than I expected, so thank you for sticking with it to the end!</p><p>Learning Flutter and Firebase has been a lot of fun, and bringing this project to life has been equally rewarding. I hope you enjoyed reading about it.</p><p>I created this project out of a desire to chat anonymously with strangers — something I can’t do on my own. So if you’re interested, feel free to <a href="https://open.talktive.app/">drop by</a> anytime; who knows, we might just run into each other in the app!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f0a2f0f889" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-challenges-of-building-a-simple-chat-app-with-flutter-and-firebase-b9f0a2f0f889">The Challenges of Building a Simple Chat App with Flutter and Firebase</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>