<?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 António Nicolau on Medium]]></title>
        <description><![CDATA[Stories by António Nicolau on Medium]]></description>
        <link>https://medium.com/@antonio.tioypedro1234?source=rss-9d49f8c1759b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2-9SsfPscxXuW03UhnThUw@2x.jpeg</url>
            <title>Stories by António Nicolau on Medium</title>
            <link>https://medium.com/@antonio.tioypedro1234?source=rss-9d49f8c1759b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:03:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antonio.tioypedro1234/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[5 Sorting Algorithms In Dart]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/5-sorting-algorithms-in-dart-c6aad21d5132?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6aad21d5132</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 15:30:21 GMT</pubDate>
            <atom:updated>2023-06-09T17:16:09.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGY1VNlAHRqTmZhUiyB5xA.jpeg" /></figure><p>As developers, we write algorithms everyday!</p><p>While Dart provides built-in sorting methods, having a solid understanding of sorting algorithms can enhance your overall programming skills and empower you to make informed decisions when it comes to designing efficient and scalable Flutter applications.</p><p>A sorting algorithm is a method for reorganising a large number of items into a specific order, such as alphabetical, highest-to-lowest value or shortest-to-longest distance.</p><p>There are many sorting algorithms to familiarize oneself with. Each of these algorithms has some pros and cons and can be chosen effectively depending on the size of data to be handled.</p><p>Let’s focus on five classic algorithms for now:</p><ol><li><strong>Insertion sort</strong></li><li><strong>Selection</strong></li><li><strong>Bubble sort</strong>,</li><li><strong>Merge sort</strong></li><li><strong>Quick</strong> <strong>sort</strong>.</li></ol><h3>Insertion Sort</h3><p>This algorithm is one of the simplest algorithms with a simple implementation.</p><p>It works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*krA0OFxEDgi8hVHJffCi4w.gif" /><figcaption>GIF credit: <a href="https://medium.com/yay-its-erica/algorithms-for-beginners-bubble-sort-insertion-sort-merge-sort-29bd5506cc48">medium-algorithms-for-beginners</a></figcaption></figure><p>The code that implements this routine is described below. The index j assumes the initial value values.length — 1 (last position) and the loop stop condition is satisfied when this index reaches 0 or when the value we want to insert in order is already in its position (values[j] &gt;= values[j-1]). If j reaches 0, the entire array has been evaluated and the algorithm must stop. Likewise, if values[j] &gt;= values[j-1] the algorithm must stop because the element we are trying to fit is already in its place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/997cbddeecc0c4619632f1943502fc97/href">https://medium.com/media/997cbddeecc0c4619632f1943502fc97/href</a></iframe><p>Insertion Sort applies sorted insertion multiple times to sort a sequence. We are going to do it by adding the for command with i ranging from 1 to the end and j varying according to i .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e16cb606635e7679f5eba2caaac1759f/href">https://medium.com/media/e16cb606635e7679f5eba2caaac1759f/href</a></iframe><h3>Selection Sort</h3><p>If you ask someone who is not familiarised with algorithm to sort a number sequence, probably this person is going to apply Selection Sort. It because Selection Sort follow a basic routine: “<strong>select the minimum value in the sequence and put that on the first position</strong>”. The idea is execute those two steps until the sequence is sorted.</p><p>In every iteration of selection sort, the <strong>minimum</strong> element from the unsorted subarray is picked and moved to the sorted subarray. The selection sort has the property of minimizing the number of swaps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c64e46fa0e03378960bdccd40d7b861f/href">https://medium.com/media/c64e46fa0e03378960bdccd40d7b861f/href</a></iframe><h3>Bubble Sort</h3><p>Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended order.</p><p>This algorithm is not suitable for large data sets as its average and worst-case complexity are of Ο(n²) where <em>n</em> is the number of items</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*w3s3oXrDmUXYQjolAG-EcQ.gif" /><figcaption>GIF credit: <a href="https://www.pinterest.com/pin/365073113520665221/">Pinterest/wikipedia-fundation</a></figcaption></figure><p>The main idea is:</p><ul><li>traverse from left and compare adjacent elements and the higher one is placed at right side.</li><li>In this way, the largest element is moved to the rightmost end at first.</li><li>This process is then continued to find the second largest and place it and so on until the data is sorted.</li></ul><p>Below is the implementation of the bubble sort.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a11cd5a39f3fda02a310a2fcd8cbcde1/href">https://medium.com/media/a11cd5a39f3fda02a310a2fcd8cbcde1/href</a></iframe><h3>Merge Sort</h3><p>Merge Sort is an efficient divide-and-conquer algorithm. That works by dividing an array into smaller subarrays, sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array.</p><blockquote>In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each half, and then merge the sorted halves back together. This process is repeated until the entire array is sorted.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*opwN0BhtH4zvPF697fPlow.gif" /><figcaption>GIF credit: <a href="https://commons.wikimedia.org/wiki/File:Merge-sort-example-300px.gif">wikipedia-merge-sort-example</a></figcaption></figure><h4>Merge implementation</h4><p>The code for the merge method is described below. Let’s break down each implementation detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc96964bbdd794a6e7eca8b91f711297/href">https://medium.com/media/cc96964bbdd794a6e7eca8b91f711297/href</a></iframe><p>The method receives the array to be processed as a parameter. It also receives three indices: left, middle and right, which determine the limits in which the algorithm must act.</p><p>To do manipulations on our original array, we need an auxiliary array (tempArray) to store the state</p><pre>...<br><br>// create a temporary Array with elements of [values]<br>final tempArray = List.generate(values.length, (index) =&gt; values[index]);<br><br>...</pre><p>Next we define i, j and k, those are the indices used to control the execution and comparison of elements. i marks the beginning of the first part of the array, j marks the beginning of the second part of the array, and k marks the position where the smallest element between tempArray[i] and tempArray[j] should be added.</p><pre>...<br><br>int i = left;<br>int j = middle + 1;<br>int k = left;<br><br>...</pre><p>Now the algorithm make the comparison between tempArray[i] and tempArray[j] to add the minimum element in values[k].</p><pre>...<br><br>while (i &lt;= middle &amp;&amp; j &lt;= right) {<br>  if (tempArray[i] &lt;= tempArray[j]) {<br>    values[k] = tempArray[i];<br>    i++;<br>  } else {<br>    values[k] = tempArray[j];<br>    j++;<br>  }<br>  k++;<br>}<br><br>...</pre><p>At the end, just append all the elements of the part that was not completely consumed.</p><pre>...<br><br>// if did not consume initial part, append<br>while (i &lt;= middle) {<br>  values[k] = tempArray[i];<br>  i++;<br>  k++;<br>}<br><br>// if did not consume last part, append<br>while (j &lt;= right) {<br>  values[k] = tempArray[j];<br>  j++;<br>  k++;<br>}<br><br>...</pre><h4>Merge Sort implementation</h4><p>Merge Sort is a divide-and-conquer algorithm. The conquest part we already covered in great detail, we know how to combine two sorted arrays into one sorted array.</p><p>The division part is actually quite simple 🙂. Simply “split” the array recursively in half until only one element remains. Let’s see the code 👇🏿</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2988997d0ba76230917af7aaf9eb5495/href">https://medium.com/media/2988997d0ba76230917af7aaf9eb5495/href</a></iframe><p>Let’s break down this method.</p><p>Let’s analyse the signature of the method. The parameters are the array to be sorted, a left index and a right index, which delimit the portion of the array that the algorithm must analyse. In the first call we are going to have left = 0 and right = values.length — 1.</p><p>In the first line of the method, we have the stop condition of the algorithm (left &gt;= right).</p><p>We define middle as the middle value between left and right. Then we create recursive calls for the left half (from left to middle) and the right half (from middle + 1 to right).</p><p>Finally, after each break there is a call to the merge method, passing the limits to be considered (left, middle, right).</p><pre>...<br><br>int middle = (left + right) ~/ 2;<br>mergeSort(values, left, middle);<br>mergeSort(values, middle + 1, right);<br><br>merge(values, left, middle, right);<br><br>...</pre><p>Complete code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7352ff174909412e42dd24c820e1b317/href">https://medium.com/media/7352ff174909412e42dd24c820e1b317/href</a></iframe><h3>Quick Sort</h3><p>Quick Sort is also a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot such that all the smaller elements are to the left of the pivot and all the greater elements are to the right of the pivot. There are many different versions of quickSort that pick pivot in different ways:</p><ul><li>Always pick the first element as a pivot.</li><li>Always pick the last element as the pivot.</li><li>Pick a random element as a pivot (implemented below).</li><li>Pick the median as a pivot.</li></ul><p>The key process in quicksort is the partition() method. Partitioning means choosing any number present in the array as pivot, and placing it in a position such that all elements on the left are less than or equal and all elements on the right are greater..</p><p>For small inputs, quicksort is the best algorithm as compared to the merge sort. When you don’t need a stable sort and average-case performance matters more than worst-case performance, go for quicksort. Let’s see the partition algorithm and its implementation first.</p><h4>Partition algorithm</h4><p>We start from the rightmost element and keep track of the index of smaller (or equal to) elements as <em>r</em>.</p><ul><li>If we find an element <em>j</em> which is less than <em>r</em>, then we increment <em>i</em> pointer and swap the elements of i and j.</li><li>If we find an element<em> j</em> which is greater than <em>r</em>, then we simply increment<em> j</em> pointer.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c0cc0a556dee322482a7143a35ed3e5/href">https://medium.com/media/6c0cc0a556dee322482a7143a35ed3e5/href</a></iframe><p>First, let’s understand the signature of the partition method. It receives the array to be partitioned as a parameter. It also receives two valid indexes of the array (left and right) that determine the limits in which the algorithm must act. In the first call, left = 0 and right = values.length — 1.</p><p>The first two lines is the choice of random pivot (<em>you can also opt to always choose the pivot as first element [left=0]</em>).</p><p>Then we need to iterate over the array looking for the lesser or equal elements and swapping them with the positions ahead of the pivot.</p><p>When a value less than or equal to the pivot is found (if values[j] &lt;= pivot), we perform two steps:</p><ol><li>Increment i</li><li>Swap values[i] by values[j]</li></ol><p>When you finish the iteration, just change values[i] by the position of the pivot. That is, we exchange values[i] by values[left].</p><p>Finally, we return i which is the pivot’s final position.</p><h4>Quick Sort implementation</h4><p>Quick Sort, is run consecutive partitions. The first is carried out taking into account the entire array (left = 0 and right = values.length — 1). Then, the left of the pivot is taken into account, that is, left = 0 and right = indexPivot — 1 and the right of the pivot (left = indexPpivot + 1 and right = values.length — 1). Then the same process is done with the left and right of the new pivots and so on until the entire array has been traversed (left &gt;= right).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e72456da44e5b32d6c2ad9af51928925/href">https://medium.com/media/e72456da44e5b32d6c2ad9af51928925/href</a></iframe><p>Complete code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/675c045b2c6ecbcd8a4ab1ad43a7de2b/href">https://medium.com/media/675c045b2c6ecbcd8a4ab1ad43a7de2b/href</a></iframe><blockquote>I hope this Article gives you an overview of some of the most widely known sort algorithms and that you will start exploring more on your own 🙂.</blockquote><p>You are going to finding all algorithms here 👇🏿👇🏿</p><p><a href="https://github.com/antonio-nicolau/sorting-algortihm-with-dart">GitHub - antonio-nicolau/sorting-algortihm-with-dart: A Dart project to help understand how to implement sorting algorithms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6aad21d5132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter auto_route Guide]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-auto-route-guide-9ac405e8a941?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ac405e8a941</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[autoroute]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Mon, 29 May 2023 18:42:06 GMT</pubDate>
            <atom:updated>2023-05-30T11:07:56.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RYamLmnI2t10wpVNgt8Ysw.png" /></figure><h4>Why AutoRoute?</h4><p>When it comes to creating an app with a robust routing setup, handling deep-linking, nested navigation, guarded routes, and other advanced routing features can quickly become a tedious and time-consuming task.</p><p>AutoRoute simplifies the process of handling routing and navigation in Flutter applications.</p><p>In this article, we will explore the power and versatility of AutoRoute, demonstrating how it simplifies routing in your Flutter applications.</p><h3>Get started</h3><p>To get started, add auto_route to your pubspec.yaml. We also need to add auto_route_generator and build_runner to generate our routes.</p><pre>dependencies:                    <br>  auto_route: ^7.2.0  <br><br>dev_dependencies:<br>  auto_route_generator: ^7.1.1<br>  build_runner: ^2.4.4</pre><p>Remember to always check the latest version</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FppdJSbkKj25NvdxFQo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FppdJSbkKj25NvdxFQo%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FppdJSbkKj25NvdxFQo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="310" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b434f4a8510b937c449a57356bde01e/href">https://medium.com/media/4b434f4a8510b937c449a57356bde01e/href</a></iframe><h3>Route Configuration</h3><p>Lets add GoRouter configuration to your app:</p><ol><li>Create a router class and annotate it with @AutoRouterConfig then extend &quot;_$YourClassName&quot;</li><li>Override the routes getter</li></ol><pre>import &#39;package:auto_route/auto_route.dart&#39;;<br>part &#39;app_router.gr.dart&#39;;<br><br>@AutoRouterConfig()<br>class AppRouter extends _$AppRouter {<br>  @override<br>  List&lt;AutoRoute&gt; get routes =&gt; [<br>        // add your routes here<br>      ];<br>}</pre><p>Now simply run build_runner to generate our route, run one of commands below (I recommend the first one)👇🏿</p><pre>// to watch the files&#39;s system edits and rebuild as necessary<br>dart run build_runner watch<br><br>// to run build_runner just once<br>dart run build_runner build</pre><p>After you run the generator your router class will be generated</p><p>Now that we have our router configuration let’s hook it up to MaterialApp</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/befdf88350451194f586ee705aee1216/href">https://medium.com/media/befdf88350451194f586ee705aee1216/href</a></iframe><p>Now that we have our basic setup is time to add new routes. How to do that ??? 🙃</p><ol><li>choose which page you want to route</li><li>annotate it with @RoutePage and that’s it, auto_router is going to generate a new route for you based on your Widget configuration e.g Widget params</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d727f5e070e241bf32995ab3d1e7c62/href">https://medium.com/media/5d727f5e070e241bf32995ab3d1e7c62/href</a></iframe><p>You will need to run generator again so go_router can generate this route for you (only if you didn’t run with watch flag).</p><blockquote>Note that your automatically generated routes are going to be included on app_router.gr file previously created</blockquote><p>Add the generated route to your routes list</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a638928977575cd0d00b11a42b6cc1/href">https://medium.com/media/28a638928977575cd0d00b11a42b6cc1/href</a></iframe><p>If we want to make this route as our initial route just add initial=true in the AutoRoute constructor.</p><pre>List&lt;AutoRoute&gt; get routes =&gt; [<br>  // HomeRoute is now the initial<br>  AutoRoute(page: HomeRoute.page, initial: true),<br>];</pre><p>Now we have our basic route setup!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff6z5TkrTIBZILYOd1t%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOTVmNmYyZGI3N2JkYmZiOGVlNDAyMmVhNWE3ZGI3YTg0YWIzZDZkMiZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/4966cd38bacc4a061ed7f6b31cab49aa/href">https://medium.com/media/4966cd38bacc4a061ed7f6b31cab49aa/href</a></iframe><h4>Navigation Between Screens</h4><p>There are many ways to navigate between destinations with auto_route.</p><p>To navigate to a new screen, call context.router.push</p><pre>// navigate by DetailsPage<br>context.router.push(const DetailsRoute());</pre><p>we can also navigate by path, just call context.router.pushNamed</p><pre>// you can define paths when adding your route to route list<br>// e.g AutoRoute(path:&#39;/home&#39;, page: HomeRoute.page)<br>context.router.pushNamed(&#39;/details&#39;);</pre><p>Navigate back to previous location by calling context.router.back()</p><pre>// navigate to previous location<br>context.router.back();</pre><p>You can even add a list of routes to the pages stack</p><pre>// adds a list of routes to the pages stack<br>context.router.pushAll([<br>  const HomeRoute(),<br>  const DetailsRoute(),<br>]);</pre><h4>Passing Arguments</h4><p>AutoRoute automatically detects and handles page’s arguments for you, the generated route object will deliver all the arguments your page needs including path/query params</p><p>e.g Think about our HomePage, if we add a userId argument to it then when our HomeRoute be generated it’ll already have this argument create and if we say that this argument is required AutoRoute will automatically handle that</p><pre>@RoutePage()<br>class HomePage extends StatelessWidget {<br>  const HomePage({super.key, required this.userId});<br><br>  final String userId;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const Placeholder();<br>  }<br>}</pre><p>When we generate our HomeRoute and try to use, it is going to required userId argument</p><pre>// `userId` argument is required since we specified this way on HomePage<br>context.router.push(HomeRoute(userId: &#39;Antonio&#39;));</pre><h4>Working with Paths</h4><p>Working with paths in AutoRoute is optional because PageRouteInfo objects are matched by name unless pushed as a string using the deepLinkBuilder property in root delegate or pushNamed , replaceNamed navigateNamed methods.</p><p>When developing an app that requires deep-linking you’d probably need to define paths with clear memorable names, and that’s done using the path argument in AutoRoute.</p><pre>AutoRoute(path: &#39;/books&#39;, page: BookListPage),</pre><p>You can define a path parameters prefixing it with a colon</p><pre>AutoRoute(path: &#39;/books/:id&#39;, page: BookDetailsPage),</pre><p>Then you can extract path parameters from path by annotating constructor params with @PathParam(&#39;name&#39;) with the same name of the segment.</p><pre>class BookDetailsPage extends StatelessWidget {                    <br>  const BookDetailsPage({@PathParam(&#39;id&#39;) this.bookId});                <br>                  <br>  final int bookId;                    <br>  ...</pre><p>Now writing /books/1 in the browser will navigate you to BookDetailsPage and automatically extract the bookId argument from path and inject it to your widget.</p><h4>Working with Query parameters</h4><p>Same old way, simply annotate the constructor parameter to hold the value of the query param with @QueryParam(&#39;name&#39;) and let AutoRoute do the rest.</p><pre>RouteData.of(context).pathParams;                    <br> // or using the extension                    <br> context.routeData.queryParams</pre><blockquote>NOTE <em>if your parameter name is the same as the path/query parameter, you could use the const </em><em>@pathParam or </em><em>@queryParam and not pass a </em><em>@PathParam(‘name’)</em>.</blockquote><pre>@RoutePage()                  <br>class BookDetailsPage extends StatelessWidget {<br>  // since widget parameter and path parameter are the same don&#39;t need to add @PathParam(&#39;id&#39;)<br>  const BookDetailsPage({@pathParam this.id});                <br>                  <br>  final int id;                    <br>  ...</pre><h4>Redirecting Paths</h4><p>Paths can be redirected using RedirectRoute. The following setup will navigate us to /feed when / is matched.</p><pre>&lt;AutoRoute&gt; [                    <br>     RedirectRoute(path: &#39;/&#39;, redirectTo: &#39;/feed&#39;),                    <br>     AutoRoute(path: &#39;/feed&#39;, page: FeedRoute.page),                    <br> ]</pre><h3>Route Guards</h3><p>Guards are useful for restricting access to certain routes, it works as middleware meaning that routes can not be added to the stack without going through their assigned guards.</p><p>We create a route guard by extending AutoRouteGuard , implement onNavigation and add our logic there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d467924302cce16b216d25c4c8535e09/href">https://medium.com/media/d467924302cce16b216d25c4c8535e09/href</a></iframe><p>Now we assign our guard to the routes we want to protect.</p><pre>AutoRoute(page: FeedRoute.page, guards: [AuthGuard()]);</pre><h4>Global route guards</h4><p>You can also add guard to all your stack-routes. Let’s say you have an app with no public screens, you’d need to have a global guard and you can do it by having your Router implement AutoRouteGuard</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a601e37cb899c114d05ecd3d77828717/href">https://medium.com/media/a601e37cb899c114d05ecd3d77828717/href</a></iframe><h4>Using Deep-link</h4><p>AutoRoute will automatically handle deep-links coming from the platform.</p><p>AutoRoute has a deep link builder, an interceptor for deep-links where you can validate or override deep-links coming from the platform.</p><p>In the following example we will only allow deep-links starting with /products</p><pre>MaterialApp.router(<br>      routerConfig: _appRouter.config(<br>        deepLinkBuilder: (deepLink){<br>          if(deepLink.path.startsWith(&#39;/products&#39;){<br>           // continute with the platfrom link<br>            return deepLink;<br>          }else{<br>            return DeepLink.defaultPath;<br>            // or DeepLink.path(&#39;/&#39;)<br>            // or DeepLink([HomeRoute()])<br>          }<br>        }<br>      ),<br>    )</pre><h3>Nested navigation</h3><p>Nesting navigators means rendering a navigator inside a screen of another navigator.</p><p>To define nested routes we just</p><ol><li>add our nested routes as children field of parent route.</li><li>add AutoRouter widget to render nested routes</li></ol><p>Let’s add our nested children</p><blockquote>We’re supposing that AudioRoute and VideoRoute were already generated 🙂</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a9aaa5be501702eb98be23ba1e60fee/href">https://medium.com/media/0a9aaa5be501702eb98be23ba1e60fee/href</a></iframe><p>We can set initial=true or path=’’ to make one of children when accessing /feed</p><p>Now that we have our nested routes let’s add AutoRouter widget to render them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3717cc7fff7255e34bf0bfec73bca9a1/href">https://medium.com/media/3717cc7fff7255e34bf0bfec73bca9a1/href</a></iframe><p>Now if we navigate to /feed/audio we will be taken to the FeedPage and the AudioPage will be shown inside of it 👇🏿👇🏿</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*s2YsUbtpc7m1nTyKEGyXDw.gif" /></figure><p><strong>Things to keep in mind when implementing nested navigation</strong></p><ol><li>Each router manages it’s own pages stack.</li><li>Navigation actions like push, pop and friends are handled by the topmost router and bubble up if it couldn’t be handled.</li></ol><h3>Nested Tab navigation</h3><p>Some apps display destinations in a subsection of the screen, for example, a BottomNavigationBar that stays on-screen when navigating between Screens.</p><p>Since this is not an easy task to implement with Flutter apps auto_route makes tabs navigation as easy and straightforward as possible.</p><p>We’ll use AutoTabsRouter to handle tab navigation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7cb46b436f95cc5d269cd5785e9be8/href">https://medium.com/media/df7cb46b436f95cc5d269cd5785e9be8/href</a></iframe><p>We just added AutoTabsRouter to handle tabs navigation. It requires:</p><ol><li>routes : your list of tab routes</li><li>transactionBuilder (optional) : the transaction animation while changing tabs</li><li>builder : which page to be rendered, normally you’re going to return a Scaffold with BottomNavigationBar.</li></ol><p>In the previous example we returned a ScaffoldWithNavbar, let’s see is defined</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8afa4ef8cd0ce4c391224ee1903ec7aa/href">https://medium.com/media/8afa4ef8cd0ce4c391224ee1903ec7aa/href</a></iframe><p>Simple right ? 🙃 after this setup we’re going to have the following result, nested tab navigation successfully implemented</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Dty8qkF-j1rCyquJXFZvag.gif" /></figure><p>You can achieve the same result by using a shipped-in AutoTabsScaffold that makes things much cleaner</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35e3aec1a951162bd95db74364f30b50/href">https://medium.com/media/35e3aec1a951162bd95db74364f30b50/href</a></iframe><p>AutoTabsRouter also has support for PageView and TabBar, for that we just need to call different constructor for each one. Follow code examples below 👇🏿</p><h4>Nested PageView navigation</h4><p>Use the AutoTabsRouter.pageView constructor to implement tabs using PageView</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5981cddf692dc16addd351c2a9ac5ea/href">https://medium.com/media/b5981cddf692dc16addd351c2a9ac5ea/href</a></iframe><h4>Nested TabBar navigation</h4><p>Use the AutoTabsRouter.tabBar constructor to implement tabs using TabBar</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd7f04f80e533c5950f3ce59609a0e21/href">https://medium.com/media/fd7f04f80e533c5950f3ce59609a0e21/href</a></iframe><p>AutoRoute empowers developers to efficiently manage navigation flows, enhance user experiences, and accelerate their development workflows.</p><blockquote>Hope you enjoyed the trip to auto_route 😊🥳</blockquote><p>Do you know you can clap up to 50 times for an article? Go give it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac405e8a941" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter firebase cloud Firestore Guide]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-firebase-cloud-firestore-guide-ecc7e42eed0d?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc7e42eed0d</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Mon, 22 May 2023 16:28:26 GMT</pubDate>
            <atom:updated>2023-05-22T16:32:51.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Cloud Firestore Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU-79tapQwKrsmtKKM_qow.jpeg" /><figcaption>image credit: <a href="https://www.youtube.com/@rajayogan8884">Raja Yogan</a></figcaption></figure><p><strong>Cloud Firestore</strong> is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps — at global scale. It ships with mobile and web SDKs and a comprehensive set of security rules so you can access your database without needing to stand up your own server.Unlike a SQL database, there are no tables or rows. Instead, you store data in <em>documents,</em></p><p>In this article, we’re going to create a simple Firestore project to help you understand how to save and load data from firestore. There’s a bonus content in the end 🥳</p><h3>Getting started</h3><ol><li>Add <a href="https://firebase.google.com/docs/flutter/setup?platform=ios">Firebase to your Flutter app</a></li></ol><p>2. Ensured you have <a href="https://firebase.flutter.dev/docs/overview#initializing-flutterfire">initialised FlutterFire</a> before using Firestore</p><p>3. Add Cloud Firestore to pubspec.yaml</p><pre>flutter pub add cloud_firestore</pre><p>4. Create a Cloud Firestore database</p><p>create a Firestore database, check out this <a href="https://firebase.google.com/docs/firestore/quickstart#create">link</a> and follow instructions.</p><p>Add a new collection user, will need that for following examples. Basic structure below</p><pre>{<br>  &#39;firstName&#39;: &#39;any-data&#39;,<br>  &#39;lastName&#39;: &#39;any-data&#39;<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff6z5TkrTIBZILYOd1t%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaml2MzEyY2NhZ3J4M3BpZnFrZmRnOTc1a2w0MzB3Mm5wMWwzM2lpNyZlcD12MV9naWZzX2dpZklkJmN0PWc%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfbbcd4a5d3731ea8947a92c56b41650/href">https://medium.com/media/bfbbcd4a5d3731ea8947a92c56b41650/href</a></iframe><p>In the app, let’s create a simple HomePage with two TextField to get user’s first and last name, also a FloatActionButton to add new item on button tap.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57c15cf7ddb402bd49311c3f4aea04d5/href">https://medium.com/media/57c15cf7ddb402bd49311c3f4aea04d5/href</a></iframe><p>That’s a simple UI, we added two TextField with its respective controllers to get user’s first and last name. We also added a FloatingActionButton to save a new user on button’s tap.</p><p>You would have this amazing UI below 😅😊 “<strong><em>don’t blame the programmer, on my machine it looks amazing</em></strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*xZM0PEd4WRVQ6xm5pT01Eg.png" /></figure><p>Now that we have our basic layout created is time to add Firestore connection.</p><p>Let’s create a class CloudFirestoreService and add a add() responsible to connect with firestore and create a new record in the database in the user collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3779b30f9d374cbfdc9a7c3b7c260ed/href">https://medium.com/media/d3779b30f9d374cbfdc9a7c3b7c260ed/href</a></iframe><p>This method access user collection and create a new record. Simple like that 🙃</p><p>Now let’s add this method call to FloatActionButton</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de93b337eb329a509a6817c539ca78cd/href">https://medium.com/media/de93b337eb329a509a6817c539ca78cd/href</a></iframe><h4>Fetching data from Cloud Firestore</h4><p>To fetch data we are going to utilize the StreamBuilder class which is a widget that builds itself based on the latest snapshot of interaction with a Stream. Stream is a source of asynchronous data events.</p><p>The stream class will be fetching data from the database without the user having to restart the app for latest additions .</p><p>We will display the data in a Listview. At the moment the design is not that nice hope you will work on improving the design after you are able to fetch all the data.</p><p>Add following method to your CloudFirestoreService</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcaa52ba5db0f4c55ac7fcc4215255cb/href">https://medium.com/media/bcaa52ba5db0f4c55ac7fcc4215255cb/href</a></iframe><p>db.collection(‘user’).snapshots() return a Stream&lt;QuerySnapshot&gt;. Let’s load those data using StreamBuilder and ListView.builder 👇🏿</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6c721556777439705382e1f5c1883d/href">https://medium.com/media/be6c721556777439705382e1f5c1883d/href</a></iframe><p>Using StreamBuilder snapshot we’re checking the connection state, if there’s any error, no data or if there’s data.</p><p>Final result 👇🏿</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*0W0Mrl44E1GCd4xotv06fg.gif" /></figure><p>That’s it, we connected to Firestore, saved and loaded data.</p><p>Before you go let’s see in details others useful Firestore method.</p><h3>Before you go!!! 😱</h3><h4>1. Set a document</h4><p>To create or overwrite a single document, use set() method:</p><pre>final user = {&#39;firstName&#39;: &#39;antonio&#39;, &#39;lastName&#39;: &#39;nicolau&#39;};<br><br>// If no [path] is provided, an auto-generated ID is used<br>FirebaseFirestore.instance.collection(&#39;user&#39;).doc(&#39;antonio&#39;).set(user);</pre><h4>2. Add a document</h4><p>When you use set() to create a document, you must specify an ID for the document to create but for most of case we want this ID to be auto generated. You can do this by calling add()</p><pre>final user = {&#39;firstName&#39;: &#39;antonio&#39;, &#39;lastName&#39;: &#39;nicolau&#39;};<br><br>FirebaseFirestore.instance.collection(&#39;user&#39;).add(user);</pre><p>Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.</p><h4>3. Update a document</h4><p>To update some fields of a document without overwriting the entire document, use update()</p><pre>final db = FirebaseFirestore.instance;<br><br>// we specify which fields we want to update `update({})`<br>db.collection(&#39;user&#39;).doc(&#39;antonio&#39;).update({&#39;lastName&#39;: &#39;new-lastName&#39;});</pre><p>If your document contains nested objects, you can use “dot notation” to reference nested fields within the document when you call update():</p><pre>    final db = FirebaseFirestore.instance;<br><br>    // Assume the document contains<br>    // {<br>    //   firstName: &quot;antonio&quot;,<br>    //   lastName: &quot;nicolau&quot;,<br>    //   social_media: {linkedin:&#39;x&#39;, github: &#39;y&#39;}<br>    // }<br><br>    // we specify which fields we want to update `update({})`<br>    db.collection(&#39;user&#39;).doc(&#39;antonio&#39;).update({<br>      &#39;lastName&#39;: &#39;new-lastName&#39;,<br>      &#39;social_media.linkedin&#39;: &#39;yz&#39; // access `social_media` and update `linkedin` field<br>    });</pre><p>Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field.</p><h3>4. Custom objects</h3><p>Using Map to represent your documents is often not very convenient, so Cloud Firestore supports writing documents with custom classes.</p><p>That’s how you could use custom objects to load firestore data.</p><ol><li>create a class e.g User with fromFirestore &amp; toFirestore methods</li></ol><pre>class User {<br>  final String? firstName;<br>  final String? lastName;<br><br>  const User({this.firstName, this.lastName});<br><br>  factory User.fromFirestore(<br>    DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; snapshot,<br>    SnapshotOptions? options,<br>  ) {<br>    final data = snapshot.data();<br>    return User(<br>      firstName: data?[&#39;firstName&#39;],<br>      lastName: data?[&#39;lastName&#39;],<br>    );<br>  }<br><br>  Map&lt;String, dynamic&gt; toFirestore() {<br>    return {<br>      &quot;firstName&quot;: firstName,<br>      &quot;lastName&quot;: lastName,<br>    };<br>  }<br>}</pre><p>2. call withConverter() when getting firestore reference and give your custom object like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf8ccd2f420d9a9202673d8cdeb875b8/href">https://medium.com/media/cf8ccd2f420d9a9202673d8cdeb875b8/href</a></iframe><h4>5. Delete documents</h4><p>To delete a document, use delete()</p><pre>db.collection(&#39;user&#39;).doc(&#39;antonio&#39;).delete()</pre><p>To delete specific fields from a document, use FieldValue.delete()</p><pre>final docRef = db.collection(&#39;user&#39;).doc(&#39;antonio&#39;);<br><br>// Remove the &#39;lastName&#39; field from the document<br>final updates = &lt;String, dynamic&gt;{<br>  &#39;lastName&#39;: FieldValue.delete(),<br>};<br><br>docRef.update(updates);</pre><blockquote><strong>Thank you</strong> for reading 😊 give a clap if you liked👏 and <strong>follow</strong> for more Flutter tips</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc7e42eed0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter go_router: The Essential Guide]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-go-router-the-essential-guide-349ef39ec5b3?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/349ef39ec5b3</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 16:40:56 GMT</pubDate>
            <atom:updated>2023-05-30T11:09:08.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EvDUbqUq135ePkDlua7bTw.png" /></figure><p>Go_router is a third-party package for routing in Flutter that aims to provide a more flexible and easy-to-use solution than the default routing options provided by Flutter. It can be useful if you want more control over how routes are defined and managed in your app. It also has a good support for web so that’s a nice choice for your application.</p><p>You can define URL patterns, navigate using a URL, handle deep links, and a number of other navigation-related scenarios.</p><h3>Features</h3><p>GoRouter has a number of features to make navigation straightforward:</p><ul><li>Parsing path and query parameters using a template syntax</li><li>Displaying multiple screens for a destination (sub-routes)</li><li>Redirection support — you can redirect the user to a different URL based on application state, for example to a sign-in when the user is not authenticated</li><li>Support Nested Tab navigation with StatefulShellRoute</li><li>Support for both Material and Cupertino apps</li><li>Backwards-compatibility with Navigator API</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff6z5TkrTIBZILYOd1t%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaml2MzEyY2NhZ3J4M3BpZnFrZmRnOTc1a2w0MzB3Mm5wMWwzM2lpNyZlcD12MV9naWZzX2dpZklkJmN0PWc%2Ff6z5TkrTIBZILYOd1t%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfbbcd4a5d3731ea8947a92c56b41650/href">https://medium.com/media/bfbbcd4a5d3731ea8947a92c56b41650/href</a></iframe><h3>Get started</h3><p>To get started, add go_router to your pubspec.yaml. In this article we’ll be using <strong>^7.1.1.</strong></p><pre>dependencies:<br>  go_router: ^7.1.1</pre><h3>Route Configuration</h3><p>After doing that lets add GoRouter configuration to your app:</p><pre>import &#39;package:go_router/go_router.dart&#39;;<br><br>// GoRouter configuration<br>final _router = GoRouter(<br>  initialLocation: &#39;/&#39;,<br>  routes: [<br>    GoRoute(<br>      name: &#39;home&#39;, // Optional, add name to your routes. Allows you navigate by name instead of path<br>      path: &#39;/&#39;,<br>      builder: (context, state) =&gt; HomeScreen(),<br>    ),<br>    GoRoute(<br>      name: &#39;page2&#39;,<br>      path: &#39;/page2&#39;,<br>      builder: (context, state) =&gt; Page2Screen(),<br>    ),<br>  ],<br>);</pre><p>Then we can use either the MaterialApp.router or CupertinoApp.router constructor and set the routerConfig parameter to your GoRouter configuration object:</p><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      routerConfig: _router,<br>    );<br>  }<br>}</pre><p>That&#39;s it 🙂 you’re ready to play around with go_router !!!</p><h4>Parameters</h4><p>To specify a path parameter, prefix a path segment with a : character, followed by a unique name, for example, :userId. We access the parameter value by GoRouterState object provided to the builder callback:</p><pre>GoRoute(<br>  path: &#39;/fruits/:id&#39;,<br>  builder: (context, state) {<br>     final id = state.params[&#39;id&#39;] // Get &quot;id&quot; param from URL<br>     return FruitsPage(id: id);<br>  },<br>),</pre><p>We can also access query string parameter using GoRouterState. For example, a URL path such as /fruits?search=antonio can read the search parameter:</p><pre>GoRoute(<br>  path: &#39;/fruits&#39;,<br>  builder: (context, state) {<br>    final search = state.queryParams[&#39;search&#39;];<br>    return FruitsPage(search: search);<br>  },<br>),</pre><h4>Adding child routes</h4><p>A matched route can result in more than one screen being displayed on a Navigator. This is equivalent to calling push(), where a new screen is displayed above the previous screen, and an in-app back button in the AppBar widget is provided.</p><p>To do it we add a child route and its parent routes:</p><pre>GoRoute(<br>  path: &#39;/fruits&#39;,<br>  builder: (context, state) {<br>    return FruitsPage();<br>  },<br>  routes: &lt;RouteBase&gt;[ // Add child routes<br>    GoRoute(<br>      path: &#39;fruits-details&#39;, // NOTE: Don&#39;t need to specify &quot;/&quot; character for router’s parents<br>      builder: (context, state) {<br>        return FruitDetailsPage();<br>      },<br>    ),<br>  ],<br>)</pre><h4>Navigation Between Screens</h4><p>There are many ways to navigate between destinations with go_router.</p><p>To change to a new screen, call context.go() with a URL:</p><pre>build(BuildContext context) {<br>  return TextButton(<br>    onPressed: () =&gt; context.go(&#39;/fruits/fruit-detail&#39;),<br>  );<br>}</pre><p>We can also navigate by name instead of URL, call context.goNamed()</p><pre>build(BuildContext context) {<br>  return TextButton(<br>    // remember to add &quot;name&quot; to your routes<br>    onPressed: () =&gt; context.goNamed(&#39;fruit-detail&#39;),<br>  );<br>}</pre><p>To build a URI with query parameters, you can use the Uri class:</p><pre>context.go(<br>  Uri(<br>    path: &#39;/fruit-detail&#39;,<br>    queryParameters: {&#39;id&#39;: &#39;10&#39;},<br>   ).toString(),<br>);</pre><p>We can pop the current screen via context.pop().</p><h3>Nested Tab navigation</h3><p>Some apps display destinations in a subsection of the screen, for example, a BottomNavigationBar that stays on-screen when navigating between Screens.</p><p>We set up nested navigation using <a href="https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute-class.html">StatefulShellRoute</a>.</p><p>This <a href="https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute-class.html">StatefulShellRoute</a> class places its sub-route on a different Navigator than the root Navigator. However, this route class differs in that it creates separate Navigators for each of its nested branches (i.e. parallel navigation trees), making it possible to build an app with stateful nested navigation.</p><p>This is convenient when for instance implementing a UI with a BottomNavigationBar, with a persistent navigation state for each tab.</p><p>A StatefulShellRoute is created by specifying a List of <a href="https://pub.dev/documentation/go_router/latest/go_router/StatefulShellBranch-class.html">StatefulShellBranch</a> items, each representing a separate stateful branch in the route tree. StatefulShellBranch provides the root routes and the Navigator key (GlobalKey) for the branch and an optional initial location.</p><p>Let’s see how to implement it 🙂</p><p>We start by creating our router, we’re going to add <a href="https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute/StatefulShellRoute.indexedStack.html">StatefulShellRoute.indexedStack()</a> to our routes, this class is going to be responsible to create our nested navigation.</p><p>StatefulShellRoute.indexedStack() constructs a <strong>StatefulShellRoute</strong> that uses an <a href="https://api.flutter.dev/flutter/widgets/IndexedStack-class.html">IndexedStack</a> for its nested Navigators.</p><p>This constructor provides an IndexedStack based implementation for the container (<a href="https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute/navigatorContainerBuilder.html">navigatorContainerBuilder</a>) used to manage the Widgets representing the branch Navigators.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ded0a30137e92cd8f64e1390fbbd51/href">https://medium.com/media/33ded0a30137e92cd8f64e1390fbbd51/href</a></iframe><p>We added StatefulShellRoute.indexedStack() to our route, it’s responsible to create our branches and return a custom shell (in this case a BottomNavigationBar).</p><ol><li>In the builder: (context, state, navigationShell) we return our custom shell, basically a Scaffold with a BottomNavigationBar, remember to pass navigationShell to this page since we’ll use that to navigate to others branch (e.g Home ==&gt; Shope)</li><li>In the branches:[] we give a list of StatefulShellBranch (our branches). We pass our previous created _sectionNavigatorKey to navigatorKey property but just for the first branch, a default key will be used for others branches. We also give it a list of RouteBase ( the supported routes for that branch)</li></ol><p>As you could see our builder return our custom shell that contains our BottomNavigationBar so let’s create that 👇🏿</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af6abe5b57752d972f9053a0a32bdb7a/href">https://medium.com/media/af6abe5b57752d972f9053a0a32bdb7a/href</a></iframe><p>Basically we return a Scaffold with BottomNavigationBar, the body is going to be a navigationShell that we got from our router.</p><p>There’s also an _onTap(index) , here we use navigationShell.goBranch(index) this way we can change between branches.</p><p>And that’s it, you’re ready to implement that in your projects 🥳🎉</p><p>For a complete example checkout my repository below 👇🏿</p><p><a href="https://github.com/antonio-nicolau/flutter-go_router-with-nested-tab-navigation">GitHub - antonio-nicolau/flutter-go_router-with-nested-tab-navigation</a></p><h3>Guards</h3><p>To guard specific routes, e.g. from un-authenticated users, global redirect can be set up via GoRouter. A most common example would be the set up redirect that guards any route that is not /login and redirects to /login if the user is not authenticated</p><p>A redirect is a callback of the type <a href="https://pub.dev/documentation/go_router/latest/go_router/GoRouterRedirect.html">GoRouterRedirect</a>. To change incoming location based on some application state, add a callback to either the GoRouter or GoRoute constructor:</p><pre>GoRouter(<br>  redirect: (BuildContext context, GoRouterState state) {<br>    final isAuthenticated = // your logic to check if user is authenticated<br>    if (!isAuthenticated) {<br>      return &#39;/login&#39;;<br>    } else {<br>      return null; // return &quot;null&quot; to display the intended route without redirecting<br>     }<br>   },<br>  ...</pre><ul><li>You can define redirect on the GoRouter constructor. Called before any navigation event.</li><li>Define redirect on the GoRoute constructor. Called when a navigation event is about to display the route.</li></ul><blockquote>You can specify a redirectLimit to configure the maximum number of redirects that are expected to occur in your app. By default, this value is set to 5. GoRouter will display the error screen if this redirect limit is exceeded</blockquote><h3>Transition animations</h3><p>GoRouter allows you to customise the transition animation for each GoRoute. To configure a custom transition animation, provide a pageBuilder parameter to the GoRoute constructor:</p><pre>GoRoute(<br>  path: &#39;/fruit-details&#39;,<br>  pageBuilder: (context, state) {<br>    return CustomTransitionPage(<br>      key: state.pageKey,<br>      child: FruitDetailsScreen(),<br>      transitionsBuilder: (context, animation, secondaryAnimation, child) {<br>        // Change the opacity of the screen using a Curve based on the the animation&#39;s value<br>        return FadeTransition(<br>          opacity: CurveTween(curve: Curves.easeInOutCirc).animate(animation),<br>          child: child,<br>        );<br>      },<br>    );<br>  },<br>),</pre><p>For a complete example, see the <a href="https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/transition_animations.dart">transition animations sample</a>.</p><h3>Error handling (404 page)</h3><p>By default, go_router comes with default error screens for both MaterialApp and CupertinoApp as well as a default error screen in the case that none is used. You can also replace the default error screen by using the errorBuilder parameter:</p><pre>GoRouter(<br>  /* ... */<br>  errorBuilder: (context, state) =&gt; ErrorPage(state.error),<br>);</pre><h3>Type-safe routes</h3><p>Instead of using URL strings (context.go(“/auth”)) to navigate, go_router supports type-safe routes using the go_router_builder package.</p><p>To get started, add <a href="https://pub.dev/packages/go_router_builder">go_router_builder</a>, <a href="https://pub.dev/packages/build_runner">build_runner</a>, and <a href="https://pub.dev/packages/build_verify">build_verify</a> to the dev_dependencies section of your pubspec.yaml:</p><pre>dev_dependencies:<br>  go_router_builder: ^1.0.16<br>  build_runner: ^2.3.3<br>  build_verify: ^3.1.0</pre><h4>Defining a route</h4><p>Then define each route as a class extending GoRouteData and overriding the build method.</p><pre>class HomeRoute extends GoRouteData {<br>  const HomeRoute();<br>  <br>  @override<br>  Widget build(BuildContext context, GoRouterState state) =&gt; const HomeScreen();<br>}</pre><h4>Route tree</h4><p>The tree of routes is defined as an attribute on each of the top-level routes:</p><pre>import &#39;package:go_router/go_router.dart&#39;;<br><br>part &#39;go_router.g.dart&#39;; // name of generated file<br><br>// Define how your route tree (path and sub-routes)<br>@TypedGoRoute&lt;HomeScreenRoute&gt;(<br>    path: &#39;/home&#39;,<br>    routes: [ // Add sub-routes<br>      TypedGoRoute&lt;SongRoute&gt;(<br>        path: &#39;song/:id&#39;,<br>      )<br>    ]<br>)<br><br>// Create your route screen that extends &quot;GoRouteData&quot; and @override &quot;build&quot;<br>// method that return the screen for this route<br>@immutable<br>class HomeScreenRoute extends GoRouteData {<br>  @override<br>  Widget build(BuildContext context) {<br>    return const HomeScreen();<br>  }<br>}<br><br>@immutable<br>class SongRoute extends GoRouteData {<br>  final int id;<br>  const SongRoute({required this.id});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SongScreen(songId: id.toString());<br>  }<br>}</pre><p>To build the generated files use the build_runner command:</p><pre>flutter pub global activate build_runner // Optional, if you already have build_runner activated so you can skip this step<br>flutter pub run build_runner build</pre><p>To navigate, construct a GoRouteData object with the required parameters and call go():</p><pre>TextButton(<br>  onPressed: () {<br>    const SongRoute(id: 2).go(context);<br>  },<br>  child: const Text(&#39;Go to song 2&#39;),<br>),</pre><h3>Before you go !!!</h3><p>There’s still a nice feature with go_router, you can add a NavigatorObserver to our GoRouter for observing the behavior of a Navigator, listen for whenever a route was push, pop or replace. To do so let’s create a class that extends NavigatorObserver :</p><pre>class MyNavigatorObserver extends NavigatorObserver {<br>  @override<br>  void didPush(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) {<br>    log(&#39;did push route&#39;);<br>  }<br><br>  @override<br>  void didPop(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) {<br>    log(&#39;did pop route&#39;);<br>  }<br>}</pre><p>Now lets add MyNavigatorObserver to our GoRouter</p><pre>GoRouter(<br>  ...<br>  observers: [ // Add your navigator observers<br>    MyNavigatorObserver(),<br>  ],<br>...<br>)</pre><p>Whenever those events are triggered your navigator will be notified.</p><p>Find here the project example 👇🏿👇🏿</p><p><a href="https://github.com/antonio-nicolau/flutter-with-go_router">GitHub - antonio-nicolau/flutter-with-go_router: A simple app to show how to work with go_router in Flutter apps to manage route navigation</a></p><blockquote>Hope you enjoyed the trip to go_router 😊🥳</blockquote><p>Do you know you can clap up to 50 times for an article? Go give it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349ef39ec5b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Riverpod: The Essential Guide]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-riverpod-the-essential-guide-f29dc563d1d4?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f29dc563d1d4</guid>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 18:46:55 GMT</pubDate>
            <atom:updated>2022-09-03T18:46:55.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRQc2UAMPVZJ-_k6YY1aMg.png" /></figure><p><a href="https://pub.dev/packages/riverpod">Riverpod</a> is a popular Flutter state management library that shares many of the advantages of <a href="https://pub.dev/packages/provider">Provider</a> and brings many additional benefits.</p><p>According to the <a href="https://pub.dev/packages/riverpod">official documentation</a>:</p><blockquote><a href="https://pub.dev/packages/riverpod"><em>Riverpod</em></a><em> is a complete rewrite of the </em><a href="https://pub.dev/packages/provider"><em>Provider</em></a><em> package to make improvements that would be otherwise impossible.</em></blockquote><p>That a powerful state management library that allow you:</p><ul><li>easily <strong>create</strong>, <strong>access</strong>, and <strong>combine</strong> providers with minimal boilerplate code</li><li>write <strong>testable code</strong> and keep your logic outside the widget tree</li><li>catch programming errors at <strong>compile-time</strong> rather than at runtime</li></ul><p>In this article I’m going to guide through this amazing tool and help you understand it once and for all.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Flluj1cauAlO2vQEm8A%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Flluj1cauAlO2vQEm8A%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Flluj1cauAlO2vQEm8A%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c11df31aae9698e388443651e943f69/href">https://medium.com/media/6c11df31aae9698e388443651e943f69/href</a></iframe><p>You need to be aware that Riverpod is spread across multiple packages, with slightly different usage.</p><p>The variant of Riverpod that you will want to install depends on the app you are making</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yE-deDlgjlBQXs0nAPJZ2A.png" /><figcaption>Multiple packages to work with Riverpod</figcaption></figure><p>To understand better which package to use looks at this illustration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVSKs9n1pcHNBGWJAS8JOg.png" /><figcaption>Credit: <a href="https://blog.csdn.net/qq_17766199/article/details/108352306">blog.csdn</a></figcaption></figure><p>In this article we’ll talk about <a href="https://pub.dev/packages/flutter_riverpod">flutter_riverpod</a> and cover other types in the next articles.</p><h3>Getting started</h3><p>First of all you need to add <strong>flutter_riverpod</strong> as dependence in your pubspec.yaml , you can do it by running flutter pub add flutter_riverpod or open your pubspec.yaml file and add</p><pre>dependencies:<br>  <strong>flutter_riverpod</strong>: ^1.0.4</pre><p>Now you can import it like this</p><pre><strong>import</strong> &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;</pre><p>Now that you have it installed let’s see how you can work with it</p><p>First, we need to wrap our main widget with the <strong>ProviderScope</strong> widget (or any widget in the tree, for a different scope). This widget is where all the states of providers will be stored.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c80b41e93f07669baeda3eff68b2af1f/href">https://medium.com/media/c80b41e93f07669baeda3eff68b2af1f/href</a></iframe><p>And once you wrapped your main widget with <strong>ProviderScope</strong> you can create a simple provider like this</p><pre><strong>final</strong> helloWorldProvider = <strong>Provider</strong>&lt;String&gt;((ref)=&gt; &quot;hello world&quot;);</pre><p>It create a simple provider that exposes as its state a “hello world” string</p><p>The following example shows how to use riverpod to make a simple “Hello world”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/067bdadde218e393a156aeda05c514a5/href">https://medium.com/media/067bdadde218e393a156aeda05c514a5/href</a></iframe><ol><li>Created a simple provider that return “hello world” final helloWorldProvider = Provider&lt;string&gt;((ref)=&gt; “hello world”);</li><li>Read provider value using <strong>ref.watch/ref.read </strong><strong>final </strong>String value = ref.watch(helloWorldProvider);</li><li>Show its value in a Text widget Text(&#39;Provider says: $value)</li></ol><p>That’s it, super simple right ?</p><p>Provider&lt;T&gt;, exposes a read-only value. It’s the most simple kind of provider, commonly used as a “cache” to share data (model classes) among widgets.</p><h3>Different Types of Providers</h3><p>We already talked about one provider type Provider&lt;T&gt; the most simplest one but there are multiple types of providers for multiple different use cases.</p><p>With all of these providers available, it is sometimes difficult to understand when to use one provider type over another. Use the table below to choose a provider that fits what you want to provide to the widget tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHqBq6ACY63dpBaSp05dZA.png" /><figcaption>Different types of providers</figcaption></figure><blockquote><strong>NOTE FROM DOCUMENTATION: </strong>While all providers have their purpose, <a href="https://pub.dev/documentation/flutter_riverpod/latest/flutter_riverpod/ChangeNotifierProvider-class.html">ChangeNotifierProvider</a>s are not recommended for scalable applications, because of issues with mutable state. It exists in the flutter_riverpod package to provide an easy migration path from package:provider, and allows for some flutter specific use-cases such as integration with some Navigator 2 packages.</blockquote><p>Lets take a look at those different type of providers to learn how you can use it in your project</p><h4>StateProvider</h4><p>StateProvider is a provider that exposes a way to modify its state. It is a simplification of StateNotifierProvider, designed to avoid having to write a StateNotifier class for very simple use-cases.</p><p>StateProvider exists primarily to allow the modification of simple variables by the User Interface</p><p>It’s really easy to work with, you can create one this way</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b9f4651e120cc93c9756ecafa6f978/href">https://medium.com/media/b9b9f4651e120cc93c9756ecafa6f978/href</a></iframe><p>Note that since it is a StateProvider, the state is made available using the <strong>state</strong> variable and can be updated as seen in the onTap function call.</p><p>But states are never one-off types as seen, rather there is more to it in bigger projects, depending on the needs you might use a class to hold the states so the sky is the limit 😉</p><h4>StateNotifierProvider</h4><p>StateNotifierProvider is a provider that is used to listen to and expose a StateNotifier.<br>This along with StateNotifier is Riverpod&#39;s recommended solution for managing state which may change in reaction to a user interaction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc7e7feec3c96464ff848c3ebaa23cd/href">https://medium.com/media/7cc7e7feec3c96464ff848c3ebaa23cd/href</a></iframe><p>We see some slight differences in that we use</p><p>When we want to read or watch a StateNotifierProviders notifier as it exposes the notifier and not its value, this helps as just seen to give us access to the methods and notifier properties.</p><pre>ref.read(clickCountProvider.notifier).increment();</pre><p>When we need to read or watch just the state without access the notifier</p><pre>ref.watch(clickCountProvider);</pre><h4>FutureProvider/StreamProvider:</h4><p>FutureProvider is the equivalent of Provider but for asynchronous code, in this sense you can create a synchronous value and watch for changes to it, like it being successfully retrieved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4599605de68b3178c198c4c5fc63ff7/href">https://medium.com/media/d4599605de68b3178c198c4c5fc63ff7/href</a></iframe><p>Riverpod removes the redundancies of using something like FutureBuilder and automatically handles the code.</p><p>For the example above we used <a href="https://catfact.ninja/fact">https://catfact.ninja/fact</a> api, a free api that get random cat facts via text message every day.</p><p>As seen, <strong>catfact</strong> is a type of <strong>AsyncValue&lt;String&gt;</strong> which provides the <strong>when</strong> method with options for data, loading, and error that we can then manipulate as required. This is much easier than using a FutureBuilder or StreamBuilder.</p><p>This is the same concept with StreamProviders, the only thing that really change is the provider name 😅 from <strong>FutureProvider</strong> to <strong>StreamProvider.</strong></p><h3>Reading a Provider: read, watch, listen, select</h3><p>We’ve been using <em>ref.read(), ref.watch</em> but what are they ? lets look at those and also take a look at <em>ref.listen() and select</em></p><h4>ref.read</h4><p>In simple worlds the ref.read method is a way to obtain the state of a provider without listening to it.</p><p>About ref.read there’s some important notes</p><blockquote>Using ref.read should be avoided as much as possible because it is not reactive.</blockquote><blockquote>It exists for cases where using watch or listen would cause issues. If you can, it is almost always better to use watch/listen, especially watch.</blockquote><h4>ref.watch</h4><p>ref.watch is used inside the build method of a widget or inside the body of a provider to have the widget/provider listen to a provider. It means that when you want to listen for provider states changes the ref.watch is the right choice, use it instead of ref.read.</p><pre><strong>final</strong> counterProvider = <strong>StateProvider</strong>((ref) =&gt; 0);<br><br>class HomeView extends ConsumerWidget {<br>  const HomeView({Key? key}): super(key: key);<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    // use ref to listen to a provider<br>    <strong>final</strong> counter = ref.<strong>watch</strong>(counterProvider);<br><br>    return <strong>Text</strong>(&#39;$counter&#39;);<br>  }<br>}</pre><blockquote>The watch method should not be called asynchronously, like inside an onPressed of an ElevatedButton. Nor should it be used inside initState and other State life-cycles.</blockquote><blockquote>In those cases, consider using ref.read instead.</blockquote><h4>ref.listen</h4><p>That’s similarly to ref.watch, it is possible to use ref.listen to observe a provider.</p><p>The main difference between them is that, rather than rebuilding the widget/provider if the listened to provider changes, using ref.listen will instead call a custom function.</p><p>For example, if we have a authErrorCodeProvider that store the returned auth request status and we want to show modal with error message or redirect to home page based on this error code, we could listen to this provider changes and call a function based on returned value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245ef562e362c559a88141c2ff090655/href">https://medium.com/media/245ef562e362c559a88141c2ff090655/href</a></iframe><h4>Filter rebuilds using “select”<a href="https://riverpod.dev/docs/concepts/reading/#using-select-to-filter-rebuilds">​</a></h4><p>One final feature to mention related to reading providers is the ability to reduce the number of times a widget/provider rebuilds from ref.watch, or how often ref.listen executes a function.</p><p>By default, listening to a provider listens to the entire object state. But sometimes, a widget/provider may only care about changes to some properties instead of the whole object.</p><p>For example, a provider may expose a <strong>User </strong>object<strong>:</strong></p><pre><strong><em>class</em></strong> User {<br>  String <em>get</em> name;<br>  int <em>get</em> age;<br>}</pre><p>But a widget may only use the user name:</p><pre><strong>Widget</strong> build(BuildContext context, WidgetRef ref) {<br>  <strong>User</strong> user = ref.watch(userProvider);<br>  <em>return</em> Text(user.name);<br>}</pre><p>If we naively used ref.watch, this would rebuild the widget when the user&#39;s age changes but we just need to listen for name property changes</p><p>The solution is to use <strong>select</strong> to explicitly tell Riverpod that we only want to listen to the name property of the User.</p><p>The updated code would be:</p><pre><strong>Widget</strong> build(<strong>BuildContext</strong> context, <strong>WidgetRef</strong> ref) {<br>  <strong>String</strong> name = <strong>ref</strong>.watch(userProvider.<strong>select</strong>((user) =&gt; user.name));<br>  <em>return</em> <strong>Text</strong>(name);<br>}</pre><p>Whenever the User changes, Riverpod will call this function and compare the previous and new result. If they are different, Riverpod will rebuild the widget.</p><p>However, if they are equal, Riverpod will not rebuild the widget. That’s really nice when we want to avoid unnecessary widget/provider rebuilds, give it a try 😉</p><h3>Provider Modifiers</h3><p>At the moment, there are two modifiers available:</p><ul><li><strong>autoDispose</strong>, which will make the provider automatically destroy its state when it is no longer being listened to.</li><li>.<strong>family</strong>, which allows creating a provider from external parameters.</li></ul><pre><strong>final</strong> myAutoDisposeProvider = StateProvider.autoDispose&lt;int&gt;((ref) =&gt; 0);<br><strong>final</strong> myFamilyProvider = Provider.family&lt;String, int&gt;((ref, id) =&gt; id);</pre><p>A provider can use multiple modifiers at once:</p><pre><strong>final</strong> userProvider = <strong>FutureProvider</strong>.autoDispose.family&lt;User, int&gt;((ref, userId) async {<br>  return fetchUser(userId);<br>});</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26FPnsRww5DbqoPuM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="237" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href">https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href</a></iframe><p>Riverpod is a powerful state management and when you learn to work with it, becomes an important ally. <em>It helps improve on certain principles of coding and gives us more control of what we can or can not do.</em></p><p>I did not cover tests in this article. <strong><em>But I’m already writing a new article covering this topic so follow to get informed when.</em></strong></p><p><strong>Thank you</strong> for reading 😊 give a clap if you liked👏 and <strong>follow</strong> for more Flutter tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f29dc563d1d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter web scraping in practice]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-web-scraping-in-practice-c4c4a861a223?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4c4a861a223</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Sun, 21 Aug 2022 21:35:24 GMT</pubDate>
            <atom:updated>2022-08-21T22:40:36.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_HA1qyqT9aqmLoh3bWwTw.png" /><figcaption>Image credit: <a href="https://medium.com/analytics-vidhya/web-scraping-made-easy-using-python-9f5f69ecff3c">@mamatha.bbb article</a></figcaption></figure><p>In this article I am going to introduce you to web scraping in Flutter/Dart</p><p>Some time ago I started developing this package <a href="https://pub.dev/packages/chaleno"><strong>chaleno</strong></a>, at that time I wanted start using web scraping in Flutter/dart. I developed the first version of the package but stoped and now that we have Dart in backend growing fast I believe is a good time to keep working on it.</p><blockquote>This package contains a set of functions that make it easy to web scrape websites. Its multi-platform, supports mobile, desktop, and the web.</blockquote><p>I’m still working on it and there’s features missing so feel free to give your contribute 🙂❤️</p><p>Now that already we met each other let’s jump to the code 💪🏿</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVgi5B3KLFC3s0bNGFi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVgi5B3KLFC3s0bNGFi%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FVgi5B3KLFC3s0bNGFi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8a98efcc329919945bbac3bf5790ba/href">https://medium.com/media/3c8a98efcc329919945bbac3bf5790ba/href</a></iframe><p>First you need to add the package in your <strong>pubspack.yaml</strong></p><pre><strong>chaleno</strong>: ^0.0.6</pre><p>This is the last version so far, make sure to always check the pub dev to get update about the last version.</p><p>Once it’s installed you can import it like this</p><pre><strong>import</strong> &#39;package:chaleno/chaleno.dart&#39;;</pre><p>Now we’re ready to go</p><p>As example we’ll use <a href="https://filipedeschamps.com.br/newsletter">Filipe Deschamps Newsletter</a></p><blockquote>If you like to read about technology this newsletter is for you! 🙂 I really love it. It’s only available in Portuguese but I believe will have english support soon</blockquote><p>We’ll extract from this newsletter:</p><ul><li>Avatar url</li><li>Newsletter title</li><li>Subscribers number</li></ul><h4>A quick introduction to <strong>Chaleno</strong> package</h4><p>To start working with <strong>chaleno</strong>, we need to create an instance of Chaleno like this.</p><pre><strong>final</strong> chaleno = <strong>await</strong> Chaleno().load(&#39;https://example.com&#39;);</pre><p>Now you can use <strong>chaleno</strong> object to fit your needs</p><p>As you can read here <a href="https://pub.dev/packages/chaleno#importants-methods-and-propriets">chaleno#importants-methods-and-propriets</a> this package offer us a bunch of method and properties that we can easily use while web scrapping.</p><p>We have different ways to extract data with this package</p><ul><li>Get an element by id</li><li>Get elements by class name</li><li>Get elements by tag name</li><li>Get an element by selector</li><li>Get elements by selector</li></ul><h4>Extracting data</h4><p>You can see here different ways to use those methods</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9e9b9c0b711362050a967d5a3cda72c/href">https://medium.com/media/f9e9b9c0b711362050a967d5a3cda72c/href</a></iframe><p>It return a Result object that contains some nice properties that you can access through your past query.</p><p>As you can see there are different ways to extract data using <strong>chaleno</strong>.</p><p>And you can access <strong>Result</strong> object properties like in the example below. You can take <strong>text</strong>, <strong>src</strong>, <strong>href</strong>, <strong>html</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597d30974a4ee122a880cb92039190a6/href">https://medium.com/media/597d30974a4ee122a880cb92039190a6/href</a></iframe><blockquote>Cool 😎 Now you’re ready to play around with this package</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLh2rS9i98vLiOZ5Lud%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLh2rS9i98vLiOZ5Lud%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLh2rS9i98vLiOZ5Lud%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/6350dcac1b65fd42864464db285f617c/href">https://medium.com/media/6350dcac1b65fd42864464db285f617c/href</a></iframe><p>Now that you know how to work with <strong>chaleno </strong>package we can start our little example (web scrape <a href="https://filipedeschamps.com.br/newsletter">Filipe Deschamps newsletter</a>)</p><p>First lets create our flutter project by running flutter create newsletter_scrapping</p><p>After that let’s open our main file, delete all unnecessary code and let this file like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09a712fdc76e2f255504b27890120aa/href">https://medium.com/media/d09a712fdc76e2f255504b27890120aa/href</a></iframe><p>I added a HomePage class to our MaterialApp(home:HomePage()) , don’t worry we’re going to create it now</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa553108b7128f7a0c77aea9c231d08b/href">https://medium.com/media/fa553108b7128f7a0c77aea9c231d08b/href</a></iframe><p>I added our HomePage and I took the opportunity to stylise to looks like with the <a href="https://filipedeschamps.com.br/newsletter">Newsletter Filipe Deschamps</a>. Basically I added an image, a Text, TextField and a button. Note that those values are hardcoded, it doesn’t come from web page yet. we’ll add the method to do it now.</p><p>That’s how it looks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*hvXsRGxqflG9-0rwlu8-jA.png" /></figure><p>Now let’s add a method to load the newsletter and extract the avatar, title and subscribers number. First we’ll need to <strong>inspect the page</strong> to see which selectors to we need to access to extract the avatar, title and subscribers number, when we click on inspect element we’ll see exactly what’s selectors we need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Vr_D5Lp9AYYKEtX7_UxQA.png" /><figcaption>Inspect element result, we can see the selectors</figcaption></figure><p>We already now which selectors we need so let’s start extracting data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e2000878e48d35b95f2400926182a1/href">https://medium.com/media/c1e2000878e48d35b95f2400926182a1/href</a></iframe><p>And that’s it 🙂 super simple.</p><p>We added scrapData method responsible to load the url (https://filipedeschamps.com.br/newsletter) and extract the avatar, title and subscriber number. After that we call this method on initState method.</p><p>We can see the final result, avatar, title and subscriber number extracted from url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*ae5TDnWkpKqxEdJnPzAqBg.png" /></figure><p>Here’s the complete code of our HomePage</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f55f0d1460571ae447990c349bf40151/href">https://medium.com/media/f55f0d1460571ae447990c349bf40151/href</a></iframe><blockquote>That’s <a href="https://pub.dev/packages/chaleno">chaleno</a> package, hope you enjoyed this tour 😊</blockquote><p>If you liked this content left a clap 👏 and follow me for more Flutter tips 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c4a861a223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter uncomplicating in-app purchases]]></title>
            <link>https://medium.com/@antonio.tioypedro1234/flutter-uncomplicating-in-app-purchases-c863042aee15?source=rss-9d49f8c1759b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c863042aee15</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[in-app-purchase]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[António Nicolau]]></dc:creator>
            <pubDate>Sat, 13 Aug 2022 12:59:01 GMT</pubDate>
            <atom:updated>2022-08-13T15:29:28.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzlAd-97EGGwRjVeRcsC6Q.jpeg" /></figure><h3>So why in app purchases?</h3><p>Well basically these in app purchases are required when we are selling digital content.</p><p>A report by <a href="https://www.statista.com/statistics/269025/worldwide-mobile-app-revenue-forecast/">Statista</a> estimated that in 2021, mobile apps can create more than 693 billion U.S. dollars in revenue using app monetization strategies like in-app purchases, in-app advertising, and paid downloads. So I can say for sure that you should think about add in-app purchase implementation to your app.</p><p>So is time to learn how to implement it in your app.</p><p>When is to implement in-app purchase using the official <a href="https://pub.dev/packages/in_app_purchase">in_app_purchase</a> package I’ve been watching many people complaining about, what makes them prefer approaches like revenue or strip but I can say for that it is more simple than it looks.</p><p><strong>let me make you understand it once and for all.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpGWitbFZflfSUYuZ9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMXo0bTV5a285Znp6Zjg1OGJwanAwMTF0dDdtYnoyOGUxbGpyY2d4ciZlcD12MV9naWZzX2dpZklkJmN0PWc%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="363" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href">https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href</a></iframe><p>This section has examples of code for the following tasks:</p><ul><li>Connecting to the underlying store</li><li>Loading products for sale</li><li>Listening to purchase updates</li><li>Making a purchase</li><li>Restoring previous purchases</li><li>Upgrading or downgrading an existing in-app subscription</li><li>Presenting a code redemption sheet (iOS 14)</li></ul><h3>Getting start</h3><p><a href="https://pub.dev/packages/in_app_purchase">in_app_purchase</a> plugin relies on the App Store and Google Play for making in-app purchases. but you still need to understand and configure your app with each store. You can check each store documentation</p><ul><li><a href="https://developer.apple.com/in-app-purchase/">App Store documentation</a></li><li><a href="https://developer.android.com/google/play/billing/billing_overview">Google Play documentation</a></li></ul><p>You can also check in-app purchase <a href="https://github.com/flutter/plugins/blob/main/packages/in_app_purchase/in_app_purchase/example/README.md">README Example</a> to help you configure your project before getting start.</p><p>Let me know in the comments how it goes 😉 this way I know if I need to write an article specially for this.</p><p>After we are done with the native steps and have a signed application on google play store and app store and have products added to them, Let’s move on to the code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVgi5B3KLFC3s0bNGFi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVgi5B3KLFC3s0bNGFi%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FVgi5B3KLFC3s0bNGFi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8a98efcc329919945bbac3bf5790ba/href">https://medium.com/media/3c8a98efcc329919945bbac3bf5790ba/href</a></iframe><p><strong>First we need to add the package in pubspec.ymal file</strong></p><blockquote><strong><em>in_app_purchase:</em></strong><em> </em>^3.0.6</blockquote><p>Let’s see the different types of products you can purchases through the use of this package.</p><blockquote><strong><em>Consumable</em></strong><em>: </em>One-time services, such as fish food in a fishing app</blockquote><blockquote><strong><em>Non-Consumable</em></strong><em>: </em>only need to be purchased once by users. Services that do not expire or decrease with use, such as new race tracks for a game app.</blockquote><blockquote><strong><em>Subscription</em></strong><em>: </em>Auto-renewable Subscriptions allow the user to purchase updating and dynamic content for a set duration of time</blockquote><h4>Connecting to the stores and loading products</h4><p>Make sure you followed the previous steps and did create products on stores</p><p>We need to check the stores availability before load the products details</p><pre><strong>final</strong> bool available = <strong>await</strong> InAppPurchase.instance.isAvailable();<br><strong>if</strong> (!available) {<br>  <em>// cannot connect with stores. Update the UI accordingly.</em><br>}else{<br>  // load products details.<br>}</pre><p>Now that we checked the store availability is time to load products details, to do that we have the queryProductDetails(your_product_id) method, this method request the store to return the product details for those specific products id (<em>make sure you have those products ids already created</em>)</p><pre><strong>final</strong> productsIds = &lt;String&gt;{&#39;product1&#39;, &#39;product2&#39;};<br><strong>final</strong> ProductDetailsResponse response = <strong>await </strong>InAppPurchase.instance.queryProductDetails(productsIds);</pre><pre><strong>if</strong> (response.notFoundIDs.isNotEmpty) {<br>  <em>// Handle the error.</em><br>}<br>List&lt;ProductDetails&gt; products = response.productDetails;</pre><p>We have done a basic query where we get all the products whose ids match the one we have provided.</p><h3>Listening to purchase updates</h3><p>In your app’s initState method, subscribe to any incoming purchases. You should always start listening to purchase update as early as possible to be able to catch all purchase updates, including the ones from the previous app session. To listen to the update:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/420994a8a82c1d4f5149182c874f7246/href">https://medium.com/media/420994a8a82c1d4f5149182c874f7246/href</a></iframe><p>That’s it 🙂 now you just need to handle purchase updates like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02df894fdb6064d52269c3776370969a/href">https://medium.com/media/02df894fdb6064d52269c3776370969a/href</a></iframe><p>Simple right ? 🥲 calm down let’s decode it</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FeMJMuOnsrxam3TxFXd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FeMJMuOnsrxam3TxFXd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FeMJMuOnsrxam3TxFXd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="348" frameborder="0" scrolling="no"><a href="https://medium.com/media/339e4942a19e466516aadc5a4d0aaf92/href">https://medium.com/media/339e4942a19e466516aadc5a4d0aaf92/href</a></iframe><p>This method _listenToPurchaseUpdated handle purchases updates states.</p><p>Let’s focus on purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored . This happen when the product/subscription was purchased successfully or restored and when it happen you <strong>always always always, I repeat ALWAYSSS… “must verify the purchase on backend before delivery it to user”, </strong>we add this logic on<strong> </strong>_verifyPurchase method.</p><p>If backend validation was successful then you must call <em>InAppPurchase.instance.completePurchase(purchaseDetails)</em></p><p>Calling <em>InAppPurchase.completePurchase</em> will inform the underlying store that the app verified and processed the purchase and the store can proceed to finalise the transaction and bill the end user&#39;s payment account</p><h4>What to send to backend to be validated ? 🤔</h4><p>You can take those params to send to backend this way 🙂 simple like that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a187d2e56c4d3867b6dbed29af36fcee/href">https://medium.com/media/a187d2e56c4d3867b6dbed29af36fcee/href</a></iframe><p>You’ll need to import in_app_purchase_storekit/in_app_purchase_storekit.dart to be able to use AppStorePurchaseDetails since it access IOS platform specific purchase properties</p><p>You can find more info here</p><ul><li><a href="https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products">GooglePlay</a></li><li><a href="https://developer.apple.com/documentation/storekit/in-app_purchase/original_api_for_in-app_purchase/validating_receipts_with_the_app_store">AppleStore</a></li></ul><h3>Making a purchase</h3><p>According to the <a href="https://pub.dev/packages/in_app_purchase#completing-a-purchase">doc</a></p><blockquote>The <em>InAppPurchase.purchaseStream</em> will send purchase updates after initiating the purchase flow using <em>InAppPurchase.buyConsumable</em> or <em>InAppPurchase.buyNonConsumable</em>. After verifying the purchase receipt and the delivering the content to the user it is important to call <em>InAppPurchase.completePurchase</em> to tell the underlying store that the purchase has been completed.</blockquote><p>Is super simple making a purchase</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b95158bea43a00fae6057a62bea440/href">https://medium.com/media/a9b95158bea43a00fae6057a62bea440/href</a></iframe><p>Both underlying stores handle consumable and non-consumable products differently. You need to make a distinction here and call the right purchase method for each type.</p><h3>Restore a purchase</h3><p>That’s a piece of cake 😋 just need to call the following method</p><pre><strong>await</strong> InAppPurchase.instance.restorePurchases();</pre><h3>Upgrading or downgrading an existing in-app subscription</h3><p>To upgrade/downgrade an existing in-app subscription in Google Play, you need to provide an instance of ChangeSubscriptionParam with the old PurchaseDetails that the user needs to migrate from, and an optional ProrationMode with the GooglePlayPurchaseParam object while calling InAppPurchase.buyNonConsumable.</p><p>The App Store does not require this because it provides a subscription grouping mechanism. Each subscription you offer must be assigned to a subscription group. Grouping related subscriptions together can help prevent users from accidentally purchasing multiple subscriptions. Refer to the <a href="https://developer.apple.com/app-store/subscriptions/#groups">Creating a Subscription Group</a> section of <a href="https://developer.apple.com/app-store/subscriptions/">Apple’s subscription guide</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2a7e4ea11b6d03babe2a2e297d0eedf/href">https://medium.com/media/e2a7e4ea11b6d03babe2a2e297d0eedf/href</a></iframe><h3>Presenting a code redemption sheet (iOS 14)</h3><p>For Android, according to <a href="https://developer.android.com/google/play/billing/billing_promotions.html">official documentation</a>,</p><blockquote><em>If your app supports the in-app purchase workflow(described in </em><a href="https://developer.android.com/google/play/billing/billing_integrate.html#billing-requests"><em>Making In-app Billing requests</em></a><em>), your app automatically supports in-app redemption of promo codes.</em></blockquote><p>So our app by default when we add in-app purchase support it automatically is prepared to deal with redemption of promo codes. <strong>Let’s worry just with Apple now</strong> 🙂</p><p>The following code brings up a sheet that enables the user to redeem offer codes that you’ve set up in App Store Connect. For more information on redeeming offer codes, see <a href="https://developer.apple.com/documentation/storekit/in-app_purchase/subscriptions_and_offers/implementing_offer_codes_in_your_app">Implementing Offer Codes in Your App</a>.</p><pre>InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = InAppPurchase.getPlatformAddition&lt;InAppPurchaseStoreKitPlatformAddition&gt;();</pre><pre>iosPlatformAddition.presentCodeRedemptionSheet();</pre><blockquote><em>Note: The </em><em>InAppPurchaseStoreKitPlatformAddition is defined in the </em><em>in_app_purchase_storekit.dart file so you need to import it into the file you will be using </em><em>InAppPurchaseStoreKitPlatformAddition:</em></blockquote><blockquote><strong><em>import</em></strong><em> &#39;package:in_app_purchase_storekit/in_app_purchase_storekit.dart&#39;;</em></blockquote><h3>An amazing Bonus for you 😊</h3><p>I developed a project using <strong>in-app purchase and riverpod</strong> as state management, you can all we learned in practice</p><p><a href="https://github.com/antonio-nicolau/flutter-in-app-purchase">GitHub - antonio-nicolau/flutter-in-app-purchase: A Flutter app to show how to implement in-app purchase using the in-app-purchase package</a></p><h3>That’s it 💪🏿 now you’re ready to go with in-app purchase</h3><p>I hope you enjoyed this tour through in-app purchase and now you see now that it isn’t so complicated like it sounded.</p><p><strong>Follow me for more Flutter tips </strong>🙂</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FlMVNl6XxTvXgs%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FlMVNl6XxTvXgs%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FlMVNl6XxTvXgs%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/e14a702be67c11a1a2fa8e86ec4f00f0/href">https://medium.com/media/e14a702be67c11a1a2fa8e86ec4f00f0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c863042aee15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>