<?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 Stanislav Sopov on Medium]]></title>
        <description><![CDATA[Stories by Stanislav Sopov on Medium]]></description>
        <link>https://medium.com/@stassop?source=rss-457b4af4514b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jbh_4ZTRkp50P4VN6SgOzQ.jpeg</url>
            <title>Stories by Stanislav Sopov on Medium</title>
            <link>https://medium.com/@stassop?source=rss-457b4af4514b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:11:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stassop/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter Calendar]]></title>
            <link>https://stassop.medium.com/flutter-calendar-8ff6f6f28915?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ff6f6f28915</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 16:34:04 GMT</pubDate>
            <atom:updated>2026-08-05T03:58:22.504Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a Material 3 Themeable Event Calendar Widget</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w57FLzquee66Qx9h" /><figcaption>Photo by <a href="https://unsplash.com/@chaurasia?utm_source=medium&amp;utm_medium=referral">Chandan Chaurasia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Why Build a Calendar in Flutter?</strong></h3><p>Flutter Material 3 still lacks an official, fully featured event calendar widget. This often leads developers to rely on large third-party packages. Our goal is to build a simple, robust, customizable calendar.</p><p>To achieve this, we use standard Flutter widgets wherever possible. This avoids reinventing the wheel, reduces unnecessary complexity, and benefits from Flutter’s built-in optimisations.</p><p>We also focus on making the widget fully themeable. It integrates seamlessly with Flutter’s Material 3 theming and adapts to your app’s existing design system and color scheme.</p><h3>UX/UI</h3><p>Events are displayed as bars spanning their scheduled dates, with the event title shown inside. Each day is divided into vertically scrollable time slots making the interface mobile friendly.</p><p>This layout provides a clear visual representation of each event’s timeframe, makes overlapping events easy to identify, allowing users quickly understand their schedule at a glance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*IMon65FXQW6QqQBf96i-zg.gif" /><figcaption>See complete example <a href="https://github.com/stassop/flutter_event_calendar">here</a></figcaption></figure><h3><strong>Data Model</strong></h3><p>We start by defining a clear interface contract so our calendar component knows what data to expect from every custom event class, regardless of its implementation.</p><pre>abstract interface class CalendarEvent {<br>  String get id;<br>  DateTimeRange get dates;<br>  String get title;<br>  String get description;<br>}</pre><h3>Event Lanes</h3><p>To preserve visual continuity and readability, events are assigned a consistent lane throughout their duration. This keeps each event in the same position across multiple days and week rows<em>.</em></p><p>This function builds a map of calendar dates to event lanes. null placeholders buffer overlapping events, ensuring events stay in their respective lanes in every grid cell.</p><pre>  Map&lt;DateTime, List&lt;CalendarEvent?&gt;&gt; _getEventLaneMap() {<br>    final sortedEvents = List&lt;CalendarEvent&gt;.from(widget.events)<br>      ..sort((a, b) =&gt; a.dates.start.compareTo(b.dates.start));<br><br>    final map = &lt;DateTime, List&lt;CalendarEvent?&gt;&gt;{};<br>    if (sortedEvents.isEmpty) return map;<br><br>    DateTime? clusterEndDay;<br>    final clusterDays = &lt;DateTime&gt;{};<br>    int maxLaneInCluster = 0;<br>    final laneEnds = &lt;DateTime&gt;[];<br><br>    void padCluster() {<br>      for (final day in clusterDays) {<br>        final dayLanes = map[day]!;<br>        while (dayLanes.length &lt;= maxLaneInCluster) {<br>          dayLanes.add(null);<br>        }<br>      }<br>    }<br><br>    for (final event in sortedEvents) {<br>      final startDay = DateTime(<br>        event.dates.start.year,<br>        event.dates.start.month,<br>        event.dates.start.day,<br>      );<br>      final endDay = DateTime(<br>        event.dates.end.year,<br>        event.dates.end.month,<br>        event.dates.end.day,<br>      );<br><br>      if (clusterEndDay != null &amp;&amp; startDay.isAfter(clusterEndDay)) {<br>        padCluster();<br>        clusterDays.clear();<br>        laneEnds.clear();<br>        maxLaneInCluster = 0;<br>      }<br><br>      if (clusterEndDay == null || endDay.isAfter(clusterEndDay)) {<br>        clusterEndDay = endDay;<br>      }<br><br>      // Check strict date boundaries to prevent same-day events from overwriting each other<br>      int laneIndex = laneEnds.indexWhere(<br>        (endTime) =&gt; startDay.isAfter(endTime),<br>      );<br><br>      if (laneIndex == -1) {<br>        // Track lane availability by date, not exact time<br>        laneEnds.add(endDay);<br>        laneIndex = laneEnds.length - 1;<br>      } else {<br>        laneEnds[laneIndex] = endDay;<br>      }<br><br>      if (laneIndex &gt; maxLaneInCluster) {<br>        maxLaneInCluster = laneIndex;<br>      }<br><br>      for (<br>        DateTime day = startDay;<br>        !day.isAfter(endDay);<br>        // Safely iterate dates avoiding Daylight Saving Time overlaps or skips<br>        day = DateTime(day.year, day.month, day.day + 1)<br>      ) {<br>        clusterDays.add(day);<br>        <br>        final dayLanes = map.putIfAbsent(day, () =&gt; &lt;CalendarEvent?&gt;[]);<br><br>        while (dayLanes.length &lt;= laneIndex) {<br>          dayLanes.add(null);<br>        }<br><br>        dayLanes[laneIndex] = event;<br>      }<br>    }<br><br>    padCluster();<br><br>    return map;<br>  }</pre><h3>Event Tile</h3><p>We use GridView because it’s an effective way to build grid layouts in Flutter using familiar, optimized widgets. At the same time, we want event titles to span multiple days and week rows.</p><p>To achieve this, we render the title in every day cell an event occupies and shift it horizontally by the day index multiplied by the day width. This creates the appearance of one continuous title.</p><pre>Widget _buildEventTile({<br>  required BuildContext context,<br>  required DateTime day,<br>  required CalendarEvent event,<br>  required double eventWidth,<br>  required double eventHeight,<br>}) {<br>  final theme = Theme.of(context);<br>  final dayIndex =<br>      DateTime(day.year, day.month, day.day)<br>          .difference(<br>            DateTime(<br>              event.dates.start.year,<br>              event.dates.start.month,<br>              event.dates.start.day,<br>            ),<br>          )<br>          .inDays;<br>  final textOffset = dayIndex * eventWidth;<br>  final isFirstDay = DateUtils.isSameDay(event.dates.start, day);<br>  final isLastDay = DateUtils.isSameDay(event.dates.end, day);<br>  final isSingleDay = isFirstDay &amp;&amp; isLastDay;<br><br>  return Tooltip(<br>    padding: const EdgeInsets.all(8),<br>    margin: const EdgeInsets.all(8),<br>    decoration: BoxDecoration(<br>      color: theme.colorScheme.inverseSurface,<br>      borderRadius: BorderRadius.circular(8),<br>    ),<br>    richMessage: TextSpan(<br>      children: [<br>        TextSpan(<br>          text: &#39;${event.title}\n&#39;,<br>          style: theme.textTheme.titleSmall?.copyWith(<br>            color: theme.colorScheme.onInverseSurface,<br>          ),<br>        ),<br>        WidgetSpan(child: const SizedBox(height: 8)),<br>        TextSpan(<br>          text: &#39;${DateFormat.yMMMd().format(event.dates.start)} - &#39;<br>            &#39;${DateFormat.yMMMd().format(event.dates.end)}\n&#39;,<br>          style: theme.textTheme.bodySmall?.copyWith(<br>            color: theme.colorScheme.onInverseSurface,<br>          ),<br>        ),<br>        WidgetSpan(child: const SizedBox(height: 8)),<br>        TextSpan(<br>          text: event.description,<br>          style: theme.textTheme.bodySmall?.copyWith(<br>            color: theme.colorScheme.onInverseSurface,<br>          ),<br>        ),<br>      ],<br>    ),<br>    preferBelow: false,<br>    child: Container(<br>      clipBehavior: Clip.hardEdge,<br>      height: eventHeight,<br>      decoration: BoxDecoration(<br>        color: theme.colorScheme.primary,<br>        borderRadius: isSingleDay<br>            ? BorderRadius.circular(8)<br>            : isFirstDay<br>                ? const BorderRadius.horizontal(left: Radius.circular(8))<br>                : isLastDay<br>                    ? const BorderRadius.horizontal(right: Radius.circular(8))<br>                    : null,<br>      ),<br>      child: Transform.translate(<br>        offset: Offset(-textOffset, 0),<br>        child: Align(<br>          alignment: Alignment.centerLeft,<br>          child: Text(<br>            event.title,<br>            style: theme.textTheme.labelSmall?.copyWith(<br>              color: theme.colorScheme.onPrimary,<br>              height: 1,<br>            ),<br>            maxLines: 1,<br>            softWrap: false,<br>            overflow: TextOverflow.visible,<br>          ),<br>        ),<br>      ),<br>    ),<br>  );<br>}</pre><h3>Calendar Grid</h3><p>With the event lane map in place, building the calendar becomes straightforward. We iterate over the month days generated earlier and render each one using a seven-column GridView.</p><p>Since lane positions are already determined and empty lanes are buffered by null placeholders, we can simply render each day&#39;s events in a Column and fill empty lanes with SizedBox.</p><pre>Widget _buildCalendarGrid(<br>  BuildContext context,<br>  List&lt;DateTime&gt; days,<br>  Map&lt;DateTime, List&lt;CalendarEvent?&gt;&gt; eventMap,<br>) {<br>  return GridView.builder(<br>    shrinkWrap: true,<br>    physics: const NeverScrollableScrollPhysics(),<br>    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(<br>      crossAxisCount: 7,<br>    ),<br>    itemCount: days.length,<br>    itemBuilder: (context, index) {<br>      final day = days[index];<br>      final isToday = DateUtils.isSameDay(day, DateTime.now());<br>      final isCurrentMonth = day.month == _currentDate.month;<br>      final dayEvents = [<br>        ...(eventMap[DateTime(day.year, day.month, day.day)] ??<br>            const &lt;CalendarEvent&gt;[]),<br>      ];<br>      final theme = Theme.of(context);<br>      final dateColor = isCurrentMonth<br>          ? (isToday<br>              ? theme.colorScheme.onPrimaryContainer<br>              : theme.textTheme.bodyLarge?.color)<br>          : theme.disabledColor;<br><br>      return InkWell(<br>        onTap: () {<br>          Navigator.of(context).push(<br>            MaterialPageRoute(<br>              builder: (_) { <br>                final events = dayEvents.whereType&lt;CalendarEvent&gt;().toList();<br>                return CalendarDay(<br>                  date: day,<br>                  events: events,<br>                  onTapEvent: widget.onTapEvent,<br>                ); <br>              },<br>            ),<br>          );<br>        },<br>        child: Column(<br>          children: [<br>            Center(<br>              child: Text(<br>                &#39;${day.day}&#39;,<br>                style: theme.textTheme.bodyLarge?.copyWith(<br>                  color: dateColor,<br>                  fontWeight: isToday ? FontWeight.bold : null,<br>                ),<br>              ),<br>            ),<br>            if (dayEvents.isNotEmpty)<br>              Expanded(<br>                child: LayoutBuilder(<br>                  builder: (context, constraints) {<br>                    final dayHeight = constraints.maxHeight;<br>                    final eventWidth = constraints.maxWidth;<br>                    final eventHeight = (dayHeight - (dayEvents.length - 1) * 2) / dayEvents.length;<br><br>                    return Column(<br>                      spacing: 2,<br>                      children: [<br>                        for (var event in dayEvents)<br>                          if (event != null)<br>                            _buildEventTile(<br>                              context: context,<br>                              day: day,<br>                              event: event,<br>                              eventWidth: eventWidth,<br>                              eventHeight: eventHeight,<br>                            )<br>                          else<br>                            SizedBox(height: eventHeight),<br>                      ],<br>                    );<br>                  },<br>                ),<br>              ),<br>          ],<br>        ),<br>      );<br>    },<br>  );<br>}</pre><h3>Day View</h3><p>Implementing the CalendarDay view is relatively straightforward. We draw a vertical hour grid inside a SingleChildScrollView, creating a mobile-friendly interface with a clear visual representation of time.</p><p>We use Stack to position event tiles over the hour grid based on their time spans. Each tile displays the event title and description, and handles user interaction through the onTapEvent callback.</p><pre>Widget _buildEventTile({<br>  required BuildContext context, <br>  required CalendarEvent event,<br>  required double eventWidth,<br>  required int index,<br>}) {<br>  final theme = Theme.of(context);<br>  final isStartDay = DateUtils.isSameDay(event.dates.start, date);<br>  final startHourDecimal = isStartDay<br>      ? event.dates.start.hour + (event.dates.start.minute / 60.0)<br>      : 0.0;<br><br>  final isEndDay = DateUtils.isSameDay(event.dates.end, date);<br>  final endHourDecimal = isEndDay<br>      ? event.dates.end.hour + (event.dates.end.minute / 60.0)<br>      : 24.0;<br><br>  final isSingleDay = isStartDay &amp;&amp; isEndDay;<br><br>  final top = startHourDecimal * hourHeight;<br>  final left = index * (eventWidth + 2);<br><br>  final height = ((endHourDecimal - startHourDecimal).clamp(0.5, 24.0)) * hourHeight;<br><br>  final formattedDateTime = &#39;${DateFormat.MMMd().add_j().format(event.dates.start)} - &#39;<br>      &#39;${DateFormat.MMMd().add_j().format(event.dates.end)}&#39;;<br><br>  return Positioned(<br>    top: top,<br>    left: left,<br>    child: InkWell(<br>      onTap: () {<br>        onTapEvent?.call(event);<br>      },<br>      child: Container(<br>        height: height,<br>        width: eventWidth,<br>        clipBehavior: Clip.hardEdge,<br>        padding: const EdgeInsets.all(8),<br>        decoration: BoxDecoration(<br>          color: theme.colorScheme.primaryContainer,<br>          borderRadius: isSingleDay<br>              ? BorderRadius.circular(8)<br>              : isStartDay<br>                  ? const BorderRadius.vertical(top: Radius.circular(8))<br>                  : isEndDay<br>                      ? const BorderRadius.vertical(bottom: Radius.circular(8))<br>                      : null,<br>        ),<br>        child: OverflowBox(<br>          alignment: Alignment.topLeft,<br>          maxHeight: double.infinity,<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            mainAxisAlignment: MainAxisAlignment.start,<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              Text(<br>                event.title,<br>                style: theme.textTheme.titleSmall?.copyWith(<br>                  color: theme.colorScheme.onPrimaryContainer,<br>                ),<br>              ),<br>              const SizedBox(height: 8),<br>              Text(<br>                formattedDateTime,<br>                style: theme.textTheme.bodySmall?.copyWith(<br>                  color: theme.colorScheme.onPrimaryContainer,<br>                ),<br>              ),<br>              const SizedBox(height: 8),<br>              Text(<br>                event.description,<br>                style: theme.textTheme.bodySmall?.copyWith(<br>                  color: theme.colorScheme.onPrimaryContainer,<br>                ),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    ),<br>  );<br>}</pre><h3>Putting It All Together</h3><p>Our Calendar widget build method is surprisingly simple. We generate the calendar days based on the current date, then render the header and calendar grid.</p><p>When the displayed month or year changes, we call the onChanged callback with the current date range. When a day is tapped, we push a new route containing CalendarDay with its respective events.</p><pre>Widget build(BuildContext context) {<br>  final firstDayOfMonth = DateTime(_currentDate.year, _currentDate.month, 1);<br>  final daysInMonth = DateUtils.getDaysInMonth(<br>    _currentDate.year,<br>    _currentDate.month,<br>  );<br><br>  final days = &lt;DateTime&gt;[];<br>  final firstWeekday = firstDayOfMonth.weekday;<br><br>  for (int i = 1; i &lt; firstWeekday; i++) {<br>    days.add(firstDayOfMonth.subtract(Duration(days: firstWeekday - i)));<br>  }<br><br>  for (int i = 0; i &lt; daysInMonth; i++) {<br>    days.add(DateTime(_currentDate.year, _currentDate.month, i + 1));<br>  }<br><br>  while (days.length % 7 != 0) {<br>    // Safely increment date to avoid Daylight Saving Time bugs<br>    days.add(DateTime(days.last.year, days.last.month, days.last.day + 1));<br>  }<br><br>  final eventLaneMap = _getEventLaneMap();<br><br>  return Padding(<br>    padding: const EdgeInsets.all(8),<br>    child: Column(<br>      children: [<br>        _buildHeader(context),<br>        const SizedBox(height: 16),<br>        _buildWeekdayLabels(context),<br>        const SizedBox(height: 8),<br>        _buildCalendarGrid(context, days, eventLaneMap),<br>      ],<br>    ),<br>  );<br>}</pre><h3>Using the Calendar</h3><p>You simply define a dedicated class implementing our calendar event interface. Then, instantiate the calendar within your scaffold body alongside chronological date constraints.</p><pre>class MyEvent implements CalendarEvent { <br>  // Implementation details here<br>}</pre><pre>// Inside your build method:<br>Calendar&lt;MyEvent&gt;(<br>  events: myEvents,<br>  startDate: DateTime.now(),<br>  startYear: 2020,<br>  endYear: 2030,<br>  onChanged: (range) =&gt; fetchEvents(range),<br>  onTapEvent: (event) =&gt; showEventDetails(event),<br>)</pre><h3>Conclusion</h3><p>Building a custom calendar gives you complete control over rendering and user experience. It perfectly adapts to your theme without unnecessarily bloating your project dependencies or relying on external packages.</p><p>You can find the complete code <a href="https://github.com/stassop/flutter_event_calendar">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ff6f6f28915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Flutter Riverpod 3.0]]></title>
            <link>https://stassop.medium.com/understanding-riverpod-providers-132ea7c72203?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/132ea7c72203</guid>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-riverpod]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 14:14:30 GMT</pubDate>
            <atom:updated>2026-03-06T14:04:19.428Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Simple Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H5qBaI3F3rqPRbJ9" /><figcaption>Photo by <a href="https://unsplash.com/@edge2edgemedia?utm_source=medium&amp;utm_medium=referral">Edge2Edge Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Riverpod is a powerful Flutter state management library that simplifies handling data dependencies and state changes. At its core, Riverpod uses providers to create and manage state.</p><p>Each provider serves a specific purpose, and selecting the right one is crucial for writing clean and efficient code. It can be confusing at first to understand the different types of providers and when to use each.</p><p>This guide will demystify Riverpod’s modern provider set, offering clear explanations to help you confidently decide which one to use for any given situation in the new ecosystem.</p><h3>Core Providers</h3><h4>Provider</h4><p>The most fundamental provider, used for read-only, synchronous state. It functions like a constant or a value derived from other providers that doesn’t change on its own. It is perfect for configuration settings or filtered lists, recomputing only when its dependencies change.</p><h4>Notifier &amp; NotifierProvider</h4><p>The modern replacement for StateProvider and StateNotifierProvider in Riverpod 3.0. It pairs a Notifier class containing business logic with its associated state. State is modified strictly through methods within the class, ensuring predictable and encapsulated mutations.</p><h4>AsyncNotifier &amp; AsyncNotifierProvider</h4><p>The go-to choice for asynchronous state that requires side effects or manual updates. It automatically manages loading, data, and error states while allowing you to define methods to mutate data. Use this instead of FutureProvider when the data needs to be modified after the initial fetch.</p><h4>FutureProvider &amp; StreamProvider</h4><p>These handle “read-only” asynchronous data and manage the three states of async operations: loading, data, and error. FutureProvider is for one-time events like fetching an API, while StreamProvider is for continuous data like real-time database updates.</p><h4>Modifiers: .family and .autoDispose</h4><p>The .family modifier allows a provider to accept external arguments, such as a user ID, to create unique instances. The .autoDispose modifier is vital for memory management, as it automatically clears the provider’s state once it is no longer being watched by the UI.</p><h4>Provider vs. Notifier</h4><p>A Provider is the recipe for accessing state, while the Notifier is the engine that manages how that state lives and changes. This separation ensures your UI stays lean by simply watching the provider while the Notifier handles the heavy lifting and logic.</p><h3>Provider</h3><h4><strong>What It’s For</strong></h4><p>Provider is for <strong>read-only, synchronous values</strong> that don&#39;t change over time. It is the simplest type of provider and remains the gold standard for dependency injection.</p><h4><strong>When to Use</strong></h4><ul><li><strong>Injecting a Repository:</strong> When you have a service class (like an ApiClient) that doesn&#39;t hold mutable state, use a Provider to make it available.</li><li><strong>Accessing Configuration:</strong> For values constant throughout the app’s lifecycle, like an API key, a Provider is the right choice.</li><li><strong>Derived Synchronous Values:</strong> If you need to derive a value from another provider — like filtering a list — a Provider with ref.watch is the perfect tool.</li></ul><h4><strong>When Not to Use</strong></h4><ul><li><strong>Mutable State:</strong> Do not use Provider for state that needs to change. <strong>Alternative:</strong> Use NotifierProvider.</li><li><strong>Asynchronous Operations:</strong> Provider cannot handle Future values or display loading states. <strong>Alternative:</strong> Use FutureProvider or AsyncNotifierProvider.</li></ul><h3>NotifierProvider</h3><h4><strong>What It’s For</strong></h4><p>NotifierProvider is the primary tool for <strong>synchronous, mutable state</strong>. It replaces the discouraged StateProvider and StateNotifierProvider by providing a single, unified way to manage logic and state together.</p><h4><strong>When to Use</strong></h4><ul><li><strong>UI State:</strong> For a counter, a boolean toggle, or the state of a form, Notifier allows you to group the state and its modification methods (e.g., increment(), toggle()) in one place.</li><li><strong>Complex Business Logic:</strong> Use this for shopping carts or authentication filters where the state transitions follow specific rules. It keeps your logic out of the UI and inside a dedicated class.</li><li><strong>Managing Selections:</strong> If you need to track which item in a list is selected, a Notifier can hold the ID and provide a method to update it.</li></ul><h4><strong>When Not to Use</strong></h4><ul><li><strong>Asynchronous Initial State:</strong> If your initial state depends on a Future (like fetching a list from a database), Notifier is not the best fit. <strong>Alternative:</strong> Use AsyncNotifierProvider.</li><li><strong>Static Data:</strong> If the data never changes, a Notifier adds unnecessary complexity. <strong>Alternative:</strong> Use a simple Provider.</li></ul><h3>AsyncNotifierProvider</h3><h4><strong>What It’s For</strong></h4><p>AsyncNotifierProvider is the workhorse for <strong>asynchronous state that can be modified</strong>. It manages an AsyncValue (loading/data/error) and allows you to perform &quot;side effects&quot; like refreshing or updating remote data.</p><h4><strong>When to Use</strong></h4><ul><li><strong>CRUD Operations:</strong> If you fetch a list of “To-Dos” from an API and need methods to addTodo() or deleteTodo(), AsyncNotifier is the correct choice.</li><li><strong>Authentication Flow:</strong> Managing login/logout where the state transitions involve network requests. The Notifiercan handle the Future while exposing the current user state.</li><li><strong>Manual Refreshing:</strong> When you need a “pull-to-refresh” feature that re-runs an asynchronous fetch manually.</li></ul><h4><strong>When Not to Use</strong></h4><ul><li><strong>Simple Fetching:</strong> If you only need to read data once and never modify it within the app. <strong>Alternative:</strong> Use FutureProvider.</li><li><strong>Synchronous State:</strong> If your data is already available in memory and doesn’t require a Future. <strong>Alternative:</strong> Use NotifierProvider.</li></ul><h3>FutureProvider &amp; StreamProvider</h3><h4><strong>What It’s For</strong></h4><p>These are essential for handling <strong>read-only asynchronous data</strong>. They automatically manage the loading, data, and error states, making it easy to build responsive UIs.</p><h4><strong>When to Use</strong></h4><ul><li><strong>Remote Data Fetching:</strong> A FutureProvider is perfect for fetching data from an API where the UI just needs to display the result or an error.</li><li><strong>Real-time Updates:</strong> If your app listens to a live chat feed or a Firebase stream, use StreamProvider. It automatically rebuilds the UI with each new value.</li><li><strong>Initial Assets:</strong> Loading a JSON configuration file or local assets before the main UI is built is a great use case for FutureProvider.</li></ul><h4><strong>When Not to Use</strong></h4><ul><li><strong>State Modification:</strong> FutureProvider is not designed for state that you intend to change manually. <strong>Alternative: </strong>Use AsyncNotifierProvider to allow for data mutations.</li><li><strong>Complex Logic:</strong> If you need to perform complex business rules after the data arrives. <strong>Alternative:</strong> Use AsyncNotifierProvider to encapsulate that logic.</li></ul><h3>Conclusion</h3><p>Choosing the right Riverpod provider in the 3.0 era centers on moving toward <strong>Notifiers</strong>. By consolidating your logic into Notifier and AsyncNotifier, you create a more predictable and testable codebase.</p><p>Understanding these modern patterns allows you to select the best tool for the job, ensuring your Flutter app is robust, scalable, and easy for other developers to navigate.</p><p>You can learn more about what’s new in Riverpod 3.0 in <a href="https://riverpod.dev/docs/whats_new#stateproviderstatenotifierprovider-and-changenotifierprovider-are-discouraged-and-moved-to-a-different-import">this article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132ea7c72203" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free-Tier Mapping and Location Search in Flutter]]></title>
            <link>https://stassop.medium.com/free-tier-mapping-and-location-search-in-flutter-3d99b2a35175?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d99b2a35175</guid>
            <category><![CDATA[location-search]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[leaflet]]></category>
            <category><![CDATA[location-services]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 17:09:26 GMT</pubDate>
            <atom:updated>2025-01-24T17:31:17.862Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create Stunning Maps and Seamless Location Search in Flutter — For Free!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JM5gmQ9vbicgThR" /><figcaption>Photo by <a href="https://unsplash.com/@hjkp?utm_source=medium&amp;utm_medium=referral">henry perks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Synopsis</h3><p>Integrating mapping and location search into apps can be a significant hurdle for startups. Many popular services involve complex setups, confusing pricing, and can quickly become expensive.</p><p>Startups need easy-to-implement, cost-effective solutions that allow them to experiment and refine their app without the fear of accruing significant mapping expenses.</p><p>This article guides you through building a professional-looking and user-friendly location search widget in Flutter. We’ll explore how to leverage the power of free-tier mapping to create a superb user experience.</p><h3>Example App</h3><p>Here’s what we’ll be building:</p><figure><img alt="https://github.com/stassop/flutter_location_search" src="https://cdn-images-1.medium.com/max/295/1*X0JWONGDVgn7ZB4xSOFDXQ.gif" /><figcaption><a href="https://github.com/stassop/flutter_location_search">https://github.com/stassop/flutter_location_search</a></figcaption></figure><p>Let’s consider the basic requirements for our app:</p><ul><li>Display a basic interactive map (e.g., using a free-tier mapping service like Mapbox or Leaflet).</li><li>Allow users to pan and zoom the map.</li><li>Allow users to recenter on the previously selected location after map movements.</li><li>Allow users to see their current location (with user permission).</li><li>Allow users to search for a location, select a search result, and show it on the map marked by a location pin.</li><li>When a location pin is tapped, display location details in a bottom sheet.</li><li>Allow users to open the currently selected location in the default maps app.</li></ul><p>You can find the complete example <a href="https://github.com/stassop/flutter_location_search">here</a>.</p><h3>Flutter Map</h3><p>The <a href="https://docs.fleaflet.dev/">Flutter Map</a> package leverages the power of <a href="https://leafletjs.com/">Leaflet maps</a> to bring interactive maps to your Flutter applications. This open-source package provides a rich and highly customizable feature set.</p><p>While Flutter Map is commonly used with Leaflet maps, it’s designed to be agnostic to the underlying map provider. This flexibility allows developers to potentially integrate with other mapping services like Mapbox.</p><p>Install the <a href="https://pub.dev/packages/flutter_map/install">Flutter Map</a> package:</p><pre>flutter pub add flutter_map</pre><h3>Flutter Geolocator</h3><p>The <a href="https://pub.dev/packages/geolocator">Flutter Geolocator</a> package simplifies location services within your Flutter apps. It provides access to device location data, including current position and location updates.</p><p>Geolocator supports various providers, offers options for permission handling, and enhances user privacy, making it essential for building location-aware applications.</p><p>Install the <a href="https://pub.dev/packages/geolocator/install">Geolocator</a> package:</p><pre>flutter pub add geolocator</pre><p>We also need to add location permissions in order for it to work.</p><p>For iOS, add this to ios/Runner/Info.plist</p><pre>&lt;key&gt;NSLocationWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs access to location when open.&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs access to location when in the background.&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysAndWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs access to location when open and in the background.&lt;/string&gt;</pre><p>For Android, add this to android/app/src/main/AndroidManifest.xml</p><pre>&lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_BACKGROUND_LOCATION&quot;/&gt;</pre><h3>LatLong Library</h3><p>The <a href="https://pub.dev/packages/latlong2">LatLong</a> package is a lightweight library for performing common geospatial calculations in Dart. It provides a simple and intuitive API for working with geographical coordinates (latitude and longitude).</p><p>It enables developers to easily calculate distances between points, determine bearings, and perform other essential geospatial operations, and is extensively used by Flutter Map.</p><p>Install the <a href="https://pub.dev/packages/latlong2/install">LatLong</a> package:</p><pre>flutter pub add latlong2</pre><h3>Location Class</h3><p>The Location class serves as a model to encapsulate location details within our application. This class is broadly based the <a href="https://datatracker.ietf.org/doc/html/rfc7946">GeoJSON</a> standard, providing a standardized way to represent and exchange location data.</p><p>Note that Location model leverages the <a href="https://pub.dev/packages/equatable">Equatable</a> package, allowing for efficient comparison to other locations. This simplifies tasks like identifying duplicates and optimizing location related logic.</p><pre>import &#39;package:flutter_map/flutter_map.dart&#39;;<br>import &#39;package:latlong2/latlong.dart&#39;;<br>import &#39;package:equatable/equatable.dart&#39;;<br><br>// Our Locaiton model class combines data from OpenStreetMap GeoJSON and LatLng coordinates<br>// At the very least, we need the latitude and longitude of a location, hence they are required<br>class Location {<br>  Location({<br>    required this.latitude,<br>    required this.longitude,<br>    this.borough,<br>    this.bounds,<br>    this.city,<br>    this.country,<br>    this.countryCode,<br>    this.displayName,<br>    this.houseNumber,<br>    this.municipality,<br>    this.name,<br>    this.neighbourhood,<br>    this.postcode,<br>    this.road,<br>    this.state,<br>    this.suburb,<br>  });<br><br>  final LatLngBounds? bounds;<br>  final String? borough;<br>  final String? city;<br>  final String? country;<br>  final String? countryCode;<br>  final String? displayName;<br>  final String? houseNumber;<br>  final double latitude;<br>  final double longitude;<br>  final String? municipality;<br>  final String? name;<br>  final String? neighbourhood;<br>  final String? postcode;<br>  final String? road;<br>  final String? state;<br>  final String? suburb;<br><br>  LatLng get latLng =&gt; LatLng(latitude, longitude);<br><br>  // Make it possible for Equatable to compare two Location objects<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        borough,<br>        bounds,<br>        city,<br>        country,<br>        countryCode,<br>        displayName,<br>        houseNumber,<br>        latitude,<br>        longitude,<br>        municipality,<br>        name,<br>        neighbourhood,<br>        postcode,<br>        road,<br>        state,<br>        suburb,<br>      ];<br><br>  factory Location.fromGeoJson(Map&lt;String, dynamic&gt; geoJson) {<br>    // We assume that the GeoJSON data always has the same structure<br>    // so we don&#39;t apply any checks here, but you should do it in a real app<br>    final address = geoJson[&#39;properties&#39;][&#39;address&#39;];<br>    final bounds = List&lt;double&gt;.from(geoJson[&#39;bbox&#39;]);<br>    // Longitude precedes latitude in GeoJSON<br>    final latLngBounds = LatLngBounds(<br>        LatLng(<br>          bounds[1],<br>          bounds[0],<br>        ),<br>        LatLng(<br>          bounds[3],<br>          bounds[2],<br>        ));<br><br>    return Location(<br>      bounds: latLngBounds,<br>      city: address[&#39;city&#39;],<br>      country: address[&#39;country&#39;],<br>      countryCode: address[&#39;country_code&#39;],<br>      displayName: geoJson[&#39;properties&#39;][&#39;display_name&#39;],<br>      houseNumber: address[&#39;house_number&#39;],<br>      latitude: geoJson[&#39;geometry&#39;][&#39;coordinates&#39;][1],<br>      longitude: geoJson[&#39;geometry&#39;][&#39;coordinates&#39;][0],<br>      name: geoJson[&#39;properties&#39;][&#39;name&#39;],<br>      neighbourhood: address[&#39;neighbourhood&#39;],<br>      postcode: address[&#39;postcode&#39;],<br>      road: address[&#39;road&#39;],<br>      state: address[&#39;state&#39;],<br>      suburb: address[&#39;suburb&#39;],<br>    );<br>  }<br><br>  @override<br>  String toString() {<br>    return displayName ?? name ?? &#39;$latitude, $longitude&#39;;<br>  }<br>}</pre><h3>Geolocation Class</h3><p>The Geolocation class encapsulates the core logic for accessing and handling location data. This class is also responsible for making network requests to the geolocation service.</p><p>Note that every request must include a User-Agent header. This header identifies your application to the server, preventing requests from being rejected by the <a href="https://nominatim.org/release-docs/latest/api/Overview/">Nominatim</a> server.</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;dart:convert&#39;;<br><br>import &#39;package:geolocator/geolocator.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;package:intl/intl.dart&#39;;<br><br>import &#39;location.dart&#39;;<br><br>// We use the OpenStreetMap API for geocoding and reverse geocoding<br>Future&lt;dynamic&gt; makeOpenStreetMapRequest({<br>  required String path,<br>  Map&lt;String, dynamic&gt;? queryParams,<br>}) async {<br>  try {<br>    // Imperatively convert all query params to strings to avoid type errors<br>    if (queryParams != null) {<br>      queryParams =<br>          queryParams.map((key, value) =&gt; MapEntry(key, value.toString()))<br>              as Map&lt;String, dynamic&gt;;<br>    }<br><br>    // Pass the user&#39;s locale to the API to get the results in the correct language<br>    final language = Intl.getCurrentLocale().split(&#39;_&#39;).first;<br><br>    // Create a request object with the OpenStreetMap API URL and parameters<br>    final request = http.Request(<br>        &#39;GET&#39;,<br>        Uri.https(&#39;nominatim.openstreetmap.org&#39;, path, {<br>          if (queryParams != null) ...queryParams,<br>          &#39;format&#39;: &#39;geojson&#39;,<br>          &#39;addressdetails&#39;: &#39;1&#39;,<br>          &#39;accept-language&#39;: language,<br>        }))<br>      ..headers.addAll({<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        &#39;Accept&#39;: &#39;application/json&#39;,<br>        &#39;User-Agent&#39;: &#39;MyApp/1.0 (https://my.app)&#39;,<br>      })<br>      ..followRedirects = false<br>      ..persistentConnection = false;<br>    // print(&#39;Requesting: ${request.url}&#39;);<br><br>    // Send the request and get the StreamedResponse with a timeout<br>    final streamedResponse =<br>        await request.send().timeout(const Duration(seconds: 5), onTimeout: () {<br>      throw TimeoutException(&#39;Request timed out&#39;);<br>    });<br><br>    // Convert the StreamedResponse into a complete response<br>    final http.Response response = await http.Response.fromStream(streamedResponse);<br><br>    // Check the response status and handle accordingly<br>    if (response.statusCode &gt;= 200 &amp;&amp; response.statusCode &lt; 300) {<br>      final ContentType? contentType = response.headers[&#39;content-type&#39;] != null<br>          ? ContentType.parse(response.headers[&#39;content-type&#39;]!)<br>          : null;<br>      // Check if the response is JSON<br>      if (contentType?.mimeType == &#39;application/json&#39;) {<br>        // Expect the response to have a JSON body<br>        final data = jsonDecode(response.body);<br>        // Check if the JSON body has an error field<br>        if (data is Map &amp;&amp; data.containsKey(&#39;error&#39;)) {<br>          throw Exception(&#39;Server error: ${data[&#39;error&#39;]}&#39;);<br>        } else {<br>          return data;<br>        }<br>      }<br>    } else {<br>      throw HttpException(&#39;Server error: ${response.statusCode}&#39;);<br>    }<br>    // Catch possible specific exceptions<br>  } on TimeoutException {<br>    throw Exception(&#39;Request timed out&#39;);<br>  } on SocketException {<br>    throw Exception(&#39;No internet connection&#39;);<br>  } on HttpException catch (error) {<br>    throw Exception(&#39;Request error: $error&#39;);<br>  } on FormatException {<br>    throw Exception(&#39;Bad response format&#39;);<br>  } catch (error) {<br>    throw Exception(&#39;Error: $error&#39;);<br>  }<br>}<br><br>// Call the OpenStreetMap search endpoint with a free-form query<br>// https://nominatim.org/release-docs/latest/api/Search/#free-form-query<br>Future&lt;List&lt;Location&gt;&gt; searchLocation(String query) async {<br>  try {<br>    final data = await makeOpenStreetMapRequest(<br>      path: &#39;search&#39;,<br>      queryParams: {<br>        &#39;q&#39;: query,<br>        &#39;limit&#39;: 10,<br>      },<br>    );<br>    // Convert the JSON data into a list of Location objects<br>    if (data is Map &amp;&amp; data.containsKey(&#39;features&#39;)) {<br>      final results = List&lt;Map&lt;String, dynamic&gt;&gt;.from(data[&#39;features&#39;])<br>          .map((result) =&gt; Location.fromGeoJson(result))<br>          .toList();<br>      return results;<br>    } else {<br>      return [];<br>    }<br>  } catch (error) {<br>    throw Exception(&#39;Error searching for location: $error&#39;);<br>  }<br>}<br><br>// The reverse endpoint returns exactly one result or an error<br>// https://nominatim.org/release-docs/latest/api/Reverse/<br>Future&lt;Location?&gt; getLocationByCoordinates(<br>    {required double latitude, required double longitude}) async {<br>  try {<br>    final data = await makeOpenStreetMapRequest(<br>      path: &#39;reverse&#39;,<br>      queryParams: {<br>        &#39;lat&#39;: latitude,<br>        &#39;lon&#39;: longitude,<br>      },<br>    );<br>    if (data is Map &amp;&amp; data.containsKey(&#39;features&#39;)) {<br>      final results = List&lt;Map&lt;String, dynamic&gt;&gt;.from(data[&#39;features&#39;]);<br>      if (results.isNotEmpty) {<br>        return Location.fromGeoJson(results.first);<br>      }<br>    }<br>    return null;<br>  } catch (error) {<br>    throw Exception(&#39;Error getting location from coordinates: $error&#39;);<br>  }<br>}<br><br>// Use the user&#39;s locale to get the location from the country code<br>// https://nominatim.org/release-docs/latest/api/Search/#structured-query<br>Future&lt;Location?&gt; getLocationByLocale() async {<br>  try {<br>    final countryCode = Intl.getCurrentLocale().split(&#39;_&#39;).last;<br>    final data = await makeOpenStreetMapRequest(<br>      path: &#39;search&#39;,<br>      queryParams: {<br>        &#39;country&#39;: countryCode,<br>      },<br>    );<br>    if (data is Map &amp;&amp; data.containsKey(&#39;features&#39;)) {<br>      final results = List&lt;Map&lt;String, dynamic&gt;&gt;.from(data[&#39;features&#39;]);<br>      if (results.isNotEmpty) {<br>        return Location.fromGeoJson(results.first);<br>      }<br>    }<br>    return null;<br>  } catch (error) {<br>    throw Exception(&#39;Error getting location from country code: $error&#39;);<br>  }<br>}<br><br>// This function follows the example from the Geolocator package<br>// https://pub.dev/packages/geolocator/example<br>Future&lt;Location&gt; getCurrentLocation() async {<br>  bool locationServiceEnabled;<br>  LocationPermission locationPermission;<br><br>  // Check if location services are enabled.<br>  locationServiceEnabled = await Geolocator.isLocationServiceEnabled();<br>  if (!locationServiceEnabled) {<br>    // Location services are not enabled, request user to enable location services.<br>    return Future.error(&#39;Location services are disabled.&#39;);<br>  }<br><br>  locationPermission = await Geolocator.checkPermission();<br>  if (locationPermission == LocationPermission.denied) {<br>    locationPermission = await Geolocator.requestPermission();<br>    if (locationPermission == LocationPermission.denied) {<br>      // Permissions are denied, you could request permissions again here.<br>      return Future.error(&#39;Location permissions are denied.&#39;);<br>    }<br>  }<br><br>  if (locationPermission == LocationPermission.deniedForever) {<br>    // Permissions are denied forever, handle appropriately.<br>    return Future.error(<br>        &#39;Location permissions are denied permanently. Please enable them in settings.&#39;);<br>  }<br><br>  try {<br>    // At this point we have permissions and location services are enabled<br>    final Position position = await Geolocator.getCurrentPosition();<br>    // Try to get the location from the coordinates<br>    final Location? location = await getLocationByCoordinates(<br>        latitude: position.latitude, longitude: position.longitude);<br>    if (location != null) {<br>      return location;<br>    } else {<br>      return Location(latitude: position.latitude, longitude: position.longitude);<br>    }<br>  } catch (error) {<br>    throw Exception(&#39;Error getting current location: $error&#39;);<br>  }<br>}<br><br>Future&lt;Location?&gt; getLastKnownLocation() async {<br>  try {<br>    final Position? position = await Geolocator.getLastKnownPosition();<br>    if (position != null) {<br>      final Location? location = await getLocationByCoordinates(<br>          latitude: position.latitude, longitude: position.longitude);<br>      return location;<br>    } else {<br>      return null;<br>    }<br>  } catch (error) {<br>    return null;<br>  }<br>}</pre><h3>LocationMap Widget</h3><p>This is the main class of our app responsible for managing the map widget, the location search bar, and any associated UI components, ensuring a seamless and cohesive user experience.</p><p>Upon map initialization, if no initialLocation is specified, we attempt to retrieve the user&#39;s last known location or determine the user&#39;s location based on their device&#39;s locale country.</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_map/flutter_map.dart&#39;;<br><br>import &#39;package:url_launcher/url_launcher.dart&#39;;<br>import &#39;package:latlong2/latlong.dart&#39;;<br><br>import &#39;geolocation.dart&#39; as Geolocation;<br><br>import &#39;debounced_search_bar.dart&#39;;<br>import &#39;round_icon_button.dart&#39;;<br>import &#39;location_pin.dart&#39;;<br>import &#39;location.dart&#39;;<br><br>class LocationMap extends StatefulWidget {<br>  const LocationMap({<br>    super.key,<br>    this.initialLocation,<br>    this.onBoundsChanged,<br>    this.onLocationChanged,<br>  });<br><br>  final Location? initialLocation;<br>  final Function(Location location)? onLocationChanged;<br>  final Function(LatLngBounds bounds, LatLng center)? onBoundsChanged;<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _LocationMapState();<br>}<br><br>class _LocationMapState extends State&lt;LocationMap&gt; {<br>  final MapController _mapController = MapController();<br>  Location? _location;<br>  bool _isMapMoved = false;<br>  Timer? _mapMovedTimer;<br><br>  void _showErrorDialog(String title, String message) {<br>    showDialog(<br>      context: context,<br>      builder: (context) {<br>        return AlertDialog(<br>          title: Text(title),<br>          content: Text(message),<br>          actions: [<br>            TextButton(<br>              onPressed: () {<br>                Navigator.of(context).pop();<br>              },<br>              child: const Text(&#39;OK&#39;),<br>            ),<br>          ],<br>        );<br>      },<br>    );<br>  }<br><br>  Future&lt;void&gt; _openMapsApp() async {<br>    if (_location == null) {<br>      return;<br>    }<br>    final lat = _location!.latitude;<br>    final lon = _location!.longitude;<br>    final zoom = _mapController.camera.zoom;<br>    final Uri? mapsUri;<br>    try {<br>      // Check if the maps app is available on the device<br>      if (await canLaunchUrl(Uri.parse(&#39;maps:&#39;))) {<br>        // Use the maps: URL scheme on iOS<br>        mapsUri = Uri.parse(&#39;maps://?ll=$lat,$lon&amp;z=$zoom&#39;);<br>      } else if (await canLaunchUrl(Uri.parse(&#39;geo:&#39;))) {<br>        // Use the geo: URL scheme on Android<br>        mapsUri = Uri.parse(&#39;geo:$lat,$lon?z=$zoom&#39;);<br>      } else if (await canLaunchUrl(Uri.parse(&#39;comgooglemaps:&#39;))) {<br>        // Use the comgooglemaps: URL scheme on Android<br>        mapsUri = Uri.parse(&#39;comgooglemaps://?center=$lat,$lon&amp;zoom=$zoom&#39;);<br>      } else if (await canLaunchUrl(Uri.parse(&#39;waze:&#39;))) {<br>        // Use the waze: URL scheme on Android<br>        mapsUri = Uri.parse(&#39;waze://?ll=$lat,$lon&amp;z=$zoom&#39;);<br>      } else {<br>        throw &#39;Failed to open maps&#39;;<br>      }<br>      await launchUrl(mapsUri);<br>    } catch (error) {<br>      _showErrorDialog(&#39;Failed to open maps&#39;, error.toString());<br>    }<br>  }<br><br>  void _setLocation(Location location) {<br>    // Move the map to the new location<br>    _mapController.move(location.latLng, 10.0);<br>    _mapController.rotate(0.0);<br>    // Fit the camera to the bounds if available<br>    if (location.bounds != null) {<br>      _mapController.fitCamera(CameraFit.bounds(<br>        bounds: location.bounds!,<br>        padding: const EdgeInsets.all(16.0),<br>      ));<br>    }<br>    setState(() {<br>      // Update the location and reset the map moved flag<br>      _location = location;<br>      _isMapMoved = false;<br>    });<br>    // If the location has changed, call the onLocationChanged callback<br>    if (location != widget.initialLocation) {<br>      widget.onLocationChanged?.call(location);<br>    }<br>  }<br><br>  Future&lt;List&lt;Location&gt;&gt; _searchLocation(String query) async {<br>    try {<br>      // Try searching for the location using the OpenStreetMap search endpoint<br>      final List&lt;Location&gt; results = await Geolocation.searchLocation(query);<br>      return results;<br>    } catch (error) {<br>      _showErrorDialog(&#39;Failed to search location&#39;, error.toString());<br>      // Because the SearchBar search function still expects a List, return an empty list<br>      return [];<br>    }<br>  }<br><br>  Future&lt;void&gt; _getCurrentLocation() async {<br>    try {<br>      final location = await Geolocation.getCurrentLocation();<br>      _setLocation(location);<br>    } catch (error) {<br>      _showErrorDialog(&#39;Failed to get current location&#39;, error.toString());<br>    }<br>  }<br><br>  Future&lt;void&gt; _initMap() async {<br>    // This is a very hacky way to wait for the parent dimensions, otherwise the map will not render correctly<br>    await Future.delayed(const Duration(milliseconds: 500));<br><br>    try {<br>      // Try getting initial location from widget, last known location, or location by locale<br>      final Location? location = widget.initialLocation ??<br>          await Geolocation.getLastKnownLocation() ??<br>          await Geolocation.getLocationByLocale();<br>      if (location != null) {<br>        _setLocation(location);<br>      }<br>    } catch (error) {<br>      _showErrorDialog(&#39;Failed to get initial location&#39;, error.toString());<br>    }<br>  }<br><br>  void _onMapMoved() {<br>    // Set the map moved flag to true to show the recenter button<br>    setState(() {<br>      _isMapMoved = true;<br>    });<br>    // To avoid calling onBoundsChanged too frequently, use a simple debounce mechanism<br>    if (_mapMovedTimer != null) {<br>      _mapMovedTimer!.cancel();<br>    }<br>    // Wait for 500ms before calling onBoundsChanged again<br>    _mapMovedTimer = Timer(const Duration(milliseconds: 500), () {<br>      final bounds = _mapController.camera.visibleBounds;<br>      final center = _mapController.camera.center;<br>      widget.onBoundsChanged?.call(bounds, center);<br>    });<br>  }<br><br>  void _onLongPress(LatLng latLng) async {<br>    // When the user long-presses on the map, try to get the location at that point<br>    try {<br>      final location = await Geolocation.getLocationByCoordinates(<br>        latitude: latLng.latitude,<br>        longitude: latLng.longitude,<br>      );<br>      if (location != null) {<br>        _setLocation(location);<br>      }<br>    } catch (error) {<br>      _showErrorDialog(&#39;Failed to get location&#39;, error.toString());<br>    }<br>  }<br><br>  void _showLocationDetails() {<br>    if (_location == null) {<br>      return;<br>    }<br>    // Show location details in a bottom sheet<br>    showModalBottomSheet(<br>      context: context,<br>      builder: (context) {<br>        return Container(<br>          padding: const EdgeInsets.all(16.0),<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.stretch,<br>            children: [<br>              Row(<br>                mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                children: [<br>                  Text(_location!.name ?? &#39;Location&#39;, style: Theme.of(context).textTheme.titleLarge),<br>                  Spacer(),<br>                  IconButton(<br>                    icon: const Icon(Icons.close),<br>                    onPressed: () {<br>                      Navigator.of(context).pop();<br>                    },<br>                  ),<br>                ],<br>              ),<br>              const SizedBox(height: 16.0),<br>              Text(_location!.displayName ?? &#39;Address&#39;, style: Theme.of(context).textTheme.titleMedium),<br>              const SizedBox(height: 16.0),<br>              Text(&#39;Lat/lng: ${_location!.latitude}, ${_location!.longitude}&#39;),<br>            ],<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _mapController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      fit: StackFit.expand,<br>      children: [<br>        FlutterMap(<br>          mapController: _mapController,<br>          options: MapOptions(<br>            initialCenter: _location?.latLng ?? LatLng(0.0, 0.0),<br>            initialZoom: 10.0,<br>            interactionOptions: const InteractionOptions(<br>              // Disable rotation<br>              flags: InteractiveFlag.all &amp; ~InteractiveFlag.rotate,<br>            ),<br>            onPositionChanged: (position, hasGesture) {<br>              _onMapMoved();<br>            },<br>            onLongPress: (point, latLng) {<br>              _onLongPress(latLng);<br>            },<br>            onMapReady: () {<br>              _initMap();<br>            },<br>          ),<br>          children: [<br>            TileLayer(<br>              // Use the OpenStreetMap tile server<br>              urlTemplate: &#39;https://tile.openstreetmap.org/{z}/{x}/{y}.png&#39;,<br>              userAgentPackageName: &#39;com.example.app&#39;,<br>            ),<br>            if (_location != null) ...[<br>              MarkerLayer(<br>                markers: [  <br>                  Marker(<br>                    point: _location!.latLng,<br>                    alignment: Alignment.topCenter,<br>                    height: 48,<br>                    width: 48,<br>                    child: GestureDetector(<br>                      onTap: () {<br>                        _showLocationDetails();<br>                      },<br>                      child: LocationPin(),<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            ],<br>            RichAttributionWidget(<br>              alignment: AttributionAlignment.bottomLeft,<br>              attributions: [<br>                TextSourceAttribution(<br>                  &#39;OpenStreetMap contributors&#39;,<br>                  onTap: () =&gt; launchUrl(Uri.parse(&#39;https://openstreetmap.org/copyright&#39;)),<br>                ),<br>              ],<br>            ),<br>          ],<br>        ),<br>        SafeArea(<br>          minimum: const EdgeInsets.all(16.0),<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.end,<br>            children: [<br>              DebouncedSearchBar&lt;Location&gt;(<br>                hintText: &#39;Search location&#39;,<br>                initialValue: _location,<br>                titleBuilder: (Location location) =&gt; Text(location.toString()),<br>                leadingIconBuilder: (Location location) =&gt; const Icon(Icons.location_pin),<br>                searchFunction: _searchLocation,<br>                onResultSelected: (Location location) {<br>                  _setLocation(location);<br>                },<br>              ),<br>              Spacer(), // Add a Spacer to push the buttons to the bottom<br>              if (_location != null &amp;&amp; _isMapMoved) ...[<br>                RoundIconButton(<br>                  icon: const Icon(Icons.near_me),<br>                  onPressed: () {<br>                    _setLocation(_location!);<br>                  },<br>                ),<br>                const SizedBox(height: 8.0),<br>              ],<br>              if (_location != null) ...[<br>                RoundIconButton(<br>                  icon: const Icon(Icons.map),<br>                  onPressed: () {<br>                    _openMapsApp();<br>                  },<br>                ),<br>                const SizedBox(height: 8.0),<br>              ],<br>              RoundIconButton(<br>                icon: const Icon(Icons.my_location),<br>                onPressed: () {<br>                  _getCurrentLocation();<br>                },<br>              ),<br>            ],<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><h3><strong>DebouncedSearchBar Widget</strong></h3><p>Debouncing is crucial for optimizing search functionality. When a user types quickly in a search bar, numerous requests can be sent to the server, overwhelming it and potentially causing delays or even crashes.</p><p><a href="https://medium.com/@stassop/debouncing-flutter-searchanchor-65101042e5aa">My previous article</a> explains the implementation of <a href="https://github.com/stassop/flutter_debounced_search_bar">DebouncedSearchBar</a> in detail. This optimization significantly improves performance and enhances the overall user experience.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;dart:async&#39;; <br><br>/// This is a simplified version of debounced search based on the following example:<br>/// https://api.flutter.dev/flutter/material/Autocomplete-class.html?v=1.0.20#material.Autocomplete.5<br>typedef _Debounceable&lt;S, T&gt; = Future&lt;S?&gt; Function(T parameter);<br><br>/// Returns a new function that is a debounced version of the given function.<br>/// This means that the original function will be called only after no calls<br>/// have been made for the given Duration.<br>_Debounceable&lt;S, T&gt; _debounce&lt;S, T&gt;(_Debounceable&lt;S?, T&gt; function) {<br>  _DebounceTimer? debounceTimer;<br><br>  return (T parameter) async {<br>    if (debounceTimer != null &amp;&amp; !debounceTimer!.isCompleted) {<br>      debounceTimer!.cancel();<br>    }<br>    debounceTimer = _DebounceTimer(duration: const Duration(milliseconds: 500));<br>    try {<br>      await debounceTimer!.future;<br>    } catch (error) {<br>      print(error); // Should be &#39;Debounce cancelled&#39; when cancelled.<br>      return null;<br>    }<br>    return function(parameter);<br>  };<br>}<br><br>// A wrapper around Timer used for debouncing.<br>class _DebounceTimer {<br>  _DebounceTimer({required this.duration}) {<br>    _timer = Timer(duration, _onComplete);<br>  }<br><br>  late final Timer _timer;<br>  final Duration duration;<br>  final Completer&lt;void&gt; _completer = Completer&lt;void&gt;();<br><br>  void _onComplete() {<br>    _completer.complete();<br>  }<br><br>  Future&lt;void&gt; get future =&gt; _completer.future;<br><br>  bool get isCompleted =&gt; _completer.isCompleted;<br><br>  void cancel() {<br>    _timer.cancel();<br>    _completer.completeError(&#39;Debounce cancelled&#39;);<br>  }<br>}<br><br>class DebouncedSearchBar&lt;T&gt; extends StatefulWidget {<br>  const DebouncedSearchBar({<br>    super.key,<br>    required this.onResultSelected,<br>    required this.searchFunction,<br>    required this.titleBuilder,<br>    this.hintText,<br>    this.initialValue,<br>    this.leadingIconBuilder,<br>    this.subtitleBuilder,<br>  });<br><br>  final String? hintText;<br>  final T? initialValue;<br>  final Widget? Function(T result)? titleBuilder;<br>  final Widget? Function(T result)? subtitleBuilder;<br>  final Widget? Function(T result)? leadingIconBuilder;<br>  final Function(T result)? onResultSelected;<br>  final Future&lt;Iterable&lt;T&gt;&gt; Function(String query) searchFunction;<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _DebouncedSearchBarState&lt;T&gt;();<br>}<br><br>class _DebouncedSearchBarState&lt;T&gt; extends State&lt;DebouncedSearchBar&lt;T&gt;&gt; {<br>  final _searchController = SearchController();<br>  late final _Debounceable&lt;Iterable&lt;T&gt;?, String&gt; _debouncedSearch;<br>  final pastResults = &lt;T&gt;[];<br><br>  _selectResult(T result) {<br>    widget.onResultSelected?.call(result);<br>    // Add the result on top of the list of past results if it is not already there<br>    // If the number of past results exceeds 10, remove the oldest one<br>    if (!pastResults.contains(result)) {<br>      pastResults.insert(0, result);<br>      if (pastResults.length &gt; 10) {<br>        pastResults.removeLast();<br>      }<br>    }<br>  }<br><br>  Future&lt;Iterable&lt;T&gt;&gt; _search(String query) async {<br>    if (query.isEmpty) {<br>      return &lt;T&gt;[];<br>    }<br><br>    try {<br>      final results = await widget.searchFunction(query);<br>      return results;<br>    } catch (error) {<br>      return &lt;T&gt;[];<br>    }<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _debouncedSearch = _debounce&lt;Iterable&lt;T&gt;?, String&gt;(_search);<br>    _searchController.text = widget.initialValue != null <br>        ? widget.initialValue.toString() <br>        : &#39;&#39;;<br>  }<br><br>  @override<br>  void didUpdateWidget(DebouncedSearchBar&lt;T&gt; oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    if (widget.initialValue != oldWidget.initialValue) {<br>      _searchController.text = widget.initialValue != null <br>          ? widget.initialValue.toString() <br>          : &#39;&#39;;<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    _searchController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SearchAnchor(<br>      searchController: _searchController,<br>      builder: (BuildContext context, SearchController controller) {<br>        return SearchBar(<br>          controller: controller,<br>          padding: const WidgetStatePropertyAll&lt;EdgeInsets&gt;(<br>              EdgeInsets.symmetric(horizontal: 16.0)),<br>          onTap: () {<br>            controller.openView();<br>          },<br>          leading: const Icon(Icons.search),<br>          hintText: widget.hintText,<br>        );<br>      },<br>      suggestionsBuilder: (BuildContext context, SearchController controller) async {<br>        final Future&lt;Iterable&lt;T&gt;?&gt; future = _debouncedSearch(controller.text);<br>        try {<br>          final Iterable&lt;T&gt;? results = await future;<br>          // If there are results, return a list of result tiles<br>          if (results?.isNotEmpty ?? false) {<br>            return results!.map((result) {<br>              return ListTile(<br>                title: widget.titleBuilder?.call(result),<br>                subtitle: widget.subtitleBuilder?.call(result),<br>                leading: widget.leadingIconBuilder?.call(result),<br>                onTap: () {<br>                  _selectResult(result);<br>                  controller.closeView(result.toString());<br>                },<br>              );<br>            }).toList();<br>          }<br>          // If there&#39;s no search text and there are past results, return a list of past results<br>          if (controller.text.isEmpty &amp;&amp; pastResults.isNotEmpty) {<br>            // Add a tile with a history icon and &#39;Search history&#39; title<br>            return &lt;Widget&gt;[<br>              ListTile(<br>                leading: const Icon(Icons.history),<br>                title: const Text(&#39;Search history&#39;),<br>              ),<br>              for (final result in pastResults)<br>                ListTile(<br>                  title: widget.titleBuilder?.call(result),<br>                  subtitle: widget.subtitleBuilder?.call(result),<br>                  leading: widget.leadingIconBuilder?.call(result),<br>                  onTap: () {<br>                    _selectResult(result);<br>                    controller.closeView(result.toString());<br>                  },<br>                ),<br>            ];<br>          }<br>          // If there&#39;s search text but no results, return a &#39;No results found&#39; tile<br>          if (controller.text.isNotEmpty) {<br>            return &lt;Widget&gt;[<br>              ListTile(<br>                title: const Text(&#39;No results found&#39;),<br>              ),<br>            ];<br>          }<br>          // If there&#39;s no search text and no past results, return an empty list<br>          return &lt;Widget&gt;[];<br>        } catch (error) {<br>          return &lt;Widget&gt;[<br>            ListTile(<br>              title: const Text(&#39;An error occurred&#39;),<br>            ),<br>          ];<br>        }<br>      },<br>    );<br>  }<br>}</pre><h3>Putting It All Together</h3><p>Here’s our main.dart class. As you can see, the top-level structure is clean and simple, making it easy to repurpose our location search widget in other applications.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;location_map.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: LocationMap(),<br>    );<br>  }<br>}</pre><h3>Conclusion</h3><p>Implementing a robust and feature-rich location search and mapping experience within your Flutter application can be surprisingly straightforward and cost-effective.</p><p>By leveraging free-tier tools and following simple guidelines, startups and developers alike can easily integrate maps into their projects without incurring significant expenses.</p><p>These free-tier solutions offer a wealth of possibilities, allowing developers to experiment, iterate, and build compelling location-based features while minimizing development costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d99b2a35175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter vs. React Native in 2025: Which One to Choose?]]></title>
            <link>https://stassop.medium.com/flutter-vs-react-native-in-2025-which-one-to-choose-5c893f4d9272?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c893f4d9272</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[2025]]></category>
            <category><![CDATA[flutter-vs-react-native]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 09:28:01 GMT</pubDate>
            <atom:updated>2025-01-08T12:10:27.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Deep Dive into Performance, Development Speed, and Ecosystem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxK_vt3dYFJBtmKjpz-bjA.png" /></figure><p>As 2025 unfolds, the cross-platform development landscape continues to evolve rapidly. Both Flutter and React Native have made significant strides in architecture, performance, and community growth.</p><p>Flutter has made dramatic progress, solidifying its position as a leading contender with its focus on performance, expressive UI, and growing community support.</p><p>React Native, a seasoned veteran in the field, has also witnessed substantial advancements, particularly in performance and addressing some of its long-standing limitations.</p><p>By carefully considering factors such as performance, development speed, and ecosystem, we hope to help developers make informed decisions about which framework to choose in 2025.</p><h3>Main Difference</h3><p>The fundamental distinction between Flutter and React Native lies in their architectural approaches. Understanding these architectural differences is crucial before delving deeper into other aspects like performance.</p><p>Flutter renders UI using its own rendering engine, ensuring a consistent look and feel across platforms. This approach provides greater control and independence from the underlying operating system.</p><p>React Native leverages native platform components and APIs, resulting in a more authentically native look and feel. It seamlessly integrates with the platform’s design language, leveraging existing UI elements.</p><p>Either approach has its advantages and limitations. Understanding and mitigating the potential drawbacks of each framework is key to achieving optimal performance and user experience.</p><h3>Developer Experience</h3><p>While performance, community support, and ecosystem maturity are often the primary considerations when choosing between Flutter and React Native, it’s crucial not to overlook the developer experience.</p><p>Long build times, complex setups, and frequent dependency conflicts can disrupt the development flow and lead to frustration, project delays, increased development costs, and lower overall team morale.</p><p>And while React Native has made <a href="https://reactnative.dev/blog/2024/10/23/the-new-architecture-is-here">significant strides</a> in improving its architecture, <a href="https://reactnative.dev/docs/build-speed">build speed</a>, and overall performance, developer experience still remains a valid concern.</p><p>In contrast to React Native’s setup that demands regular maintenance, <a href="https://docs.flutter.dev/reference/flutter-cli">Flutter CLI</a> offers a comprehensive set of tools that make it easier to identify and resolve issues during setup and development.</p><h3>Performance</h3><p>While numerous <a href="https://nateshmbhat.medium.com/flutter-vs-react-native-performance-benchmarks-you-cant-miss-%EF%B8%8F-2e31905df9b4">performance comparisons</a> have been made between Flutter and React Native, both frameworks continue to evolve, as well as mobile CPUs and cross-platform development ecosystem.</p><p>Flutter leverages the powerful <a href="https://docs.flutter.dev/resources/architectural-overview">Skia</a> (soon <a href="https://docs.flutter.dev/perf/impeller">Impeller</a>) graphics engine for exceptional performance. Flutter also embeds its own copy of Skia as part of the engine, granting it full control over the rendering process.</p><p>React Native aims for a native look and feel, which creates an extra layer of abstraction that can sometimes lead to performance bottlenecks, especially when dealing with complex UI interactions or demanding animations.</p><p>And while React Native performance <a href="https://reactnative.dev/architecture/landing-page">continues to improve</a>, Flutter’s direct control over rendering unlocks near-native performance, enabling smooth animations and a highly responsive UI.</p><h3>Dart vs <strong>TypeScript</strong></h3><p>Flutter utilizes <a href="https://dart.dev/overview">Dart</a>, a mature object-oriented programming language developed by Google, offers a comprehensive feature set, including strong typing, garbage collection, and asynchronous programming support.</p><p>If you have experience with modern object-oriented programming languages, you’ll find Dart’s syntax and structure familiar, enabling you to confidently build a robust foundation for your applications.</p><p>TypeScript, on the other hand, is a superset of JavaScript, adding static typing to the language. TypeScript’s primary advantage is that it allows developers to leverage existing JavaScript libraries and frameworks.</p><p>While TypeScript incorporates some object-oriented features, its capabilities are ultimately constrained by the underlying JavaScript paradigm, whereas Dart is a fully-fledged object-oriented language.</p><h3>State Management</h3><p>State management is arguably one of the most critical aspects to consider when choosing a framework. Effective state management directly impacts the maintainability, scalability, and testability of an application.</p><p>Both Flutter and React Native offer a variety of state management solutions, providing developers with flexibility in choosing the approach that best suits their project’s needs.</p><p>Flutter boasts a growing ecosystem of <a href="https://docs.flutter.dev/data-and-backend/state-mgmt/options">state management libraries</a> like Provider, BLoC, and Riverpod, while React Native benefits from the wealth of JavaScript-based solutions like Redux, React Query, Zustand, and Recoil.</p><p>This abundance of options empowers developers to select the most appropriate state management strategy for their specific use case, whether it prioritizes simplicity, scalability, or a particular architectural pattern.</p><h3>UI/UX</h3><p>The <a href="https://api.flutter.dev/flutter/material/material-library.html">Material</a> (or <a href="https://api.flutter.dev/flutter/cupertino/cupertino-library.html">Cupertino</a> for iOS) widget library is arguably Flutter’s most significant asset. It provides a comprehensive set of pre-built, customizable widgets like buttons, form fields, and navigation bars.</p><p>Using Material, developers can quickly assemble complex UIs with minimal effort. This leads to a significant increase in productivity, reduced development time, and more predictable project timelines and budgets.</p><p>However, while theoretically possible, building a Flutter app without relying heavily on the Material library can be cumbersome and may require significant custom widget development.</p><p>Meanwhile, React Native delegates much of the UI/UX rendering to the native platform. This approach ensures that the application always maintains a genuine native look and feel on both iOS and Android.</p><h3>Testing</h3><p>When it comes to testing, Flutter and React Native follow different approaches. Flutter provides <a href="https://docs.flutter.dev/testing/overview">built-in support</a> for unit, widget, and integration tests, while React Native relies heavily on <a href="https://reactnative.dev/docs/testing-overview">third-party libraries</a>.</p><p>While React Native’s testing ecosystem offers a wide range of tools, it can require more configuration effort. Flutter’s testing framework, while easy to set up, has a slightly more limited selection of testing tools and options.</p><h3>Going Native</h3><p>When choosing between Flutter and React Native, it’s crucial to consider whether your cross-platform approach is a temporary phase or a long-term investment.</p><p>If you’re building an MVP or a project with a finite lifespan, a cross-platform framework like Flutter or React Native can be an excellent choice for rapid prototyping and initial development.</p><p>However, if you anticipate the need for deep platform integration, high-performance graphics, or extensive customization, consider whether a native approach would be more suitable in the long run.</p><p>While Flutter has gained significant traction in recent years, React Native boasts a longer history of powering mature, production-level applications across various industries.</p><h3>Conclusion</h3><p>Both Flutter and React Native have matured into robust frameworks suitable for serious projects. The gap between them has narrowed considerably, making the choice more nuanced than ever before.</p><p>React Native excels at delivering a truly native look and feel, leveraging the platform’s existing UI components. However, performance and long-term maintenance can be a concern.</p><p>Flutter, while it requires Dart knowledge, delivers unparalleled performance and exceptional developer experience, making it ideal for rapid prototyping and MVPs.</p><p>Finally, it’s crucial to remember that cross-platform frameworks inherently involve trade-offs. Carefully consider the potential limitations of each framework and their long-term implications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c893f4d9272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending Emails with Firebase]]></title>
            <link>https://stassop.medium.com/sending-emails-with-firebase-2202f1abffac?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2202f1abffac</guid>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[nodemailer]]></category>
            <category><![CDATA[email-service-provider]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 13:16:04 GMT</pubDate>
            <atom:updated>2024-04-30T10:18:58.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Complete Guide Using Cloud Functions and Nodemailer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zphhKU9zBgOS_VnDTgxaGA.png" /></figure><p>Websites and apps use emails to keep users informed. This includes confirmations (sign-up, password reset), notifications (deliveries, receipts), and even marketing (newsletters, promotions).</p><p>Firebase apps can’t send emails directly, but <a href="https://firebase.google.com/docs/functions">Cloud Functions</a> bridge the gap using libraries like <a href="https://www.nodemailer.com/">Nodemailer</a> to connect to email services and send emails upon receiving triggers or HTTP requests.</p><p>This guide dives deep into equipping your Firebase app with email functionality. We’ll walk you through setting up Firebase Cloud Functions and utilizing Nodemailer to send emails.</p><h3><strong>Setup</strong></h3><p>This guide uses the <a href="https://firebase.google.com/docs/functions/version-comparison">New Cloud Functions (2nd gen)</a>.</p><p>To <a href="https://firebase.google.com/docs/functions/get-started?gen=2nd">get started</a>, create a Firebase project and install <a href="https://firebase.google.com/docs/cli">Firebase CLI</a>.</p><p>If you’re <a href="https://firebase.google.com/docs/functions/typescript#using_an_existing_typescript_project">adding Cloud Functions to an existing TypeScript project </a>or <a href="https://firebase.google.com/docs/functions/typescript#migrating_an_existing_javascript_project_to_typescript">migrating an existing JavaScript project to TypeScript</a>, follow <a href="https://firebase.google.com/docs/functions/typescript">these instructions</a>.</p><p>In many cases, new features and bug fixes are available only with the latest version of the Firebase CLI and the firebase-functions SDK. It&#39;s a good practice to frequently update both the Firebase CLI and the SDK:</p><pre>npm install firebase-functions@latest firebase-admin@latest --save<br>npm install -g firebase-tools</pre><p>Add Cloud Functions to your Firebase project:</p><pre>firebase init functions</pre><p>When adding Cloud Functions, Firebase CLI gives you options to build the project with JavaScript or TypeScript. Choosing TypeScript will create the necessary configs.</p><p>Adding Cloud Functions will create a file named functions/src/index.ts This is where your cloud functions reside. They can be called from your client-side code.</p><h4>Firebase Emulator Suite</h4><p>You’ll need the <a href="https://firebase.google.com/docs/emulator-suite">Emulator Suite</a> for testing your code locally. For troubleshooting and detailed instructions for installing Emulator Suite refer to <a href="https://firebase.google.com/docs/emulator-suite/install_and_configure">this page</a>.</p><p>Add Emulator Suite to your Firebase project:</p><pre>firebase init emulators</pre><p>Identify emulators to be installed and optionally specify emulator port settings. init emulators is non-destructive; accepting defaults will preserve the current emulator configuration.</p><h4>Nodemailer</h4><p>Nodemailer integrates smoothly with Firebase Cloud Functions’ Node.js environment, making it an ideal choice for setting up email functionality within your Firebase website.</p><p>Install Nodemailer:</p><pre>npm install nodemailer</pre><h4>Email Service Providers (ESPs)</h4><p>Nodemailer acts as a bridge between your Firebase Cloud Functions and various email service providers (ESPs) like Gmail or <a href="https://sendgrid.com/">SendGrid</a>. In our example we’ll be using Gmail.</p><p>In order to use Nodemailer with Gmail you must create an <a href="https://support.google.com/mail/answer/185833">app password</a>. An app password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account.</p><h3>Cloud Functions Code</h3><p>Here’s what your Cloud Functions code will look like in functions/src/index.ts:</p><pre>import { onRequest } from &#39;firebase-functions/v2/https&#39;;<br>import { createTransport } from &#39;nodemailer&#39;;<br>import express from &#39;express&#39;;<br>import rateLimit from &#39;express-rate-limit&#39;;<br><br>// Create an Express app<br>const app = express();<br><br>// Create a rate limiter that allows 1 request per 15 minutes<br>const rateLimiter = rateLimit({<br>  windowMs: 15 * 60 * 1000, // 15-minute window<br>  max: 1, // Maximum 1 request per 15-minute window per IP<br>  message: &#39;Too many requests. Please try again later.&#39;,<br>  headers: true,<br>  handler: (request, response, options) =&gt; {<br>    console.error(&#39;Rate limit exceeded:&#39;, request.ip);<br>    response.status(429).json({ error: &#39;Too many requests. Please try again later.&#39; });<br>  },<br>});<br><br>// Apply the rate limiter middleware to the Express app<br>app.use(rateLimiter);<br><br>// Create a Nodemailer transporter using SMTP<br>const transporter = createTransport({<br>  service: &#39;Gmail&#39;,<br>  auth: {<br>    user: process.env.GMAIL_EMAIL_ADDRESS,<br>    pass: process.env.GMAIL_APP_PASSWORD,<br>  }<br>});<br><br>interface EmailData {<br>  name?: string;<br>  subject?: string;<br>  message?: string;<br>}<br><br>// The POST endpoint that handles email sending<br>app.post(&#39;*&#39;, async (request, response) =&gt; {<br>  // Since CORS consists of two requests (a preflight OPTIONS request, and a main request that follows the OPTIONS request), <br>  // to handle a preflight request, you must set the appropriate Access-Control-Allow-* headers to match the requests you want to accept. <br>  // Learn more about CORS and preflight requests at: https://cloud.google.com/functions/docs/writing/write-http-functions#cors<br>  response.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  if (request.method === &#39;OPTIONS&#39;) {<br>    response.set(&#39;Access-Control-Allow-Methods&#39;, &#39;GET&#39;);<br>    response.set(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type&#39;);<br>    response.set(&#39;Access-Control-Max-Age&#39;, &#39;3600&#39;);<br>    response.status(204).send(&#39;&#39;);<br>  } <br><br>  const data = request.body.data as EmailData;<br><br>  // Check if the data object contains the required fields<br>  if (!data.name || !data.subject || !data.message) {<br>    response.status(400).json({ error: &#39;Missing required fields&#39; });<br>    return;<br>  }<br><br>  // Create the email message<br>  const message = `<br>      From: ${data.name}<br>      Subject: ${data.subject}<br>      Message: ${data.message}<br>    `;<br><br>  // The response from a client endpoint is always a JSON object. <br>  // At a minimum it contains either `result` or `error`, along with any optional fields. <br>  // If the response is not a JSON object, or does not contain data or error, <br>  // the client SDK should treat the request as failed with Google error code INTERNAL (13).<br>  // Learn more about the response format at: https://firebase.google.com/docs/functions/callable-reference#response_body<br>  return transporter.sendMail({<br>    from: data.name,<br>    to: RECEPIENT_EMAIL_ADDRESS,<br>    subject: data.subject,<br>    text: message,<br>  }).then(() =&gt; {<br>    response.status(200).json({ result: &#39;Email sent successfully&#39;});<br>  }).catch(error =&gt; {<br>    response.status(500).json({ error: `Error sending email: ${error.message}` });<br>  });<br>});<br><br>// Export the Express app with rate limiter applied and CORS enabled<br>export const sendEmail = onRequest({<br>  cors: [<br>    &#39;http://localhost:5002&#39;, <br>    &#39;http://127.0.0.1:5002&#39;,<br>    &#39;https://www.your-allowed-domain.com&#39;,<br>  ],<br>}, app);</pre><p>There are a few things to note here:</p><h4>CORS</h4><p>By default, <a href="https://firebase.google.com/docs/functions/http-events?gen=2nd#configuring_cors_cross-origin_resource_sharing">HTTP functions don&#39;t have CORS configured</a>, which may result in the following error:</p><pre>Access to fetch at &#39;https://YOUR_FUNCTION_URL&#39; from origin &#39;https://YOUR_DOMAIN&#39; has been blocked by CORS policy: Response to preflight request doesn&#39;t pass access control check: No &#39;Access-Control-Allow-Origin&#39; header is present on the requested resource. If an opaque response serves your needs, set the request&#39;s mode to &#39;no-cors&#39; to fetch the resource with CORS disabled.</pre><p>We use the cors option to control which origins can access our function. At a minimum, we’ll need http://localhost:5002 to allow test requests made to Firebase emulators.</p><p>In addition, we handle a <a href="https://cloud.google.com/functions/docs/writing/write-http-functions#cors">preflight request</a>, which utilizes the OPTIONS method and precedes the main request. We must respond to the preflight request with a 204 response code and additional headers.</p><h4>Rate Limiting</h4><p>Firebase Cloud Functions do not automatically debounce or rate limit requests. This can lead to performance issues, unexpected costs, and security risks such as denial-of-service attacks.</p><p>Luckily, <a href="https://www.npmjs.com/package/express-rate-limit">express-rate-limit</a> offers an easy solution for this problem. By integrating this library into your function’s code, you can define limits on the number of requests allowed within a specific timeframe.</p><h4>Response body format</h4><p>The <a href="https://firebase.google.com/docs/functions/callable-reference#response_body">response from a client endpoint</a> is always a JSON object, and must contain either result or error, along with any optional fields. Otherwise the request fails with Google error code INTERNAL (13).</p><h3>Client-Side Code</h3><p>Here’s what your client-side code looks like:</p><pre>import { initializeApp, getApp } from &#39;firebase/app&#39;;<br>import { httpsCallable, getFunctions, connectFunctionsEmulator } from &#39;firebase/functions&#39;;<br><br>const app = initializeApp(YOUR_FIREBASE_PROJECT_SETTINGS);<br>const functions = getFunctions(app);<br><br>// Connect your app to the Cloud Functions Emulator running on localhost for local testing<br>// When running locally, Cloud Functions will be available at http://localhost:5001/&lt;projectId&gt;/&lt;region&gt;/&lt;functionName&gt;<br>// Learn more about testing Cloud Functions locally: https://firebase.google.com/docs/emulator-suite/connect_functions<br>if (window.location.hostname === &quot;localhost&quot; || window.location.hostname === &quot;127.0.0.1&quot;) {<br>  connectFunctionsEmulator(functions, &#39;127.0.0.1&#39;, 5001);<br>}<br><br>const sendEmail = httpsCallable(functions, &#39;sendEmail&#39;);<br><br>sendEmail({<br>  name: NAME_INPUT_VALUE,<br>  subject: SUBJECT_INPUT_VALUE,<br>  message: MESSAGE_INPUT_VALUE,<br>}).then((result) =&gt; {<br>  console.log(&#39;Email sent:&#39;, result);<br>}).catch((error) =&gt; {<br>  console.error(&#39;Error sending email:&#39;, error);<br>});</pre><h3>Testing with Firebase Emulator</h3><p>You can run emulators for any or all of the supported Firebase products. For any products you are not emulating, your code will interact with the <em>live</em> resource (database instance, storage bucket, function, etc.).</p><p>Code changes you make during an active session are automatically reloaded by the emulator. If your code needs to be transpiled (TypeScript, React) make sure to do so before running the emulator.</p><p>You can run your transpiler in watch mode with commands like tsc -w to transpile and reload code automatically as you save. If you’re using a packager tool, e.g. Parcel, don’t forget to run npm run build .</p><p>To run the Cloud Functions emulator, use the emulators:start command:</p><pre>firebase emulators:start</pre><p>Starting the emulator in the terminal will show the following:</p><pre>✔  hosting[YOUR_FIREBASE_PROJECT_ID]: Local server: http://127.0.0.1:5002<br>✔  functions: Loaded functions definitions from source: sendEmail.<br>✔  functions[us-central1-sendEmail]: http function initialized (http://127.0.0.1:5001/&lt;projectId&gt;/us-central1/sendEmail).</pre><p>Now your project is available at http://localhost:5002 using the Cloud Functions emulator.</p><h3>Security</h3><p>You might have noticed that the Cloud Functions code uses process.env to retrieve the Gmail address and app password. While this is okay for testing, it is <a href="https://firebase.google.com/docs/functions/config-env?gen=2nd#env-variables">not a secure way to store sensitive information</a>.</p><p>When writing code for production, consider using <a href="https://firebase.google.com/docs/functions/config-env?gen=2nd#secret-manager">Google Cloud Secret Manager</a>. This encrypted service stores configuration values securely, while still allowing easy access from your functions when needed.</p><p>Similar to Cloud Functions to how .env.local take precedence over .env you can override secrets values by setting up a .secret.local file. This makes it easy for you to test your functions locally.</p><p>Refer to the <a href="https://firebase.google.com/docs/functions">Firebase Cloud Functions documentation</a> to learn how to safely <a href="https://firebase.google.com/docs/functions/config-env?gen=2nd">configure your environment</a> for production and <a href="https://firebase.google.com/docs/emulator-suite/connect_functions#configure_a_local_testing_environment">testing with the Cloud Functions Emulator</a>.</p><h3>Conclusion</h3><p>Sending emails with Firebase Cloud Functions might involve some initial setup, but it offers a robust and secure solution in the long run. By leveraging Nodemailer and external email service providers, you can automate emails without managing a separate server.</p><p>Moreover, Firebase Security Rules ensure only authorized functions can access sensitive information like email credentials. This combination provides a reliable and secure way to integrate email functionality within your Firebase app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2202f1abffac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animated Flutter Tooltip]]></title>
            <link>https://stassop.medium.com/animated-flutter-tooltip-c5fdcc4c613d?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5fdcc4c613d</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[tooltips]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 13:28:02 GMT</pubDate>
            <atom:updated>2025-09-25T12:14:24.162Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building Rich and Intuitive Tooltips in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JinCGaAWkjuP6-Jk" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Flutter Material Tooltip</h3><p>Flutter’s built-in tooltip, though functional, lacks visual appeal and customization options. Let’s create an animated and customisable tooltip to take the user experience to the next level!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*KSYFSq7hwUelWnmWjbI_0w.gif" /><figcaption>Flutter Material Tooltip</figcaption></figure><h3>What We’ll Be Building</h3><p>We want a tooltip with an arrow that scales to the optimal content size, positions itself relative to the target using available space, and emerges from the center of the target.</p><p>You can find the complete example <a href="https://github.com/stassop/flutter_animated_tooltip">here</a>. The animation is actually smooth when run on the simulator. Unfortunately, gif screen recording doesn’t capture smooth animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*3gpPQfdT18rbQvZQ8b_krQ.gif" /><figcaption><a href="https://github.com/stassop/flutter_animated_tooltip">https://github.com/stassop/flutter_animated_tooltip</a></figcaption></figure><h3>How It Works</h3><p>To display the tooltip above the rest of the UI we use an <a href="https://api.flutter.dev/flutter/widgets/Overlay-class.html">Overlay</a>. Flutter’s OverlayPortal.targetsRootOverlay creates an overlay portal that renders its widget on the root Overlay when shown.</p><p>Thanks to Flutter’s extensive widget library, most of the essential components are already there, minimising the need for custom work. There’s only four things we need to calculate ourselves:</p><ul><li>The vertical position of the tooltip relative to the target</li><li>The horizontal alignment of the tooltip relative to the target</li><li>The horizontal alignment of the arrow relative to the target</li><li>The alignment (origin point) of the animation</li></ul><p>For vertical positioning, we use the <a href="https://api.flutter.dev/flutter/widgets/Positioned-class.html">Positioned</a> widget&#39;s top and bottom properties to position the tooltip above or below the target based on available space.</p><p>The tooltip’s horizontal alignment is based on the target&#39;s horizontal position relative to the screen width. The <a href="https://api.flutter.dev/flutter/widgets/Align-class.html">Align</a> widget uses a relative system: -1 (far left), 0 (center), 1 (far right).</p><p>Here’s what the code looks like:</p><pre>void _updatePosition() {<br>  final Size contextSize = MediaQuery.of(context).size;<br>  final BuildContext? targetContext = widget.targetGlobalKey != null<br>    ? widget.targetGlobalKey!.currentContext<br>    : context;<br>  final targetRenderBox = targetContext?.findRenderObject() as RenderBox;<br>  final targetOffset = targetRenderBox.localToGlobal(Offset.zero);<br>  final targetSize = targetRenderBox.size;<br>  // Try to position the tooltip above the target, <br>  // otherwise try to position it below or in the center of the target.<br>  final tooltipFitsAboveTarget = targetOffset.dy - _tooltipMinimumHeight &gt;= 0;<br>  final tooltipFitsBelowTarget = targetOffset.dy + targetSize.height + _tooltipMinimumHeight &lt;= contextSize.height;<br>  _tooltipTop = tooltipFitsAboveTarget<br>      ? null<br>      : tooltipFitsBelowTarget<br>          ? targetOffset.dy + targetSize.height<br>          : null;<br>  _tooltipBottom = tooltipFitsAboveTarget<br>      ? contextSize.height - targetOffset.dy<br>      : tooltipFitsBelowTarget<br>          ? null<br>          : targetOffset.dy + targetSize.height / 2;<br>  // If the tooltip is below the target, invert the arrow.<br>  _isInverted = _tooltipTop != null;<br>  // Align the tooltip horizontally relative to the target.<br>  _tooltipAlignment = Alignment(<br>    (targetOffset.dx) / (contextSize.width - targetSize.width) * 2 - 1.0,<br>    _isInverted ? 1.0 : -1.0,<br>  );<br>  // Make the tooltip appear from the target.<br>  _transitionAlignment = Alignment(<br>    (targetOffset.dx + targetSize.width / 2) / contextSize.width * 2 - 1.0,<br>    _isInverted ? -1.0 : 1.0,<br>  );<br>  // Center the arrow horizontally on the target.<br>  _arrowAlignment = Alignment(<br>    (targetOffset.dx + targetSize.width / 2) / (contextSize.width - _arrowSize.width) * 2 - 1.0,<br>    _isInverted ? 1.0 : -1.0,<br>  );<br>}</pre><h3>Tooltip Arrow</h3><p>We use a <a href="https://api.flutter.dev/flutter/rendering/CustomPainter-class.html">CustomPainter</a> to draw the arrow. One thing to keep in mind is that when the tooltip is positioned below the target (inverted), the arrow needs to be flipped upside down.</p><pre>class TooltipArrowPainter extends CustomPainter {<br>  final Size size;<br>  final Color color;<br>  final bool isInverted;<br><br>  TooltipArrowPainter({<br>    required this.size,<br>    required this.color,<br>    required this.isInverted,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = color<br>      ..style = PaintingStyle.fill;<br><br>    final path = Path();<br><br>    if (isInverted) {<br>      path.moveTo(0.0, size.height);<br>      path.lineTo(size.width / 2, 0.0);<br>      path.lineTo(size.width, size.height);<br>    } else {<br>      path.moveTo(0.0, 0.0);<br>      path.lineTo(size.width / 2, size.height);<br>      path.lineTo(size.width, 0.0);<br>    }<br>    <br>    path.close();<br><br>    canvas.drawShadow(path, Colors.black, 4.0, false);<br>    <br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(covariant CustomPainter oldDelegate) =&gt; false;<br>}<br><br>class TooltipArrow extends StatelessWidget {<br>  final Size size;<br>  final Color color;<br>  final bool isInverted;<br><br>  const TooltipArrow({<br>    super.key,<br>    this.size = const Size(16.0, 16.0),<br>    this.color = Colors.white,<br>    this.isInverted = false,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Transform.translate(<br>      offset: Offset(-size.width / 2, 0.0),<br>      child: CustomPaint(<br>        size: size,<br>        painter: TooltipArrowPainter(<br>          size: size,<br>          color: color,<br>          isInverted: isInverted,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>The Animation</h3><p>We can encapsulate all the animation logic within a single function. The widget utilises a <a href="https://api.flutter.dev/flutter/animation/CurvedAnimation-class.html">CurvedAnimation</a> that adjusts its direction (forward or reverse) based on whether the tooltip overlay is being shown or hidden.</p><pre>final _overlayController = OverlayPortalController();<br>late final AnimationController _animationController = AnimationController(<br>  duration: const Duration(milliseconds: 200),<br>  vsync: this,<br>);<br>late final Animation&lt;double&gt; _scaleAnimation = CurvedAnimation(<br>  parent: _animationController,<br>  curve: Curves.easeOutBack,<br>);<br><br>void _toggle() {<br>  _delayTimer?.cancel();<br>  _animationController.stop();<br>  if (_overlayController.isShowing) {<br>    _animationController.reverse().then((_) {<br>      _overlayController.hide();<br>    });<br>  } else {<br>    _updatePosition();<br>    _overlayController.show();<br>    _animationController.forward();<br>  }<br>}</pre><h3>Putting It All Together</h3><p>Now let’s assemble our widget. Note that if no theme is provided, the widget will use a theme with inverted brightness to create contrast and make the tooltip stand out.</p><pre>return OverlayPortal.targetsRootOverlay(<br>  controller: _overlayController,<br>  child: widget.child != null<br>      ? GestureDetector(onTap: _toggle, child: widget.child)<br>      : null,<br>  overlayChildBuilder: (context) {<br>    return Positioned(<br>      top: _tooltipTop,<br>      bottom: _tooltipBottom,<br>      // Provide a transition alignment to make the tooltip appear from the target.<br>      child: ScaleTransition(<br>        alignment: _transitionAlignment,<br>        scale: _scaleAnimation,<br>        // TapRegion allows the tooltip to be dismissed by tapping outside of it.<br>        child: TapRegion(<br>          onTapOutside: (PointerDownEvent event) {<br>            _toggle();<br>          },<br>          // If no theme is provided, a theme with inverted brightness is used.<br>          child: Theme(<br>            data: theme,<br>            // Don&#39;t allow the tooltip to get wider than the screen.<br>            child: SizedBox(<br>              width: MediaQuery.of(context).size.width,<br>              child: Column(<br>                mainAxisSize: MainAxisSize.min,<br>                children: [<br>                  if (_isInverted)<br>                    Align(<br>                      alignment: _arrowAlignment,<br>                      child: TooltipArrow(<br>                        size: _arrowSize,<br>                        isInverted: true,<br>                        color: theme.canvasColor,<br>                      ),<br>                    ),<br>                  Align(<br>                    alignment: _tooltipAlignment,<br>                    child: IntrinsicWidth(<br>                      child: Material(<br>                        elevation: 4.0,<br>                        color: theme.canvasColor,<br>                        borderRadius: BorderRadius.circular(8.0),<br>                        child: Padding(<br>                          padding: const EdgeInsets.all(16.0),<br>                          child: Column(<br>                            children: [<br>                              widget.content,<br>                              const SizedBox(height: 16.0),<br>                              Align(<br>                                alignment: Alignment.centerRight,<br>                                child: ElevatedButton(<br>                                  onPressed: _toggle,<br>                                  child: const Text(&#39;OK&#39;),<br>                                ),<br>                              ),<br>                            ],<br>                          ),<br>                        ),<br>                      ),<br>                    ),<br>                  ),<br>                  if (!_isInverted)<br>                    Align(<br>                      alignment: _arrowAlignment,<br>                      child: TooltipArrow(<br>                        size: _arrowSize,<br>                        isInverted: false,<br>                        color: theme.canvasColor,<br>                      ),<br>                    ),<br>                ],<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  },<br>);</pre><h3><strong>Conclusion</strong></h3><p>While Flutter offers a vast collection of widgets, some provide less-than-ideal user experiences. However, by leveraging existing widgets to create new ones you can significantly enhance the usability of your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5fdcc4c613d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Hero Page Route]]></title>
            <link>https://stassop.medium.com/flutter-hero-page-route-updated-8a5a01e11093?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5a01e11093</guid>
            <category><![CDATA[route]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[composition]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 13:39:56 GMT</pubDate>
            <atom:updated>2025-08-18T10:46:18.524Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create Hero-like Page Route Transitions in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D13Gapo60Ha-x-NF" /><figcaption>Photo by <a href="https://unsplash.com/@king_lip?utm_source=medium&amp;utm_medium=referral">King Lip</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Synopsis</h3><p>If you’re unfamiliar with the <a href="https://api.flutter.dev/flutter/widgets/Hero-class.html">Hero class</a>, have a look at this <a href="https://docs.flutter.dev/ui/animations/hero-animations">article about Hero animations</a>. Hero is a powerful Flutter class that enables seamless transitions of widgets between routes.</p><p>In contrast to standard Hero animations, which transition a single widget between screens, we want to apply a Hero animation to the entire screen. This results in more dramatic and engaging transitions.</p><p>Another great thing about the Hero class is its composability. Like any other Flutter widget, it can be composed or extended, enabling cool route transitions that animate the entire screen content.</p><p>In our example, we seamlessly morph the FloatingActionButton into a new screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*uXfaN9iBrnXGwZHMcPPPJw.gif" /><figcaption><a href="https://github.com/stassop/flutter_hero_page_route">https://github.com/stassop/flutter_hero_page_route</a></figcaption></figure><h3>How It Works</h3><p>The <a href="https://api.flutter.dev/flutter/widgets/Hero-class.html">Hero class</a> does most of the heavy lifting here by creating a smooth transition between the origin and destination widgets. But what if we want more control over the animation?</p><p>To switch routes, <a href="https://docs.flutter.dev/cookbook/navigation/navigation-basics#2-navigate-to-the-second-route-using-navigatorpush">Navigator.push()</a> expects a descendant of the <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a> class, such as <a href="https://api.flutter.dev/flutter/material/MaterialPageRoute-class.html">MaterialPageRoute</a>. To create a custom route transition, we can use <a href="https://api.flutter.dev/flutter/widgets/PageRouteBuilder-class.html">PageRouteBuilder</a> class, as described in this <a href="https://docs.flutter.dev/cookbook/animation/page-route-animation">recipe</a>.</p><p>To avoid wrapping each route in PageRouteBuilder, we extend it instead. We then call the superclass, and use its pageBuilder property to gain full control of the route transition animation.</p><p>The pageBuilder callback receives an animation argument that we can use to control the route transition. This allows us to animate other properties like shape, color, and elevation.</p><p>In order to apply a custom animation <a href="https://api.flutter.dev/flutter/animation/Curves-class.html">Curve</a>, we extend the default <a href="https://api.flutter.dev/flutter/material/MaterialRectArcTween-class.html">MaterialRectArcTween</a> class, responsible for Hero’s flight path, and pass it to the createRectTween property.</p><p>Finally, we wrap the Hero’s child in a Material widget. This enables us to transition between the initial and final shape, color, and elevation. We then AnimatedBuilder to run the animation.</p><p>Here’s what the code looks like:</p><pre>import &#39;dart:ui&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class CurvedRectTween extends MaterialRectArcTween {<br>  CurvedRectTween({<br>    required super.begin,<br>    required super.end,<br>    required this.curve,<br>  });<br><br>  final Curve curve;<br><br>  @override<br>  Rect lerp(double t) {<br>    return super.lerp(curve.transform(t));<br>  }<br>}<br><br>class HeroPageRoute extends PageRouteBuilder {<br>  final Color? beginColor;<br>  final Curve curve;<br>  final double? beginElevation;<br>  final Duration duration;<br>  final ShapeBorder? beginShape;<br>  final String tag;<br>  final Widget child;<br><br>  HeroPageRoute({<br>    required this.child,<br>    required this.tag,<br>    this.beginColor,<br>    this.curve = Curves.easeInOut,<br>    this.beginElevation,<br>    this.beginShape,<br>    this.duration = const Duration(milliseconds: 500),<br>  }) : super(<br>          transitionDuration: duration,<br>          reverseTransitionDuration: duration,<br>          pageBuilder: (<br>            BuildContext context,<br>            Animation&lt;double&gt; animation,<br>            Animation&lt;double&gt; secondaryAnimation,<br>          ) {<br>            return Hero(<br>              tag: tag,<br>              createRectTween: (begin, end) =&gt;<br>                  CurvedRectTween(begin: begin, end: end, curve: curve),<br>              child: HeroAnimatedContainer(<br>                animation: animation,<br>                beginShape: beginShape ??<br>                    const RoundedRectangleBorder(<br>                      borderRadius: BorderRadius.all(Radius.circular(16)),<br>                    ),<br>                endShape: const RoundedRectangleBorder(<br>                  borderRadius: BorderRadius.zero,<br>                ),<br>                beginElevation: beginElevation ?? 6.0,<br>                endElevation: 0.0,<br>                beginColor: beginColor ??<br>                    Theme.of(context).colorScheme.primaryContainer,<br>                endColor: Colors.transparent,<br>                curve: curve,<br>                child: child,<br>              ),<br>            );<br>          },<br>        );<br>}<br><br>class HeroAnimatedContainer extends StatelessWidget {<br>  final Animation&lt;double&gt; animation;<br>  final Widget child;<br>  final ShapeBorder beginShape;<br>  final ShapeBorder endShape;<br>  final double beginElevation;<br>  final double endElevation;<br>  final Color beginColor;<br>  final Color endColor;<br>  final Curve curve;<br><br>  const HeroAnimatedContainer({<br>    super.key,<br>    required this.animation,<br>    required this.child,<br>    required this.beginShape,<br>    required this.endShape,<br>    required this.beginElevation,<br>    required this.endElevation,<br>    required this.beginColor,<br>    required this.endColor,<br>    this.curve = Curves.easeInOut,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final curvedAnimation = CurvedAnimation(<br>      parent: animation,<br>      curve: curve,<br>    );<br><br>    return AnimatedBuilder(<br>      animation: curvedAnimation,<br>      builder: (context, _) {<br>        final t = curvedAnimation.value;<br><br>        return Material(<br>          shape: ShapeBorderTween(begin: beginShape, end: endShape).lerp(t),<br>          elevation: lerpDouble(beginElevation, endElevation, t) ?? 0.0,<br>          color: Color.lerp(beginColor, endColor, t) ?? Colors.transparent,<br>          clipBehavior: Clip.antiAlias,<br>          child: Opacity(<br>            opacity: t.clamp(0.0, 1.0),<br>            child: child,<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}</pre><h3>Putting It All Together</h3><p>In our example, we want the second route’s content appear to originate from the <a href="https://api.flutter.dev/flutter/material/FloatingActionButton-class.html">FloatingActionButton</a>, so we use the button’s default properties as the starting point of our animation.</p><p>Unfortunately, some default properties might not be defined in the default theme (e.g. Theme.of(context).floatingActionButtonTheme.shape), so we use the null-coalescing (??) operator to provide backup values.</p><p>Since our HeroPageRoute is essentially a subclass of <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>, we can use the Navigator.of(context).push method to add it to the route stack. However, it still requires a tag for the Hero to use.</p><p>Finally, we can apply custom duration and curve. These are optional since Hero defaults to Curves.fastOutSlowIn and PageRouteBuilder uses a 300-millisecond transition by default.</p><p>You can find the complete example <a href="https://github.com/stassop/flutter_hero_page_route">here</a>.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;package:flutter_hero_page_route/hero_page_route.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Hero Page Route&#39;,<br>      theme: ThemeData(<br>        useMaterial3: true,<br>        primarySwatch: Colors.deepPurple,<br>      ),<br>      home: const HomePage(),<br>    );<br>  }<br>}<br><br>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final theme = Theme.of(context);<br>    final fabTheme = theme.floatingActionButtonTheme;<br>    final beginElevation = fabTheme.elevation ?? 6.0;<br>    final beginShape = fabTheme.shape ??<br>        const RoundedRectangleBorder(<br>          borderRadius: BorderRadius.all(Radius.circular(16.0)),<br>        );<br>    final beginColor = fabTheme.backgroundColor ?? theme.colorScheme.primaryContainer;<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Home Page&#39;),<br>      ),<br>      body: const Center(<br>        child: Text(&#39;Home page&#39;),<br>      ),<br>      floatingActionButton: FloatingActionButton.extended(<br>        heroTag: &#39;my_hero_route&#39;,<br>        onPressed: () {<br>          Navigator.of(context).push(<br>            HeroPageRoute(<br>              tag: &#39;my_hero_route&#39;,<br>              child: const NextPage(),<br>              curve: Curves.easeInOut,<br>              duration: const Duration(milliseconds: 1000),<br>              beginElevation: beginElevation,<br>              beginShape: beginShape,<br>              beginColor: beginColor,<br>            ),<br>          );<br>        },<br>        label: const Text(&#39;Next Page&#39;),<br>      ),<br>    );<br>  }<br>}<br><br>class NextPage extends StatelessWidget {<br>  const NextPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Next Page&#39;),<br>      ),<br>      body: const Center(<br>        child: Text(&#39;Next page&#39;),<br>      ),<br>    );<br>  }<br>}</pre><h3>Conclusion</h3><p>While Flutter generally favours <a href="https://docs.flutter.dev/resources/inside-flutter#aggressive-composability">composition over inheritance</a>, extending its classes can significantly enhance customization, leading to dramatic effects and highly personalized user interfaces.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5a01e11093" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing Flutter SearchAnchor]]></title>
            <link>https://stassop.medium.com/debouncing-flutter-searchanchor-65101042e5aa?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65101042e5aa</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[rxdart]]></category>
            <category><![CDATA[searchbar]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 17:04:45 GMT</pubDate>
            <atom:updated>2024-03-09T09:57:40.389Z</atom:updated>
            <content:encoded><![CDATA[<h4>With and Without Third-party Libraries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZyP6Ve6PuhlG2UJ" /><figcaption>Photo by <a href="https://unsplash.com/@arnosenoner?utm_source=medium&amp;utm_medium=referral">Arno Senoner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p><a href="https://api.flutter.dev/flutter/material/SearchAnchor-class.html">SearchAnchor</a> is probably one of the most useful Material widgets. There’s a small problem however: it doesn’t appear to have any debouncing mechanism.</p><p>Debouncing works by introducing a delay between consecutive event occurrences, ensuring that a function is only executed after a specified quiet period following the last event.</p><p>In the case of SearchAnchor it means that when the user is typing, the suggestionsBuilder function is called multiple times, causing flicker and consecutive sets of search results to appear.</p><p>The obvious solution would be to fetch the results in an async function delayed by a Timer and update the state. Unfortunately, this won’t work because widget state and that of SearchAnchor aren’t synced.</p><h3>What Does Google Say?</h3><p>Here’s what Google Gemini tells us about the issue:</p><blockquote>The reason suggestionBuilder in SearchAnchor might not rebuild even when the list is refreshed is due to a known limitation in Flutter.</blockquote><blockquote>Here’s a breakdown of the issue:</blockquote><blockquote><strong>Normal behavior:</strong></blockquote><blockquote>Ideally, any changes to the data used by a widget should trigger a rebuild, ensuring the UI reflects the updated information.</blockquote><blockquote><strong>SearchAnchor limitation:</strong></blockquote><blockquote>In the case of SearchAnchor, when the suggestion list is refreshed based on user interaction (e.g., typing in the search bar), the suggestionBuilder itself might not automatically rebuild due to the way Flutter manages state updates within this specific widget.</blockquote><p>Gemini goes on to suggest using StatefulBuilder or ValueListenableBuilder, neither of which work.</p><p>Great! Now what?</p><h3>Solution #1: RxDart</h3><p><a href="https://pub.dev/packages/rxdart">RxDart</a> is a powerful package that extends the capabilities of Dart <a href="https://api.dart.dev/stable/dart-async/Stream-class.html">Streams</a> and <a href="https://api.dart.dev/stable/dart-async/StreamController-class.html">StreamControllers</a>. It also offers a neat and concise way of creating a debounced stream of function calls.</p><p>Here’s what the code looks like:</p><pre>class DebouncedSearchBarState&lt;T&gt; extends State&lt;DebouncedSearchBar&lt;T&gt;&gt; {<br>  final _searchController = SearchController();<br>  final _debouncedSearchRx = BehaviorSubject&lt;String&gt;.seeded(&#39;&#39;);<br><br>  Future&lt;Iterable&lt;T&gt;&gt; _search(String query) async {<br>    if (query.isEmpty) {<br>      return &lt;T&gt;[];<br>    }<br><br>    try {<br>      final results = await widget.searchFunction(query);<br>      return results;<br>    } catch (error) {<br>      return &lt;T&gt;[];<br>    }<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _searchController.addListener(() {<br>      _debouncedSearchRx.add(_searchController.text);<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    _searchController.dispose();<br>    _debouncedSearchRx.close();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SearchAnchor(<br>      searchController: _searchController,<br>      builder: (BuildContext context, SearchController controller) {<br>        return SearchBar(<br>          controller: controller,<br>          onTap: () {<br>            controller.openView();<br>          },<br>        );<br>      },<br>      suggestionsBuilder: (BuildContext context, SearchController controller) async {<br>        final results = await _debouncedSearchRx<br>            .debounceTime(const Duration(milliseconds: 500))<br>            .asyncMap((query) =&gt; widget.searchFunction(query))<br>            .first;<br>        return results.map((result) {<br>          return ListTile(<br>            title: Text(result),<br>            onTap: () {<br>              widget.onResultSelected?.call(result);<br>              controller.closeView(controller.text);<br>            },<br>          );<br>        }).toList();<br>      },<br>    );<br>  }<br>}</pre><h3>Solution #2: Using Completers</h3><p>What if you want more granular control over your code or you don’t want to use a third-party library? Fortunately, there’s a solution, and it’s actually mentioned in one of the SearchAnchor docs <a href="https://api.flutter.dev/flutter/material/SearchAnchor-class.html#material.SearchAnchor.4">examples</a>.</p><p>This solution requires two extra parts:</p><pre>/// Returns a new function that is a debounced version of the given function.<br>/// This means that the original function will be called only after no calls<br>/// have been made for the given Duration.<br>_Debounceable&lt;S, T&gt; _debounce&lt;S, T&gt;(_Debounceable&lt;S?, T&gt; function) {<br>  _DebounceTimer? debounceTimer;<br><br>  return (T parameter) async {<br>    if (debounceTimer != null &amp;&amp; !debounceTimer!.isCompleted) {<br>      debounceTimer!.cancel();<br>    }<br>    debounceTimer = _DebounceTimer();<br>    try {<br>      await debounceTimer!.future;<br>    } catch (error) {<br>      print(error); // Should be &#39;Debounce cancelled&#39; when cancelled.<br>      return null;<br>    }<br>    return function(parameter);<br>  };<br>}</pre><p>Next, we need a Timer that acts like a Future but is cancelable:</p><pre>// A wrapper around Timer used for debouncing.<br>class _DebounceTimer {<br>  _DebounceTimer() {<br>    _timer = Timer(_duration, _onComplete);<br>  }<br><br>  late final Timer _timer;<br>  final Duration _duration = const Duration(milliseconds: 500);<br>  final Completer&lt;void&gt; _completer = Completer&lt;void&gt;();<br><br>  void _onComplete() {<br>    _completer.complete();<br>  }<br><br>  Future&lt;void&gt; get future =&gt; _completer.future;<br><br>  bool get isCompleted =&gt; _completer.isCompleted;<br><br>  void cancel() {<br>    _timer.cancel();<br>    _completer.completeError(&#39;Debounce cancelled&#39;);<br>  }<br>}</pre><p>Finally, wrap your search function in the above:</p><pre>class DebouncedSearchBarState&lt;T&gt; extends State&lt;DebouncedSearchBar&lt;T&gt;&gt; {<br>  final _searchController = SearchController();<br>  late final _Debounceable&lt;Iterable&lt;T&gt;?, String&gt; _debouncedSearch;<br><br>  Future&lt;Iterable&lt;T&gt;&gt; _search(String query) async {<br>    if (query.isEmpty) {<br>      return &lt;T&gt;[];<br>    }<br><br>    try {<br>      final results = await widget.searchFunction(query);<br>      return results;<br>    } catch (error) {<br>      return &lt;T&gt;[];<br>    }<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _debouncedSearch = _debounce&lt;Iterable&lt;T&gt;?, String&gt;(_search);<br>  }<br><br>  @override<br>  void dispose() {<br>    _searchController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SearchAnchor(<br>      searchController: _searchController,<br>      builder: (BuildContext context, SearchController controller) {<br>        return SearchBar(<br>          controller: controller,<br>          padding: const MaterialStatePropertyAll&lt;EdgeInsets&gt;(<br>              EdgeInsets.symmetric(horizontal: 16.0)),<br>          onTap: () {<br>            controller.openView();<br>          },<br>          leading: const Icon(Icons.search),<br>          hintText: widget.hintText,<br>        );<br>      },<br>      suggestionsBuilder: (BuildContext context, SearchController controller) async {<br>        final results = await _debouncedSearch(controller.text);<br>        if (results == null) {<br>          return &lt;Widget&gt;[];<br>        }<br>        return results.map((result) {<br>          return ListTile(<br>            title: Text(result),<br>            onTap: () {<br>              widget.onResultSelected?.call(result);<br>              controller.closeView(controller.text);<br>            },<br>          );<br>        }).toList();<br>      },<br>    );<br>  }<br>}</pre><h3>Which Solution to Choose?</h3><p>Both approaches achieve debouncing, but the rxdart solution is generally considered more efficient and easier to manage for complex scenarios. Choose the approach that best suits your project&#39;s dependencies and preferences.</p><h3>Complete Example</h3><p>The complete example can be found <a href="https://github.com/stassop/flutter_debounced_search_bar">here</a>. It uses the <a href="https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/iTuneSearchAPI/">iTunes Search API</a> to search for music. The API is free and doesn’t require registration or an auth key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*36flqy4u8xVtq9j5RzmGWQ.gif" /><figcaption><a href="https://github.com/stassop/flutter_debounced_search_bar">https://github.com/stassop/flutter_debounced_search_bar</a></figcaption></figure><h3>Conclusion</h3><p>Use debouncing to avoid unnecessary API calls and optimize your code. I recommend spending more time looking into how this code works in order to choose the optimal solution for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65101042e5aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting Flutter as a React Native Developer]]></title>
            <link>https://stassop.medium.com/starting-flutter-as-a-react-native-developer-6773fe3ec2a7?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6773fe3ec2a7</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 13:03:14 GMT</pubDate>
            <atom:updated>2024-03-07T09:43:23.318Z</atom:updated>
            <content:encoded><![CDATA[<h4>First Impression and Beyond</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q7s-hioWg1lNYg5C" /><figcaption>Photo by <a href="https://unsplash.com/@bradencollum?utm_source=medium&amp;utm_medium=referral">Braden Collum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Flutter is <a href="https://medium.com/flutter">developing rapidly</a>, with a focus on performance and development experience, and is actively <a href="https://flutter.dev/community">engaging the community</a>. And while React Native was a great alternative to other frameworks when it was released in 2015, its paradigms might be somewhat dated for the needs and demands of mobile development in 2021.</p><p>The purpose of this article is not to list all the <a href="https://flutter.dev/docs/get-started/flutter-for/react-native-devs">differences between Flutter and React Native</a> or go over all the cons and pros— there’s plenty of other sources that would do a much better job — but rather to describe things that struck me as different as a React Native developer.</p><h3><strong>Composition vs Inheritance</strong></h3><p>One of the best features of Flutter is the ability to extend existing classes, in contrast to React Native, which <a href="https://reactjs.org/docs/composition-vs-inheritance.html">discourages inheritance in favour of composition</a>. Flutter’s comprehensive <a href="https://flutter.dev/docs">documentation</a> and <a href="https://flutter.dev/docs/cookbook">tutorials</a> make it easy to find the right class to extend.</p><p>Not only does it greatly reduce the amount of code you have to write yourself, but also practically removes the need for third-party plugins, since virtually any lacking functionality can be easily added on top of existing code.</p><h3><strong>Documentation</strong></h3><p>In order to make sense of Flutter you’ll have to do some reading, perhaps even more so than with React Native. Without a good grasp of basic Flutter concepts, some <a href="https://flutter.dev/docs/testing/common-errors">errors</a> can be hard to understand and will slow you down significantly.</p><p>That said, <a href="https://flutter.dev/docs">Flutter documentation</a> is very rich with plenty of examples, and there’s a widget for everything, so reading the docs will save you a lot of time. Also, there’s many ways to achieve the same result, and having the knowledge will help you pick the right one.</p><h3><strong>Dart vs TypeScript</strong></h3><p>If you’re used to TypeScript, Dart will feel familiar, with the exception that TypeScript is a strongly typed superset of JavaScript, while Dart is a complete programming language. There’s already plenty of <a href="https://jworks.io/dart-vs-typescript-vs-kotlin-js/">Dart vs TypeScript</a> articles around, so I won’t go over all the cons and pros here.</p><p>Learning Dart felt surprisingly easy with the <a href="https://dart.dev/guides/language/language-tour">language tour</a> and <a href="https://dart.dev/samples">code samples</a> available on the <a href="https://dart.dev/">Dart website</a>. Dart is also perfectly suited for this purpose given the Flutter coding style and the common practice of extending Flutter classes.</p><h3><strong>Components vs Widgets</strong></h3><p>Say goodbye to JSX, and say hello to <a href="https://flutter.dev/docs/resources/inside-flutter#aggressive-composability">aggressive composability</a>. Although after JSX components Flutter widgets might seem a little verbose, once you get used to the new way of doing things, there’s plenty of ways to make it more concise and readable.</p><p>Although <a href="https://flutter.dev/docs/perf">performance</a> is paramount in Flutter, you can’t always expect it to do the work for you. Just like in React Native there are some considerations you have to make as a developer in order to keep your code performant and avoid bottlenecks.</p><h3><strong>State Management</strong></h3><p>State management using <a href="https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple">Provider/Consumer</a> is surprisingly simple, although some of its limitations might make you build odd workarounds. That said, there’s plenty of <a href="https://flutter.dev/docs/development/data-and-backend/state-mgmt/options">other options</a>, including Redux, so you’re never tied to a single solution.</p><p>For the rest, if you’re already familiar with the React concepts of State, Provider, Container and Context, using state in Flutter won’t feel much different. Likewise, you’ll have to consider whether something has to be in the local or in the global state.</p><h3><strong>Debugging</strong></h3><p>Flutter <a href="https://flutter.dev/docs/development/tools/devtools">DevTools</a> is surprisingly similar to <a href="https://github.com/jhen0409/react-native-debugger">React Native Debugger</a>, but runs in the browser, much like React <a href="https://reactnative.dev/docs/debugging#chrome-developer-tools">Chrome Developer Tools</a>. It offers a similar set of features and interface, which doesn’t take long to get used to for a React Native developer.</p><p>As far as error messages are concerned, I’m tempted to say that React Native does it better, although I might be biased. As mentioned earlier, understanding Flutter errors requires some background knowledge, and can quickly become frustrating without it.</p><h3><strong>Conclusion</strong></h3><p>Despite what feels like a higher entry barrier at first, learning Flutter is a rewarding experience. Once you get past the initial learning curve and gain some momentum, you’ll be surprised how powerful it really is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6773fe3ec2a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Startup Red Flags]]></title>
            <link>https://stassop.medium.com/five-startup-red-flags-5e3a950b8c36?source=rss-457b4af4514b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3a950b8c36</guid>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[lean-startup]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Stanislav Sopov]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 17:22:13 GMT</pubDate>
            <atom:updated>2024-03-07T09:46:09.528Z</atom:updated>
            <content:encoded><![CDATA[<h4>Early Signs Your Project May be in Trouble</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xCbfaVRlEkzPtcxrQy9EA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@studiorepublic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Studio Republic</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve worked for a number of startups in the past ten years. Some of them soared to success while others never managed to get past the tipping point. Over time I grew curious why some startups become successful and others don’t. As I started reading books about startup management and digital entrepreneurship, a number of patterns emerged that confirmed my experiences. Here are some of them.</p><h3><strong>Not Running Analytics</strong></h3><p><a href="https://hbr.org/2018/01/is-your-companys-data-actually-valuable-in-the-ai-era">Data is the new oil</a>. Your product, no matter how well-researched and planned, may still fail because the reality of the digital market is often not how we imagine it or how common logic dictates it should be. But even if your product ends up being unsuccessful you can still gain some valuable insights from its data. Those insights can guide you on your next venture or even help you to timely pivot and save a failing startup. But not collecting data or running analytics is likely to leave you none the wiser.</p><h3><strong>Arbitrary Tech Stack</strong></h3><p>If your stack is mainly determined by the skills currently available within the team—and not by it being the best fit for the job—it may create some serious issues down the road. It can be argued that it doesn’t really matter in the early stages of a startup, since the goal is to test an idea and do it quick. But issues like performance, scalability, and the availability of relevant skills on the job market may pop up sooner than you expect and slow you down while time is still precious.</p><h3><strong>Not Following the 80/20 Rule</strong></h3><p>This goes for both features and their implementation. Trying to deliver a polished feature before it’s been validated is a waste of time. According to research <a href="https://www.pendo.io/pendo-blog/pendo-data-suggests-29-5-billion-global-cloud-rd-investment-squandered-software-features-go-unused/">80% of features are rarely or never used</a>. The same goes for trying to catch every edge case no matter how rare. In the early stages of a startup, anything you build must be validated by data. Build the absolute minimum you can get away with and demand tangible proof for anything that comes on top of that.</p><h3><strong>Not Removing Unsuccessful Features</strong></h3><p>This dovetails into the previous point: most features end up unused. But new features also add complexity to the code that has to be maintained and increases the chance of bugs. Once you’ve found out a feature is not being actively used, it becomes a good candidate for removal. If you have compelling data you may even opt for early removal based on prototype testing or <a href="https://hbr.org/2020/03/building-a-culture-of-experimentation">experiment results</a>. Also, the earlier you remove a feature, the lesser the chance it will annoy some of your users</p><h3><strong>MVP Taking Too Long</strong></h3><p>There’s a reason Marty Cagan calls it <a href="https://www.thegrowthfaculty.com/blog/Inspiredbookmartycagancreatingtechproducts">Minimum Viable Prototype</a> (not Product). If it’s taking months to build without something to show your users and stakeholders, it’s probably way past the Minimum phase. Remember, an MVP is a product discovery tool, not the actual product. There’s no way of knowing when it’s complete because you haven’t discovered what it has to do yet. During the product discovery phase there are <a href="https://www.emergeinteractive.com/insights/detail/what-is-a-minimum-viable-product-mvp/">other things</a> to worry about rather than delivering a slick piece of software. So don’t wait too long!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3a950b8c36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>