<?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 Ernesto Alfonso on Medium]]></title>
        <description><![CDATA[Stories by Ernesto Alfonso on Medium]]></description>
        <link>https://medium.com/@erns70b?source=rss-6fdd9be740b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oYSFRnGMSrvVXUIxFB28eg@2x.jpeg</url>
            <title>Stories by Ernesto Alfonso on Medium</title>
            <link>https://medium.com/@erns70b?source=rss-6fdd9be740b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:17:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erns70b/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[Fixing unit tests with AutoRoute and Mockito]]></title>
            <link>https://medium.com/@erns70b/fixing-unit-tests-with-autoroute-and-mockito-6932512a4cc6?source=rss-6fdd9be740b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6932512a4cc6</guid>
            <category><![CDATA[issues]]></category>
            <category><![CDATA[autoroute]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ernesto Alfonso]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 12:29:24 GMT</pubDate>
            <atom:updated>2023-06-04T12:29:24.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The image shows an astronaut and planets." src="https://cdn-images-1.medium.com/max/1024/1*rFgKHPI5UQDrA2i9Yxd-TQ.jpeg" /><figcaption>Taken from <strong>ImagenesPoeticas</strong> on <a href="https://t.me/Imagenespoeticas">Telegram</a></figcaption></figure><p>It&#39;s been a while since I started to use the <a href="https://pub.dev/packages/auto_route"><strong>auto_route</strong></a> package for routing. It’s straightforward and intuitive. Before, I tried others, but since I began to use auto_route, it was like love at first sight.</p><p>On the other side, I’ve always used <a href="https://pub.dev/packages/mockito"><strong>Mockito</strong></a> for testing. Doesn’t matter the language, there is always a library with this popular name among developers, and the result is always the same: Just the best!</p><p>This weekend I re-take an old side project 🕸️ 🕷️ and migrate it to the latest version of Flutter available at the moment (from 3.0.1 to 3.10.2), and also upgrade all the packages to the latest possible version. The pub <strong>auto_router</strong> was <strong>updated from version 5.0.4. to 7.4.0, </strong>and<strong> </strong>the pub<strong> </strong><strong>mockito </strong>was updated<strong> from version 5.3.2 to 5.4.1… </strong>a<strong> </strong>very long jump that will cause trouble for sure.</p><p>Then every unit test just fucked up 🥶😱</p><p>The problem was that in the new version, Mockito is not generating the stubs for the routing methods: navigate , navigateBack, push, replaceAlland others…. every test where I was doing:</p><pre> final appRouter = MockAppRouter();<br><br>  setUpAll(() {<br>     ....<br>    locator.allowReassignment = true;<br>    locator.registerSingleton&lt;AppRouter&gt;(appRouter);<br>    when(appRouter.navigate(any)).thenAnswer((_) async =&gt; true);<br>  });<br><br>  ....<br>  <br>  verify(appRouter.navigate(const SomeOtherRoute()));</pre><p>was failing with the next error:</p><pre>type &#39;Null&#39; is not a subtype of type &#39;Future&lt;void&gt;&#39;</pre><p>After I made 30 to 40 minutes of research on the internet and looked at the GitHub issues on the package repository I was unable to find any solution for this issue. So I dig deep into the reason why this was happening.</p><p>The first I notices was not a big change in the <strong>auto_router</strong>package:</p><blockquote>- My class AppRouter extends from _$AppRouter that extends from RootSrackRouter that extends from StackRouter and extends from RoutingController … what a tree 🎄</blockquote><blockquote>- The RoutingController is the one who defines the methods for navigation in general while the StackRouter defines the methods mentioned in the error above.</blockquote><p>Somehow, before the upgrade, Mockito was able to introspect and generate all the mocks for this method, but after the upgrade, it doesn&#39;t do that anymore (or at least not for me 🤷🏻‍♂️). I still don’t know why this happens, but I found a solution for fixing this at least momentarily.</p><p>First I defined this class on test/mocks/test_router.dart</p><pre>class TestRouter extends Mock implements AppRouter, StackRouter {}</pre><p>Then on the file test/mocks/mock.dart</p><pre>@GenerateMocks(<br>  [],<br>  customMocks: [<br>    MockSpec&lt;TestRouter&gt;(<br>      as: Symbol(&#39;MockAppRouter&#39;),<br>      onMissingStub: OnMissingStub.returnDefault,<br>    )<br>  ],<br>)<br>void main() {}</pre><p>now I can do:</p><pre><br>import &#39;package:app_name/route/to/injector.dart&#39;;<br>import &#39;package:app_name/route/to/app_routes.dart&#39;;<br>import &#39;package:app_name/route/to/some_page.dart&#39;;<br><br>import &#39;../../../helpers/extensions.dart&#39;;<br>import &#39;../../../mocks/mocks.mocks.dart&#39;;<br><br>void main() {<br>  TestWidgetsFlutterBinding.ensureInitialized();<br>  final appRouter = MockAppRouter();<br><br>  setUpAll(() {<br>    locator.allowReassignment = true;<br>    locator.registerSingleton&lt;AppRouter&gt;(appRouter);<br>    when(appRouter.navigate(any)).thenAnswer((_) async =&gt; true);<br>  });<br><br>  // There is an animation in [SomePage]. <br>  // Once it ends navigate to [SomeOtherRoute]<br>  testWidgets(&#39;when animation ends navigate to home&#39;,<br>      (WidgetTester tester) async {<br>    // Build our app and trigger a frame.<br>    await tester.pumpWithAppScope(<br>      widget: const SomePage(),<br>    );<br><br>    // Wait for animation<br>    await tester.pump(1.seconds);<br>    await tester.pumpAndSettle();<br><br>    // Check navigation<br>    verify(appRouter.navigate(const SomeOtherRoute()));<br>  });<br>}</pre><p>and that’s it 😁🥳</p><h3>The end</h3><p>Thanks for getting here 🙏🙏.</p><p>With the hope you don’t spend 30 to 40 minutes searching to solve this issue, I stopped working and came to write this post. If you found it helpful please give me a clap 👏.</p><p>Feel free to provide any feedback or recommendation and if you have another way of solving this, please leave it in the comments 👍🏼</p><p>Until the next one: keep improving! The limit is your imagination!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6932512a4cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter state management tips]]></title>
            <link>https://medium.com/@erns70b/flutter-state-management-tips-e011f48b4b2c?source=rss-6fdd9be740b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e011f48b4b2c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[tips]]></category>
            <dc:creator><![CDATA[Ernesto Alfonso]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 08:06:26 GMT</pubDate>
            <atom:updated>2022-08-25T08:06:26.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hk8DbHebfXiyKQK-" /><figcaption>Photo by <a href="https://unsplash.com/@joszczepanska?utm_source=medium&amp;utm_medium=referral">Jo Szczepanska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After 5 years of developing applications in Flutter, I’ve made the travel across several state management packages and approaches. In projects so far I&#39;ve used InheritedWidget/Model, BLoC Pattern, RxDart, Provider, GetX, and Riverpod. After all this unfinished journey I’ve learned successful tips in each of them that I will share in the following lines.</p><blockquote><strong>⚠️ Disclaimer: </strong>In this post, I’m giving an opinion based on my personal experience. I do not intend to discredit or prejudice those packages that I do not know or have not used.</blockquote><h3>1. Make the right choice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*3Lp-z8UhL02ItNvakTDV_Q.jpeg" /><figcaption>meme created by myself</figcaption></figure><p>There are a lot of <a href="https://docs.flutter.dev/development/data-and-backend/state-mgmt/options">options for state management</a> in the flutter pub. Every time you’re going to start a new project could be hard to choose among all of them, and sometimes making the wrong decision could lead to a lot (yes! A LOT!!) of time wasted fixing bugs, misbehavior, code duplicity, a high learning curve for new team members and in some cases a lot of code refactoring.</p><p>When we are trying to choose we need to have several things in mind given the nature of the challenge we are facing. For this we need to have clear several “key variables” that we need to analyze:</p><ul><li>Time budget</li><li>Size of the project (complexity)</li><li>Size of the team</li><li>The expertise of the team members *</li></ul><blockquote>(*) Here I´m talking about if the team members have experience in some of the state management options.</blockquote><p>I used to do it this way. If the time <strong>budget is high</strong> and the <strong>team is only me</strong> (one man band) then I <strong>try a new package</strong> that I´ve never used before. This is the way I get here and how I get to know several of the state management options.</p><p>If <strong>the majority of the team members</strong> have <strong>a lot of experience</strong> in one package <strong>that one is the one to choose</strong>. The best way to look at it is that you should have a very good justification to deviate from familiar technologies. New tech always brings in unknown factors that could be costly long term, so sticking to what you know reduces risk in the project. But sometimes what you know isn’t fit for the problem, and at this point, you should reevaluate.</p><p><strong>Based on my experience</strong> with the technologies I’ve already mentioned I made this graph where I rank the packages given the project complexity and time budget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*LeZIU_RynFfj5npC9O4RHQ.png" /><figcaption>Ranking of libraries given the project complexity and time budget</figcaption></figure><p>If the <strong>time budget is short</strong> and the <strong>complexity is low (green square)</strong>, then <strong>GetX is the best choice</strong>. <a href="https://pub.dev/packages/get">GetX</a> is an extra-light and powerful tool for state management that has gained a lot of fame among flutter developers. It is very powerful indeed but lacks organization and readability for long and complex projects. Also, there is a huge amount of issues that the package has been carrying that can create problems in long and complex applications.</p><p>If the <strong>time budget is long</strong> and the <strong>complexity is low (blue square)</strong>, then you should <strong>try </strong><a href="https://pub.dev/packages/bloc"><strong>BLoC Pattern</strong></a>. Because time is not a problem and complexity is low, using the BLoC pattern you can get to understand what is State Management and all the concepts attached to it. The journey through this may be beneficial for your personal development as well as for your professional career because many real job options in the flutter environment require knowledge of the BLoC pattern. In case you decide to go with this option may be good for you to read <a href="https://medium.com/codechai/architecting-your-flutter-project-bd04e144a8f1">this article</a>.</p><p>If the <strong>time budget is short</strong> and the <strong>complexity is high (yellow square)</strong>, then <strong>Provider is the one I choose. </strong>The <a href="https://pub.dev/packages/provider">Provider</a> does not need a high amount of code to deliver state management compared to Riverpod. Merging it with <a href="https://pub.dev/packages/get_it">GetIt</a> can create a very powerful tool with which you can develop a complex project in a short time and the learning curve is so low that you can even develop while you learn.</p><p>Last but not least, If the <strong>time budget is long</strong> and the <strong>complexity is high (red square)</strong>, then <strong>Riverpod will make it. </strong>Riverpod is that kind of package that you can dislike at first sight but when you get into it you end up loving it ’cause is very powerful. It really can be used in any of the scenarios mentioned before if you have skills in it. For me is so far the best State Management package I’ve used and my journey with it have started only a few months ago.</p><p>Of course, criteria can be diverse, also I’ve never used other packages such as MobX or Redux but I promise that when I do, I will enrich this post with those experiences.</p><h3>2. Use State Management wisely</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*oLLCJtK8BEXKVyWghix_aQ.jpeg" /><figcaption>With great power comes great responsibility — Uncle Ben, Spiderman.</figcaption></figure><p>In my experience, I’ve seen and faced situations where I’ve realized State Management was used in the wrong way. One of the common ways is when we create a whole view as a Consumer when we just need to change the state to a short part of it, repainting all the view instead of just the section that must be repainted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b697eec39496e2b51cfe0fdd99ba31f/href">https://medium.com/media/1b697eec39496e2b51cfe0fdd99ba31f/href</a></iframe><p>In the above example (Riverpod) we are watching the provider in the build method of the Home widget which makes it reactive. Then every time we hit the button the whole view is repainted instead of only the Text that shows the count.</p><p>The correct way of using it can be found in the counter-example on the riverpod repository:</p><p><a href="https://github.com/rrousselGit/riverpod/blob/master/examples/counter/lib/main.dart#:~:text=%7D-,///%20Providers%20are%20declared%20globally%20and%20specify%20how%20to%20create%20a%20state,%7D,-Footer">riverpod/main.dart at master · rrousselGit/riverpod</a></p><p>That being said, you should always think on what is the exact part of the view that will change to not repaint widgets that don&#39;t need to be repainted.</p><h3>3. Where the captain rules, the sailor doesn´t</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETGL88SDDzhV3wf1" /><figcaption>Photo by <a href="https://unsplash.com/@feneek?utm_source=medium&amp;utm_medium=referral">Sergey Semin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Do not use more than one State Management approach/package. This is not correct. One and only one package should be enough to fulfill the requirements of every application. So if you get to the point where you need to use another approach then just go to the documentation or ask an experienced developer because there should be a way to solve your issue using your current approach.</p><p>Also don’t feel bad if at an advanced point of development you figure it out that your choice was not a good one. Just keep moving with that choice. In some cases changing the approach could lead to almost starting from scratch again. Focus on the goal, write the learnings, and refactor what you have but never mix packages.</p><h3>(Bonus) Use Reactive Forms 😁</h3><blockquote>Reactive Forms provides a model-driven approach to handling form inputs whose values change over time. It’s heavily inspired by Angular Reactive Form</blockquote><p>It avoids a lot of time of coding trying to accomplish the same with any other package.</p><p>If you’re interested in it you can read this article that I wrote: <a href="https://medium.com/@erns70b/forms-in-flutter-have-never-been-so-easy-3b707c4236cf">Reactive Forms in Flutter have never been so eas</a>y</p><p>And this other one from the package creator: <a href="https://dev.to/joanpablo/star-rating-with-flutter-reactive-forms-2d52">Star Rating with Flutter Reactive Forms</a></p><h3>The end</h3><p>Thanks for getting here 🙏🙏.</p><p>I hope you found this helpful. If so please give me a clap 👏. Feel free to provide any feedback or recommendation.</p><p>Until the next one: keep improving! The limit is your imagination!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e011f48b4b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Formularios Reactivos en Flutter de manera fácil]]></title>
            <link>https://medium.com/@erns70b/formularios-reactivos-en-flutter-de-manera-f%C3%A1cil-7b73b3fc6b25?source=rss-6fdd9be740b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b73b3fc6b25</guid>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[flutter-form]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ernesto Alfonso]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 05:31:52 GMT</pubDate>
            <atom:updated>2022-08-22T05:31:52.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>Formularios en Flutter de manera fácil</h3><figure><img alt="A file with some forms, a calculator and a cup of coffe" src="https://cdn-images-1.medium.com/max/1024/0*wic8DsA05YsDIEBS" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/@erns70b/forms-in-flutter-have-never-been-so-easy-3b707c4236cf">Reactive Forms in Flutter have never been so easy</a></p><p>No hay casi ninguna aplicación que no tenga formularios. La adquisición de datos, la autenticación y la creación de perfiles son algunos de los principales casos de uso para que una aplicación incluya cualquier formulario. Además, los formularios son el punto de presión preferido por los evaluadores de control de calidad (QA testers), ya que la validación de datos es uno de los puntos más atacados por aquellos que intentan encontrar agujeros en nuestras aplicaciones. Es por eso que crear un formulario puede ser complejo para los desarrolladores, independientemente del <em>framework</em> o el lenguaje. Hacer un buen formulario siempre es difícil de hacer si necesita tener en cuenta todos los casos extremos.</p><p>En este artículo, compararé la <a href="https://docs.flutter.dev/cookbook/forms/validation">forma nativa</a> en flutter y una biblioteca que creo que me hizo la vida más fácil desde que comencé a usarla en sus primeras versiones. Estoy hablando de <a href="https://pub.dev/packages/reactive_forms"><em>reactive_forms</em></a></p><p>Lo que haremos es:</p><ol><li>Iniciar el proyecto.</li><li>Crear dos formularios idénticos, uno con Flutter Forms y el otro con Reactive Forms.</li><li>Validar los campos de los formularios.</li><li>Obtener datos de los formularios.</li><li>Deshabilitar el botón cuando el formulario no es válido.</li></ol><p>Primero, me gustaría agradecer al creador del paquete por su trabajo y a la comunidad por el apoyo. Te animo a que le des un Me Gusta 👍 al paquete en <a href="https://pub.dev/packages/reactive_forms">pub.dev</a> y una Estrella ⭐️ en <a href="https://github.com/joanpablo/reactive_forms">Github</a> si lo usas y lo encuentras útil.</p><h3>1. Iniciar el Proyecto.</h3><p>Comencemos creando un nuevo proyecto y modificando <strong>lib/main.dart</strong> para eliminar cualquier comentario y código innecesarios. En <strong>MyHomePage</strong> ponemos dos botones, uno para mostrar la versión de Flutter Form y el otro para la versión de Reactive Form. El resultado debería ser como esta vista:</p><figure><img alt="Home view with two buttons" src="https://cdn-images-1.medium.com/max/1024/1*hxXDJjUuhGUZyOf0jQzsww.png" /><figcaption>Home View with two buttons</figcaption></figure><p>Después de esto, creamos dos ficheros separados en la carpeta<strong> /lib</strong>: <strong>flutter_form_example.dart</strong> y <strong>reactive_form_example.dart</strong>. Ahora agregamos navegación a estas vistas desde MyHomePage haciendo lo siguiente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08f672c153a1063b55e550db07ea63bc/href">https://medium.com/media/08f672c153a1063b55e550db07ea63bc/href</a></iframe><p>Ahora todo está listo para pasar al siguiente capítulo 👌.</p><h3>2. <strong>Crear dos formularios idénticos, uno con Flutter Forms y el otro con Reactive Forms.</strong></h3><h4>2.1 Crear el formulario Flutter</h4><p>Para crear el Flutter Form, simplemente copie y pegue el siguiente código.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/478cc7145618d01efe44f0b80009bde5/href">https://medium.com/media/478cc7145618d01efe44f0b80009bde5/href</a></iframe><h4>2.2 Create Reactive Form</h4><p>Para la versión de Reactive Form, hay varias formas de crear un formulario. Este artículo usaré una simple, pero puede leer la documentación del paquete para encontrar y probar los otras.</p><blockquote><em>En Reactive Forms &quot;</em>Un formulario se compone de múltiples campos o controles<em>&quot;. Un FormGroup es el componente principal para crear formularios. Puede contener FormControls pero también puede incluir estructuras más complejas como FormArrays u otros FormControls anidados. (</em><a href="https://pub.dev/packages/reactive_forms#creating-a-form"><em>Lee mas</em></a><em>).</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57ece250f4dd719231d6abca2ddc9ed/href">https://medium.com/media/c57ece250f4dd719231d6abca2ddc9ed/href</a></iframe><p>En la <strong>línea 12</strong>, se crea <strong>FormGroup</strong>. Este es un mapa que tiene como key el <strong>FormControlName</strong> y como value los <strong>FormControl</strong>. El widget principal para alojar nuestro formulario es el widget <strong>ReactiveForm</strong>. Contendrá todos los widgets reactivos como <strong>ReactiveTextField</strong> (primo de <strong>TextFormField</strong>), <strong>ReactiveCheckboxListTile</strong>, etc.</p><p>Además, envolvemos el Botón en un ReactiveFormConsumer. Este widget tendrá el estado actualizado del formulario en su constructor. De esta manera, flutter no repinta toda la vista cuando cambia el estado del formulario.En este momento, tenemos dos pantallas similares. El código no es muy diferente para las dos versiones pero la parte divertida comienza aquí. 👉</p><h3>3. Validar los campos de los formularios.</h3><p>Ahora vamos a validar los campos siguiendo las siguientes reglas:</p><ol><li><strong>Nickname:</strong> Requerido. Solo caracteres alfanuméricos, no puede tener saltos ni espacios. Caracteres “-”, “_” y “.” están permitidos.</li><li><strong>Email:</strong> Requerido. Debe ser una cadena de correo electrónico válida.</li><li><strong>Comment:</strong> Longitud máxima 120 caracteres.</li><li><strong>Terms and conditions: </strong>es obligatorio ser seleccionado.</li></ol><p>Para validar los campos <em>Nickname</em> y <em>Email</em> agregamos la propiedad del <strong><em>validator</em></strong> del <strong>TextFormField</strong>, luego para el RegExp utilize estas expresiones regulares:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd84a84e0fb53a62109a0ec70e106cc9/href">https://medium.com/media/dd84a84e0fb53a62109a0ec70e106cc9/href</a></iframe><p>También configuramos <strong>autovalidateMode</strong>: <strong>AutovalidateMode.onUserInteraction</strong> para que los campos se validen a medida que el usuario escribe. Para los campos <em>Nickname</em> y <em>Comment</em>, usamos la propiedad <strong>maxLength</strong> para validar y mostrar la longitud máxima visible en el formulario. Esta es la forma nativa de validar campos de formulario.</p><p>Luego al presionar el Botón <em>Submit,</em> vamos a verificar la validez de los campos y también si se seleccionó los Términos y Condiciones. El resultado es el siguiente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fdf874e0cab309eb6e2868db49b1bfb/href">https://medium.com/media/8fdf874e0cab309eb6e2868db49b1bfb/href</a></iframe><p>El lado del Formulario Reactivo necesita mucho menos código para hacer esto.</p><p>Primero, modifique <strong>FormGroup</strong> para incluir validadores. Utilice <strong>Validators.required</strong> para los campos obligatorios, <strong>Validators.email</strong> para el campo correo electrónico y<strong> Validators.pattern</strong> para el RexExp del campo <em>Nickname</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6016875a5d8a28cbb8a26290aab0698/href">https://medium.com/media/e6016875a5d8a28cbb8a26290aab0698/href</a></iframe><p>Luego, agregue <em>ValCamposnMessages</em> a los campos y listo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6fc5423debc32bf9b37e18745ed2af/href">https://medium.com/media/7b6fc5423debc32bf9b37e18745ed2af/href</a></iframe><p>En este punto se aprecia la diferencia. Mientras que en flutter nativo necesitábamos codificar mucho para hacer las validaciones, en <em>Reactive Forms</em> es muy fácil y sin tanto código.</p><h3>4. Obtener datos de los formularios.</h3><p>Obtener los datos del formulario no es simple en Flutter. Para esto hay varios enfoques, pero el que se usa en el <a href="https://docs.flutter.dev/cookbook/forms/retrieve-input">cookbock de flutter</a> es empleando <strong>TextEditingControllers</strong>, uno para cada <strong>TextFormField</strong>. Así que vamos a seguir este enfoque. Luego mostraremos los datos en un SnackBar como el siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*DmuJwVmMPMlWJpZ7S5l9Lg.png" /><figcaption>SnackBar example</figcaption></figure><p>Primero, creamos los controladores de edición de texto y agréguelos a <strong>TextFormFields</strong> en la propiedad: controlador.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e3976995f0d6f8eb536db5ee94974c/href">https://medium.com/media/c4e3976995f0d6f8eb536db5ee94974c/href</a></iframe><p>Luego mostramos los datos en el <em>SnackBar</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d6fb1a75110f9237ead0bb334d53f8f/href">https://medium.com/media/9d6fb1a75110f9237ead0bb334d53f8f/href</a></iframe><p>En el lado de la forma reactiva, no necesitamos demasiado código para esto. El objeto <strong><em>form</em></strong> en el <strong><em>builder</em></strong> del <strong>ReactiveFormConsumer</strong> devuelve un Mapa con los valores para cada <em>FormControl</em>. Así que simplemente agregue este código al botón Enviar</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f49ea7a779d6e7f763a1acb7c89e79/href">https://medium.com/media/a7f49ea7a779d6e7f763a1acb7c89e79/href</a></iframe><h3>5. Deshabilitar el botón cuando el formulario no es válido.</h3><p>Una de las mejores formas de decirle al usuario que tiene errores de validación es deshabilitando el botón si el formulario no es válido.</p><p>En Flutrter, necesitamos hacer lo siguiente:</p><ol><li>Agregar una variable booleana para mantener el estado de validación.</li><li>Agregar un <em>listener</em> en la propiedad <strong>onChanged</strong> del formulario para establecer el estado y cambiar el valor de esa variable</li><li>Hacer que la propiedad <strong>onPressed</strong> del botón <em>Submit</em> sea condicional para devolver un valor nulo si la variable es falsa</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b147632a17376b4262e813dd151f71/href">https://medium.com/media/55b147632a17376b4262e813dd151f71/href</a></iframe><p>En Reactive Form simplemente hay que verificar la propiedad <strong>valid</strong> del formulario en el parámetro <strong>onPressed</strong> del botón Enviar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6525f61e9d4a66a7ac955f0f32fbab5/href">https://medium.com/media/d6525f61e9d4a66a7ac955f0f32fbab5/href</a></iframe><h3>Conclusión</h3><p>Así termina esto. He tratado de demostrar aquí que es muy fácil y útil usar formularios reactivos para crear formularios complejos en nuestras aplicaciones. Las ventajas de su uso que pudimos ver con este ejemplo son:</p><ul><li>Menos código</li><li>Fácil validación</li><li>Algunas validaciones están predefinidas en la biblioteca.</li><li>Si coloca un print en el método build del formulario Flutter, verá que la vista se vuelve a pintar cada vez que el usuario ingresa un carácter en un <strong>TextFormField</strong>. En cambio en Reactive Forms, esto no ocurre.</li><li>También en <strong>Profiling</strong> se puede ver que la versión reactiva es más óptima que la nativa</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*bgi3uCuj0NwbNoeYTw9BkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*LPFmvqegKGXgnRUEG2xcXQ.png" /></figure><p>Además, otras ventajas de usar Reactive Forms son:</p><ul><li>Una gran cantidad de widgets reactivos que se pueden usar (<a href="https://pub.dev/packages/reactive_forms#supported-reactive-form-field-widgets">ver aqui</a>)</li><li>Generador de código (<a href="https://pub.dev/packages/reactive_forms_generator">leer mas</a>)</li><li>Imagine que tiene un campo como un número de teléfono y una persona puede tener más de uno, por lo que debe repetir el mismo campo varias veces y almacenar los datos en un arreglo. Bueno, con Reactive Forms esto es pan comido 🍞 si usas <strong>FormArray</strong>.</li><li>Imagina que tienes un formulario dividido en varias vistas 🤯 (como un carrusel) y necesitas enviar los datos al final. Con Reactive Forms también es muy fácil hacer esto.</li></ul><p>No diré más 🤗. Solo anímese a leer los documentos y darle una oportunidad.</p><p>Puedes encontrar <a href="https://github.com/Ch4rl3B/easy_reactive_forms"><strong>EL CÓDIGO AQUÍ</strong></a>.</p><p>Además, si esto te resultó útil, dame un aplauso 👏. Este es mi primer post por lo que cualquier comentario positivo o negativo que me puedan dar será muy bien recibido.</p><p>Hasta el próximo: ¡sigue mejorando! El límite es tu imaginación!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b73b3fc6b25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Forms in Flutter have never been so easy]]></title>
            <link>https://medium.com/@erns70b/forms-in-flutter-have-never-been-so-easy-3b707c4236cf?source=rss-6fdd9be740b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b707c4236cf</guid>
            <category><![CDATA[reactive-form-validation]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[form-validation]]></category>
            <dc:creator><![CDATA[Ernesto Alfonso]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 08:04:00 GMT</pubDate>
            <atom:updated>2022-07-13T15:28:09.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A file with some forms, a calculator and a cup of coffe" src="https://cdn-images-1.medium.com/max/1024/0*wic8DsA05YsDIEBS" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is almost no application that doesn’t have forms. Data acquisition, authentication, and profiling are some of the primary use cases for an application to include any Form. Also, forms are the preferred point of pressure for QA testers as data validation is one of the most attacked points for those who try to find holes in our applications. That is why making a form can be painful for developers regardless of the framework or language. Making a good form is always hard to do if you need to look for all the edge cases.</p><p>In this article, I will contrast <a href="https://docs.flutter.dev/cookbook/forms/validation">classical forms in flutter</a> and a package that I think made my life easier since I started to use it in its early versions. I’m talking about <a href="https://pub.dev/packages/reactive_forms"><em>reactive_forms</em></a>.</p><p>What we will do is:</p><ol><li>Scaffold the project.</li><li>Create two identical forms, one using Flutter Forms and the other using Reactive Forms.</li><li>Validate form fields.</li><li>Get form data.</li><li>Disable the button on an invalid form.</li></ol><p>First, I would like to thank the package creator for his work and the community for the support. I encourage you to give the package a Like 👍 in <a href="https://pub.dev/packages/reactive_forms">pub.dev</a> and a Star ⭐️ on <a href="https://github.com/joanpablo/reactive_forms">Github</a> if you use it and find it helpful.</p><h3>1. Scaffold the project</h3><p>Start by creating a new project and modifying the <strong><em>lib/main.dart </em></strong>to remove any unnecessary comments and code. In MyHomePage create two buttons, one for showing the Flutter Form version and the other for the Reactive Form Version. The result should be like this view:</p><figure><img alt="Home view with two buttons" src="https://cdn-images-1.medium.com/max/1024/1*hxXDJjUuhGUZyOf0jQzsww.png" /><figcaption>Home View with two buttons</figcaption></figure><p>After this create two separate files under <strong><em>/lib</em></strong> folder: <em>flutter_form_example.dart</em> and <em>reactive_form_example.dart</em>. Now add navigation to these views from MyHomePage by doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08f672c153a1063b55e550db07ea63bc/href">https://medium.com/media/08f672c153a1063b55e550db07ea63bc/href</a></iframe><p>Now everything is ready to move to the next chapter 👌.</p><h3>2. Create two identical forms, one using Flutter Forms and the other using Reactive Forms.</h3><h4>2.1 Create the Flutter Form</h4><p>To create the flutter form just copy/paste the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/478cc7145618d01efe44f0b80009bde5/href">https://medium.com/media/478cc7145618d01efe44f0b80009bde5/href</a></iframe><h4>2.2 Create Reactive Form</h4><p>For the reactive form version, there are several ways of creating a Form. This article will use a simple one, but you can read the package documentation to find and try the others.</p><blockquote>In reactive forms “<em>A form is composed of multiple fields or controls.</em>”. A FormGroup is the main component for creating forms. It can contain FormControls but also can include more complex structures such as FormArrays or other nested FormControls. (<a href="https://pub.dev/packages/reactive_forms#creating-a-form">Read more</a>).</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57ece250f4dd719231d6abca2ddc9ed/href">https://medium.com/media/c57ece250f4dd719231d6abca2ddc9ed/href</a></iframe><p>On the <strong><em>12th line, </em></strong>the <strong>FormGroup</strong> is created. The form group is a Map that contains the <strong>FormControlName</strong> and the <strong>FormControl</strong> object. The main widget to host our form is the <strong>ReactiveForm</strong> widget. It will hold all the reactive widgets such as <strong>ReactiveTextField</strong> (cousin of the TextFormField), <strong>ReactiveCheckboxListTile</strong>, and so on.</p><p>Also, wrap the <em>Button</em> in a <strong>ReactiveFormConsumer</strong>. This widget will have the updated state of the form in its builder. Then <strong>flutter doesn’t repaint all the view when the form states changes</strong>.</p><p>At this point, we have two similar views. The code is not much different for the two versions because the fun part begins here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRb-8VQxjZ1cbX2iji4Acg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhaHwa-9ArayngBU6j5K-g.png" /><figcaption>The two forms till now</figcaption></figure><h3>3. Validate form fields</h3><p>Now we are going to validate the fields following the next rules:</p><ol><li><strong>Nickname:</strong> Required. Only alphanumeric characters, can’t have jumps or spaces. Characters “-”, “_”, and “.” are allowed.</li><li><strong>Email:</strong> Required. Must be a valid email string.</li><li><strong>Comment:</strong> Max length 120 characters.</li><li><strong>Terms and conditions</strong> are mandatory to be selected.</li></ol><p>For validating the <em>Nickname and Email </em>fields add the <strong><em>validator</em></strong> property in <strong>TextFormField</strong>, then use <strong>RegExp</strong> validate using these regular expressions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd84a84e0fb53a62109a0ec70e106cc9/href">https://medium.com/media/dd84a84e0fb53a62109a0ec70e106cc9/href</a></iframe><p>Also set <strong><em>autovalidateMode: AutovalidateMode.onUserInteraction</em></strong> for having the fields be validated as the user types. For <em>Nickname</em> and <em>Comment</em> fields use the property <strong>maxLength</strong> to validate and show the max length visible on the form. This is the native way of validating Form fields.</p><p>Then in the <em>Submit Button</em>, when pressed check the validity of the fields, and also if <em>Terms and Conditions</em> were checked to act. The result is next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fdf874e0cab309eb6e2868db49b1bfb/href">https://medium.com/media/8fdf874e0cab309eb6e2868db49b1bfb/href</a></iframe><p>The Reactive Form side needs way less code to do this.</p><p>First, modify FormGroup to include validators. Use <strong>Validators.required</strong> for required fields, <strong>Validators.email</strong> for <em>Email</em> field, and <strong>Validators.pattern</strong> for the RexExp of the <em>Nickname</em> field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6016875a5d8a28cbb8a26290aab0698/href">https://medium.com/media/e6016875a5d8a28cbb8a26290aab0698/href</a></iframe><p>Then add the <em>ValidationMessages</em> to the fields and that’s it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6fc5423debc32bf9b37e18745ed2af/href">https://medium.com/media/7b6fc5423debc32bf9b37e18745ed2af/href</a></iframe><p>At this point, you see the difference. While in flutter we needed to code a lot of boilerplate for doing the validations, in reactive forms was very easy and without so much code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlEY9H8oL5KGWW6qklQZ-A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ajy5JyTxKy0d_LgYHWlW1w.gif" /></figure><h3>4. Get form data</h3><p>Getting the form data is not simple in flutter form. For this, there are several approaches but the one used in <a href="https://docs.flutter.dev/cookbook/forms/retrieve-input">the flutter cookbook</a> is using <strong>TextEditingControllers</strong>, one for each <strong>TextFormField</strong>. So we are going to follow this approach. Then show the data on the <em>SnackBar</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*DmuJwVmMPMlWJpZ7S5l9Lg.png" /><figcaption>SnackBar example</figcaption></figure><p>First, create the text editing controllers and add them to the <strong>TextFormFields</strong> on the property: <em>controller</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e3976995f0d6f8eb536db5ee94974c/href">https://medium.com/media/c4e3976995f0d6f8eb536db5ee94974c/href</a></iframe><p>Then show the data in the <em>SnackBar</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d6fb1a75110f9237ead0bb334d53f8f/href">https://medium.com/media/9d6fb1a75110f9237ead0bb334d53f8f/href</a></iframe><p>On the reactive form side, we don’t need too much for this. The form object in the <strong>ReactiveFormConsumer</strong> builder has the property <strong><em>value</em></strong> which returns a Map with the values for each control. So just ad this code to the <em>Submit Button</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f49ea7a779d6e7f763a1acb7c89e79/href">https://medium.com/media/a7f49ea7a779d6e7f763a1acb7c89e79/href</a></iframe><h3>5. Disable the button on an invalid form</h3><p>One of the best ways of telling the user that he has validation errors is by disabling the button if the form is invalid.</p><p>On the flutter side we need to create the next workaround:</p><ol><li>Add a boolean variable to hold the validation state.</li><li>Add a listener on the <strong>onChanged</strong> property of the form to set the state and change the value of that variable</li><li>Make the <strong>onPressed</strong> property of the <em>Submit Button</em> conditional to return null if the variable is false</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b147632a17376b4262e813dd151f71/href">https://medium.com/media/55b147632a17376b4262e813dd151f71/href</a></iframe><p>In reactive form just check the property <strong><em>valid</em></strong> of the form in the <strong>onPressed</strong> property of the <em>Submit</em> <em>Button</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6525f61e9d4a66a7ac955f0f32fbab5/href">https://medium.com/media/d6525f61e9d4a66a7ac955f0f32fbab5/href</a></iframe><h3>Conclusion</h3><p>This way this ends. I’ve tried to demonstrate here that it is very easy and useful to use reactive_forms to create complex forms in our applications. The advantages of its use that we could see with this example are:</p><ul><li>Less code</li><li>Easy validation</li><li>Some validations are pre-defined in the library</li><li>If you put a print on the Flutter form build method you will see that the view is repainted every time user enters a character on a TextFormField. On the other hand in the reactive form, this doesn’t happen in any widget.</li><li>Also profiling you can see that the reactive version is more optimal than the native one</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*bgi3uCuj0NwbNoeYTw9BkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*LPFmvqegKGXgnRUEG2xcXQ.png" /></figure><p>Also, other advantages of using <em>reactive_forms</em> are:</p><ul><li>A high amount of Reactive Widgets that can be used (<a href="https://pub.dev/packages/reactive_forms#supported-reactive-form-field-widgets">see here</a>)</li><li>Code generator for generating (<a href="https://pub.dev/packages/reactive_forms_generator">read more</a>)</li><li>Imagine you have a field like a phone number and a person can have more than one so you need to repeat the same field several times and store the data on an array. Well with reactive forms this is a piece of cake 🍰 if you use FormArray.</li><li>Imagine you have a form divided into several views 🤯 (like an onboarding carousel) and you need to submit the data at the end. With reactive form is also very easy to do this.</li></ul><p>I won’t say more 🤗. Just encourage you to read the docs and give it a chance.</p><p>You can <a href="https://github.com/Ch4rl3B/easy_reactive_forms"><strong>FIND THE CODE HERE</strong></a><strong>.</strong></p><p>Also if you found this helpful please give me a clap 👏. This is my first post so any feedback positive or negative that you can give me will be very well appreciated.</p><p>Until the next one: keep improving! The limit is your imagination!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b707c4236cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>