<?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 christiannitas on Medium]]></title>
        <description><![CDATA[Stories by christiannitas on Medium]]></description>
        <link>https://medium.com/@christiannitas?source=rss-b3da5aae4241------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bep0z-I2WWuWTTGJEoXE9w.jpeg</url>
            <title>Stories by christiannitas on Medium</title>
            <link>https://medium.com/@christiannitas?source=rss-b3da5aae4241------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:59:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christiannitas/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[Why does having a software architecture matter? (not only for the developers)]]></title>
            <link>https://blog.stackademic.com/why-does-having-a-software-architecture-matter-not-only-for-the-developers-fe1f0edac02b?source=rss-b3da5aae4241------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe1f0edac02b</guid>
            <category><![CDATA[team-management]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[christiannitas]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 08:33:00 GMT</pubDate>
            <atom:updated>2024-03-15T01:02:15.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kIPlVYC-763MkFG" /><figcaption>Photo by <a href="https://unsplash.com/@louisemink?utm_source=medium&amp;utm_medium=referral">Louise Viallesoubranne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The other day I was talking to my senior software engineer friend who works for a startup. He was expressing his grievances on how he was pulled aside by his CEO that day and was told that he was not happy with his performance as a senior software developer. When asked why, the CEO showed him an app that listed all his code contributions to the project.</p><p>The report did not look too bad, but then he showed him the report of one of their junior developers and the statistics showed amazing productivity compared to his own.</p><p>Of course, I pointed out that such a simple, one-sided view of something so complex as worker productivity did not take into account the other responsibilities of a senior developer, like supporting and guiding the members of his team to produce higher-quality code. But then a thought popped into my mind and I asked him:</p><blockquote>“Does your team use any project architecture?”</blockquote><blockquote>“No.”</blockquote><h4>“It just slows you down”</h4><p>My first job was at a young software development agency. We did not have a big team and we still had that startup mindset of “move fast, ship product”.</p><p>Over time, this became a nuisance for me and my fellow developers, as our projects grew in complexity, the codebase became more and more unmanageable, and we never really had time to go and rewrite stuff.</p><p>In my next workplace, I was introduced to my new project and was told that I had to get up to speed on Clean Architecture in Flutter.</p><p>At first, I resented my days. I would find myself writing 10 classes to take some data from the server and show it to the users in a simple use case. Compared to my productivity at my previous job, I felt I was standing still, and all of this was too overcomplicated.</p><p>Now, I’ve come to appreciate the wisdom of having a rigid set of rules applied when it comes to structuring code and dependencies between your classes, and I noticed that I tended to rewrite less code and, more importantly, I didn’t have to refactor so much code I wrote before when I had to reuse that logic in another task.</p><h4>Messy code is just future wasted hours</h4><p>Why is having an architecture an unnoticeable boost to overall productivity? It’s all about the technical debt.</p><p>Technical debt is the phenomenon where pressed by external factors, developers start cutting corners and focusing only on functionality and ignoring how their logic will integrate into the greater product and how their code can and will change over time.</p><p>Most younger companies and teams will take on a lot of technical debt, in the hopes that their product will become successful, so they will eventually come back and reimplement things “properly” by having more funds to refactor and focus on architecture.</p><p>However, from my experience and the experience of my colleagues, the moment of repaying the technical debt rarely comes, and most projects will just build on top of a shaky base product, due to reasons like staying competitive with releases, reinvesting the success into scaling their businesses, taking newer, more exciting projects on board, etc…</p><p>In this context, one of the best corners to cut is to ditch that <em>“silly architecture stuff”</em>, because the product works without it too.</p><blockquote>“So stop worrying, developer! Keep commits up!”</blockquote><p>But we do worry. When working on messy code, we have to use more focus to understand what is happening, and then we have to use up more time to be able to fix the bugs and implement the features, not even mention the utter lack of code reuse that happens when you don’t structure your codebase! That’s company time.</p><h4>Only when playing by the same rules, can we measure productivity the right way</h4><p>Coming back to the original anecdote, what was happening was easily explainable by the lack of architecture. In a team without code standards, any solution goes. But no solutions are created equal.</p><p>A junior developer can pump out a lot of code that is hard to integrate and next to impossible to reuse, and that will show up as productivity, when measuring the number of commits, however, a senior developer will have a harder time keeping up to those standards when he will look at the code and instinctively realize that cutting corners will just generate more work for himself later down the line, so will take the time to implement things the right way.</p><p>What architecture does is even the playing field, when applied across the team. Now everyone works a bit slower. But when you look at the quality of the code introduced in the project, you can more easily measure the true value of productivity by looking at the commits.</p><p>Creating a framework for how a feature must be implemented, will highlight more justly the difference between the expertise of a senior developer and a junior developer, and will boost productivity in the long term.</p><h4>Why is this important?</h4><p>As a product owner, it is important to have a clear view of the health of the project, so you can make accurate decisions. Technical debt is the invisible enemy that sabotages your ability to make business-aware decisions.</p><p>When you only look at the amount of code being introduced, i.e. the amount of product produced, you may be tricked into a false sense of productivity, or you might be misled into believing that the people who improve the quality of your project are a burden on your business, especially when experienced developers are so rare (and so expensive!).</p><p>Imagine trying to balance your finances, while someone keeps secretly borrowing money with your credit card. You believe you’re doing everything great and saving money but, at the end of the month, you realize you can’t pay the rent.</p><h4>What should you take away?</h4><p>Sometimes, doing things by the book is slower. But it is proven by time and experience that will yield better results in the long run.</p><p>That doesn’t mean you should go to the other extreme and over-engineer your architecture to maximize code reuse and structure. That has the opposite effect and unfortunately can be another trap that very talented and intelligent developers can fall into.</p><p>But a good standard must be set for the team when it comes to code quality. Having a strong and time-tested project architecture can serve as that standard.</p><p>If you reached all the way down here, might as well leave a 👏 and if you think my content is interesting and of help to you, follow me for more!</p><p>Cheers!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe1f0edac02b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-does-having-a-software-architecture-matter-not-only-for-the-developers-fe1f0edac02b">Why does having a software architecture matter? (not only for the developers)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error handling in Flutter, two approaches inspired by Rust and Go]]></title>
            <link>https://blog.stackademic.com/error-handling-in-flutter-two-approaches-inspired-by-rust-and-go-2b39df6c6abb?source=rss-b3da5aae4241------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b39df6c6abb</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[christiannitas]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 06:01:39 GMT</pubDate>
            <atom:updated>2023-11-13T00:36:37.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0B0v12fLDwWwROjKr57dPg.png" /></figure><p>Let us start with a simple truth:</p><blockquote>“Errors will happen. They need to be handled!”</blockquote><p>There are plenty of ways our apps can run into errors. They can be predictable or unpredictable ways. They can be justified failures or unexpected errors and for the sake of the stability of our application, we need to handle them all.</p><p>For most apps, that handling is done through try-catches (the traditional approach), and the user is shown some kind of screen or pop-up element that indicates that something went wrong.</p><p>However, for larger apps, surrounding all your logic in try-catch blocks can lead to bloating and complexity.</p><p>The main idea of error handling is to be able to easily pass errors through the different layers of your app architecture and in the event of a failure run some special logic to show that to your user.</p><h3>Pattern Matching: The Rust Approach</h3><p>Rust is a great system programming language, and it gives its users a powerful approach to error handling. In Rust, functions that can throw an error will return an object of type result, which is an enum of two values, Ok or Err. This approach is inspired by functional programming, the Result object being in fact an Either monad.</p><pre>enum Result&lt;T, E&gt; {<br>    Ok(T),<br>    Err(E),<br>}<br><br>fn main() {<br>    let greeting_file_result = File::open(&quot;hello.txt&quot;);<br><br>    let greeting_file = match greeting_file_result {<br>        Ok(file) =&gt; file,<br>        Err(error) =&gt; panic!(&quot;Problem opening the file: {:?}&quot;, error),<br>    };<br>}</pre><p>You can see that after we run the function, we can match the result of the returned type to the possible files and then act according to the result. In this case, enum acts like a union type which can either have the value of ok or error.</p><p>In Dart, enums behave differently, so to achieve such behavior we need to declare our own special class to implement this logic:</p><pre>class Result&lt;T,E&gt;{<br>  T? ok;<br>  E? err;<br>  <br>  Result.ok(this.ok);<br>  Result.err(this.err);<br>  <br>  B match&lt;B&gt;(B Function(E) left, B Function(T) right) {<br>    if(err != null){<br>      return left(err!);<br>    }<br>    else{<br>      return right(ok!);<br>    }<br>  }<br>}<br><br>Result&lt;int ,Exception&gt; riskyManeuver(){<br>//   return Result.ok(0);<br>  return Result.err(Exception(&#39;baaah!&#39;));<br>}<br><br>void main() {<br>  final result = riskyManeuver();<br>  <br>  return result.match(<br>    (err) =&gt; print(&#39;Encountered an error: ${err.toString()}&#39;),<br>    (ok) =&gt; print(&#39;Risky maneuver succeeded with $ok&#39;),<br>  );<br>}</pre><blockquote>You can run this code on <a href="https://dartpad.dev/?id=f0354c6894e515287dc8d2080fbb8bdf">DartPad</a>.</blockquote><p>You can see that we declare a class called Result which is very similar to the rust enum. We create two constructors and a match function which takes two functions and will run the correct one depending on the value contained in the result. The match function will also combine the two values into one of type B.</p><p>For example, if we try to fetch a list of posts from the server and we encounter an error, we can perform a match on the result, and in the error case, we can return an empty list.</p><p>This particular class, and many others that implement concepts from functional programming can be imported from the Dartz package available on <a href="https://pub.dev/packages/dartz">pub.dev</a>.</p><p>In Dartz, this result type is called Either, and the match function is called fold, but otherwise, the idea is the same.</p><p>This approach is very clean and reliable, however, we will quickly run into an issue if we, for example, want to make multiple consecutive calls to the server. Let us take the example below:</p><pre>int getTheThings()  {<br>  final result1 = getThing1();<br>  return result1.match(<br>    (err) =&gt; -1,<br>    (ok) {<br>      final result2 = getThing2(ok);<br>      //do some stuff.<br>      return result2.match(<br>        (err) =&gt; -1,<br>        (ok2) {<br>          //do some stuff.<br>          final result3 = getThing3(ok, ok2);<br>          return result3.match(<br>            (err) =&gt; -1,<br>            (ok3) =&gt; ok3,<br>          );<br>        }<br>      );<br>    }<br>  );<br>}</pre><p>You can see that by following this approach if we want to chain multiple function calls that depend on one another, we will arrive in the lovely place called <em>callback hell</em>.</p><p>This is a side effect of trying to use functional programming concepts in imperative-style languages. Sometimes you may have some friction. The previously mentioned package can help alleviate a bit of pain by using monads (see <em>Task</em> and <em>bind()</em> in Dartz), but then the code becomes a bit too complex and you will need to learn some very hard-to-learn concepts in order to write it in functional style.</p><h3>Returning records: The Go approach</h3><p>Go is also a very efficient compiled programming language. It prides itself on speed and simplicity, having only 25 keywords. It uses an error handling style of having a function return two values, the result and the error:</p><pre>f, err := os.Open(&quot;hello.txt&quot;)<br>if err != nil {<br>    log.Fatal(err)<br>}<br>// do something with the open *File f</pre><p>Returning multiple values from a function was not possible in Dart before the introduction of Record types (I do not take into consideration creating your custom Result class). But ever since their introduction, we can now return pairs of values seamlessly from our functions, by declaring them like so:</p><pre>(int?, Exception?) riskyManouver(){<br>//   return (0, null);<br>  return (null, Exception(&#39;Baaah!&#39;));<br>}<br><br>void main(){<br>  final (ok, err) = riskyManouver();<br>  <br>  if(err != null){<br>    return print(&#39;Oh no!! We got an ${err.toString()}&#39;);<br>  }<br>  print(&#39;Risky maneuver succeeded with $ok&#39;);<br>}</pre><p>However, the function declaration and the return statement now look quite bloated, as we need to follow the order of values in the record. However, we can fix that by declaring a custom type and two factory functions like the following:</p><pre>typedef Result&lt;T,E&gt; = (T?, E?);<br><br>Result&lt;T,E&gt; ok&lt;T,E&gt;(T value) =&gt; (value, null);<br><br>Result&lt;T,E&gt; error&lt;T,E&gt;(E err) =&gt; (null, err);<br><br>Result&lt;int,Exception&gt; riskyManouver(){<br>  return ok(0);<br>//   return error(Exception(&#39;Baaah!&#39;));<br>}<br><br>void main(){<br>  final (ok, err) = riskyManouver();<br>  <br>  if(err != null){<br>    return print(&#39;Oh no!! We got an ${err.toString()}&#39;);<br>  }<br>  print(&#39;Risky maneuver succeeded with $ok&#39;);<br>}</pre><blockquote>You can run this code on <a href="https://dartpad.dev/?id=ed6aae2ab01be5922694471bbfcf4ec1">DartPad</a>.</blockquote><p>This approach is quite simple, and errors are handled and returned without involving multiple nested blocks, as we can simply check to see if the error is null and then move on with our logic.</p><h3>Strengths and weaknesses</h3><p>Which approach you want to choose depends on the type of logic that you want your app to focus on. If you want to have a business logic method to fail if any of its sub-methods fail, then the GO approach is more desirable. However, if you want your business logic to continue in the event of a failure in the chain of methods, then maybe the Rust style can be more effective, as you can match the result of the operation and have a default value returned in the case of error.</p><pre><br>final result1 = doThing1();<br>final partial = result1.match(<br>  (error) =&gt; [],<br>  (ok) =&gt; ok,<br>);<br><br>final result2 = doThing2(partial);<br>...</pre><p>Where, in the case of the GO approach, you would have to write something like this, which would be more bloated:</p><pre><br>final (result, error)= doThing1();<br>late var partial;<br>if(error != null){<br>  partial = [];<br>}else {<br>  partial = result;<br>}<br>final result2 = doThing2(partial);<br>...</pre><p>However, we could write the above code in a better style, using Dart’s brand new pattern matching:</p><pre>final (result,error) = doThing1();<br>final partial = switch(error){<br>  null =&gt; result,<br>  _ =&gt; [],<br>};<br>final result2 = doThing2(partial);</pre><p>In my experience, however, these cases where you have to build partial solutions are infrequent, and usually, when a failure happens, the rest of the process cannot go on.</p><p>I believe the choice comes down to personal preference and the individual coding style. I hope that this article has at least given you some ideas on how you can handle and pass errors around in a straightforward and clear way.</p><p>If you reached all the way down here, might as well leave a 👏 and if you think my content will help you, follow me for more! Cheers!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b39df6c6abb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/error-handling-in-flutter-two-approaches-inspired-by-rust-and-go-2b39df6c6abb">Error handling in Flutter, two approaches inspired by Rust and Go</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speedrun your MVP with Flutter and Firebase UI]]></title>
            <link>https://medium.com/firebase-developers/speedrun-your-flutter-mvp-with-firebase-ui-f4927e1ab502?source=rss-b3da5aae4241------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4927e1ab502</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[christiannitas]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 20:00:42 GMT</pubDate>
            <atom:updated>2023-08-17T09:15:23.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Jrh7Bbmuix5nhoL_tyt0w.jpeg" /><figcaption>Dash and Firebase</figcaption></figure><p>If you are like me, you are always on the lookout for great ideas for a cool side project. Whenever I cook up a new idea that may have potential, I always go for Flutter + Firebase for the implementation because they work amazingly together.</p><p>However, whenever I start these projects, I get hit with a wall of tasks that I have to implement before actually implementing the business logic I think about. Most apps use some form of authentication, file uploads, pagination, or register screens, and without implementing them, you cannot see your MVP (Minimum Viable Product) realized.</p><p>That’s where Firebase UI for Flutter comes in, offering all developers seamless integration with the most popular services offered by Firebase and handling all the boilerplate for you so that you can get back to the code that really matters.</p><p>We are going to look at a number of widgets from the Firebase UI set of packages with which you can speedrun your MVP. In this article, we will implement a chat app on MacOS using these tools. You can find the full code on my GitHub:</p><p><a href="https://github.com/aniteicristi/firebase_widgets_demo_flutter_meetup">GitHub - aniteicristi/firebase_widgets_demo_flutter_meetup: The code written for and during the Bucharest Flutter Meetup of July 2023 as part of a presentation on Flutter Firebase Widgets.</a></p><h3>Firebase Auth UI</h3><p><a href="https://pub.dev/packages/firebase_ui_auth">firebase_ui_auth | Flutter Package</a></p><p>Firebase already provides quick and easy-to-use solutions for authentication, but when it comes to authentication UI, it is up to you to implement all the necessary logic a user expects from any modern apps, like an auth screen, integration with 3rd party auth providers, register capabilities and even a profile screen for your user to see its details.</p><p>Firebase UI offers all of these functionalities as a pre-packaged set of widgets that can handle authentication with most providers, a register screen, and a profile screen. To use the sign-in screen, you can simply return the SignInScreen widget in your build method:</p><pre>class LoginPage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final providers = [EmailAuthProvider()];<br><br>    return SignInScreen(<br>      providers: providers,<br>      actions: [<br>        AuthStateChangeAction&lt;SignedIn&gt;((context, state) {<br>          Navigator.pushReplacementNamed(context, &#39;/chat&#39;);<br>        }),<br>      ],<br>    );<br>  }<br>}</pre><p>The widget can be configured with multiple authentication providers, like email, Google, Apple, Facebook, and many others. When the user enters its credentials and logs in, a new auth state is generated and the widget will look in the actions field to see if any objects match the new state generated. If so, then the provided callback is run. This screen also doubles as a register screen so your users can sign up on your app. In this example, we redirect the user to the chat route on successful login.</p><p>You can listen to multiple events including:</p><ul><li>AuthFailed — when authentication fails, you can execute custom behaviors.</li><li>UserCreated — called when a user registers and is created in FirebaseAuth.</li><li>SignedIn — called on successful login.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*1BN0file3o_ehRcK4agSLg.png" /><figcaption>Sign-In Screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*YOHrKQe0bKS0efmy7w3m9g.png" /><figcaption>Register Screen</figcaption></figure><p>However, you may soon find that these screens do not fit your overall app style. Even though these widgets do not expose parameters for theming, we can wrap them with a Theme widget where we can override the default themes to match our overall style language:</p><pre>class LoginPage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final providers = [EmailAuthProvider()];<br><br>    return Theme(<br>      data: Theme.of(context).copyWith(<br>        inputDecorationTheme: const InputDecorationTheme(<br>          border: OutlineInputBorder(),<br>        )<br>      ),<br>      child: SignInScreen(<br>        providers: providers,<br>        actions: [<br>          AuthStateChangeAction&lt;SignedIn&gt;((context, state) {<br>            Navigator.pushReplacementNamed(context, &#39;/chat&#39;);<br>          }),<br>        ],<br>      )<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*c1IfsxYWd0lVxW7iB5bKMg.png" /><figcaption>Customized Sign-In Screen</figcaption></figure><h3>Firebase Firestore UI</h3><p><a href="https://pub.dev/packages/firebase_ui_firestore">firebase_ui_firestore | Flutter Package</a></p><p>Good. The user is now logged in to our application. Now what? Well, in comes the most versatile widget out of all of the ones presented here.</p><p>When you think of it, most data on mobile is displayed as a list of items the user can interact with. If you use Firestore, this list comes from a query performed on a collection. When developing your app, you must write the logic of getting your documents from Firebase and display them on the screen all by yourself, but the FirestoreListView widget will make this process nonexistent.</p><p>It works by taking a query on your collections and then mapping each document to a widget using a builder function provided by us:</p><pre><br>class ChatPage extends StatefulWidget {<br>  const ChatPage({super.key});<br><br>  @override<br>  State&lt;ChatPage&gt; createState() =&gt; _ChatPageState();<br>}<br><br>class _ChatPageState extends State&lt;ChatPage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    final query = FirebaseFirestore.instance<br>        .collection(&#39;chat&#39;)<br>        .orderBy(&#39;createdAt&#39;, descending: true);<br><br>    return Scaffold(<br>      body: Column(<br>        children: [<br>          Expanded(<br>            child: FirestoreListView(<br>              reverse: true,<br>              query: query,<br>              itemBuilder: (context, item) =&gt; MessageWidget(item.data()),<br>            ),<br>          ),<br>          SendMessageFooter(),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Here we wrote a page that will display chat messages from a collection. You can see how we simply create our query and then pass it to our list view, as well as a function that will return a message widget.</p><p>If we want however to write this properly, we would like to use a converter in order to transform our Firebase documents to our local model of a Message. To do this, we write two functions that convert our Message model to and from snapshots.</p><pre>class Message {<br>  String? id;<br>  String name;<br>  String text;<br>  DateTime? createdAt;<br>  String? senderId;<br><br>  Message({<br>    required this.text,<br>    this.id,<br>    name,<br>    this.senderId,<br>    this.createdAt,<br>  }) : name = name ?? FirebaseAuth.instance.currentUser!.displayName;<br><br>  factory Message.fromSnapshot(DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; snap) =&gt;<br>      Message(<br>        id: snap.id,<br>        name: snap[&quot;name&quot;],<br>        text: snap[&quot;text&quot;],<br>        createdAt: (snap[&#39;createdAt&#39;] as Timestamp?)?.toDate(),<br>        senderId: snap[&#39;senderId&#39;],<br>      );<br><br>  Map&lt;String, dynamic&gt; toJson() =&gt; {<br>        if (id != null) &#39;id&#39;: id,<br>        &#39;name&#39;: name,<br>        &#39;text&#39;: text,<br>        &#39;createdAt&#39;: createdAt ?? FieldValue.serverTimestamp(),<br>        &#39;senderId&#39;: senderId ?? FirebaseAuth.instance.currentUser!.uid,<br>      };<br>}</pre><p>We will call these functions from our query and then we will pass our model to the ListView as a type argument for the widget to infer the actual type of objects in the item builder.</p><pre>class _ChatPageState extends State&lt;ChatPage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    final query = FirebaseFirestore.instance<br>        .collection(&#39;chat&#39;)<br>        .orderBy(&#39;createdAt&#39;, descending: true)<br>        .withConverter&lt;Message&gt;(<br>          fromFirestore: (json, _) =&gt; Message.fromSnapshot(json),<br>          toFirestore: (obj, _) =&gt; obj.toJson(),<br>        );<br>    return Scaffold(<br>      body: Column(<br>        children: [<br>          Expanded(<br>            child: FirestoreListView&lt;Message&gt;(<br>              reverse: true,<br>              query: query,<br>              itemBuilder: (context, item) =&gt; MessageWidget(item.data()),<br>            ),<br>          ),<br>          SendMessageFooter(),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>What is excellent about this widget is that it comes with reactivity built in. Whenever a user will send a message to the collection, all other users will receive it, thus keeping the widget up to date with the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*F_XpKbyhPQyGy5wSzBGZSQ.gif" /></figure><p>The list also comes with a default page size and a default loading indicator, which can both be modified to fit the theme of the application, so that’s two problems to not worry about anymore when using this widget!</p><h3>Firebase Storage UI</h3><p><a href="https://pub.dev/packages/firebase_ui_storage">firebase_ui_storage | Flutter Package</a></p><p>At the time of writing this, the UI library for Firebase storage is still in development, but even now in this early stage, it offers a few functionalities that are great for building apps. One of these functionalities is the upload button which is a widget that will handle the selection and uploading of files from your local device to your Firebase storage buckets.</p><pre>UploadButton(<br>  onError: (_, __) {},<br>  onUploadComplete: (ref) async {<br>    final download = await ref.getDownloadURL();<br>    final msg = Message(text: download);<br>    FirebaseFirestore.instance.collection(&#39;chat&#39;).add(<br>      msg.toJson(),<br>    );<br>}),</pre><p>You can use it as any other button in your Flutter app, however, when pressed it will open a file picker and will allow you to upload that file to Firebase storage. If any error happens, the onError callback is called, and once it successfully uploaded the file, it will call the onUploadComplete call back which will provide us with the reference to that file. In the above example, we get the download URL for the file and then create a new message entity in our collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*RkXEWIICIwz2TBTbpRTB7A.gif" /></figure><p>If you want to upload to a specific folder in your storage bucket, you can wrap the button in a FirebaseUIStorageConfigOverride widget which takes a config object of type FirebaseUIStorageConfiguration. Here you can change the uploadRoot property to suit your requirements.</p><pre>FirebaseUIStorageConfigOverride(<br>  config: FirebaseUIStorageConfiguration(<br>    uploadRoot: FirebaseStorage.instance.ref(&#39;photos/&#39;),<br>  ),<br>  child: UploadButton(<br>      onError: (_, __) {},<br>      onUploadComplete: (ref) async {<br>        final down = await ref.getDownloadURL();<br>        final msg = Message(text: down);<br>        FirebaseFirestore.instance.collection(&#39;chat&#39;).add(<br>              msg.toJson(),<br>            );<br>      }),<br>),</pre><h3>And many more…</h3><p>These few widgets offer you incredible speed and convenience when developing your next million-dollar startup, but the Firebase UI toolkit will only continue to grow. Right now you have many more widgets like the Firestore collection builder or storage list view so that you may use them in building your apps and getting them to your users as fast as possible.</p><p>This article was written as part of my presentation at the Bucharest Flutter Meetup on the same topic. I want to thank the community organizers and sponsors for making it possible for me to talk about what I am passionate about in real person, not only here on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4927e1ab502" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/speedrun-your-flutter-mvp-with-firebase-ui-f4927e1ab502">Speedrun your MVP with Flutter and Firebase UI</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dartx and the Power of Extensions— How it’s Made]]></title>
            <link>https://christiannitas.medium.com/dartx-and-the-power-of-extensions-how-its-made-b6e0c34e2832?source=rss-b3da5aae4241------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e0c34e2832</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[christiannitas]]></dc:creator>
            <pubDate>Mon, 15 May 2023 09:32:28 GMT</pubDate>
            <atom:updated>2023-05-15T09:32:28.223Z</atom:updated>
            <content:encoded><![CDATA[<p>Dartx is one of my must-have dart packages on pub.dev which through the powerful use of extensions simplifies the way we write common logic for list processing, string handling, and date-time manipulations.</p><p>You can read more about it in one of my previous articles on the topic where I showcase some of the most interesting things you can do with it.</p><p><a href="https://christiannitas.medium.com/dartx-the-powerful-dart-package-that-will-simplify-your-day-to-day-developer-life-e009defd12b">Dartx: The powerful dart package that will simplify your day-to-day developer life.</a></p><p>In this article, however, I want to dive deeper into how this package is implemented and explore the simple dart concepts behind its seemingly complex extension methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j7f_J3WXmNL6yLK9" /><figcaption>Photo by <a href="https://unsplash.com/fr/@arifriyanto?utm_source=medium&amp;utm_medium=referral">Arif Riyanto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Extensions in Dart</h3><p>Ever since Dart 2.7, extensions have been a game changer for writing Dart &amp; Flutter code. In short, with extensions, you can add extra functionality to types and classes which you do not control. This functionality is not only limited to implementing functions. You can also add getters and setters and even overload operators on said types.</p><p>This is useful when you want to extend types and classes from the standard dart library to have extra functionality. One of my favorite examples is the time library on pub.dev, which overloads arithmetic operators to make operations with time values a breeze. You can check it out here:</p><p><a href="https://pub.dev/packages/time">time | Dart Package</a></p><p>This is also what constitutes the core functionality of the Dartx package, which adds extra logic to standard library types, like iterators, strings, and integers.</p><p>Let’s look at the most basic example of a dart extension. We will create an extension on the String type called <strong><em>toIntOrNull() </em></strong>which when called will try to parse its contents and return either an integer or null.</p><pre>extension ToIntOrNull on String {<br>  int? toIntOrNull() {<br>    return int.tryParse(this);<br>  }<br>}</pre><p>To explain the previous code snippet, we declare an extension and we give it a name. We then specify the type we are trying to extend using the <strong>on</strong> keyword. Afterward, we can begin writing our functions, operator overloads, getters, and setters. Notice that when writing the function we do not need to pass any parameter, as this function will be called on a String object. In the scope of the extension, <strong>this</strong> keyword refers to the object on which this function was called, and will be always of the type defined in the extension declaration, in this case, <em>String</em>.</p><p>Once this extension is defined, we can use it on any string object or string literal in our code, by importing the file it is declared in:</p><pre>void main() {<br>  print(&quot;203&quot;.toIntOrNull()); // 203<br>  print(&quot;not a number&quot;.toIntOrNull()); // null<br>}</pre><h3>Dartx Extensions up close</h3><p>As explained in my previous article, Dartx is a powerful package on pub.dev that exposes a number of extensions on types such as Lists, Iterables, Strings, integers, floats, and other base types from the standard dart library.</p><p>In the following section, we will look at some of the more interesting extensions and how they are implemented. We will only look at some examples, but you can feel free to take the information in this article and go look for yourself in the source code of Dartx available on GitHub. I really recommend installing it and trying it out for yourself. It’s worth it!</p><p><a href="https://pub.dev/packages/dartx">dartx | Dart Package</a></p><h4>Extensions on String</h4><p>One of the many extensions on strings was implemented in the very example I have given in the previous sections, however, there are many more available. Let us say you want to create an extension to return the reverse of the string to, for example, check if the string is a palindrome. We can do that by creating an extension and using the StringBuffer to build the new string.</p><pre>extension ReversedString on String {<br>  String get reversed {<br>    StringBuffer buffer = StringBuffer();<br><br>    for (int i = length - 1; i &gt;= 0; i--) {<br>      buffer.write(this[i]);<br>    }<br><br>    return buffer.toString();<br>  }<br>}</pre><p>In this example, I have created a ReversedString extension on String which implements the getter reversed just like in Dartx. However, their implementation uses an iterator to go through the contents of the string. Here I just use plain indexing on the string object by using <strong><em>this[i]. </em></strong>Also, notice how calling the <strong><em>length</em></strong> getter is used like a class member in this function. That is because all extension methods have access to the members of the extended class.</p><p>Now we can just call these methods as so:</p><pre>print(&quot;stressed&quot;.reversed); // desserts 😋</pre><p>And this is how you implement this method. However, you don’t have to, because you can just use Dartx and its many extension methods to do this!</p><h4>Extensions on Lists &amp; Iterables</h4><p>When creating extensions on lists and iterables, but especially on the latter, it is usually a good practice to use lazily evaluated generator functions.</p><p>Generators are special functions in Dart that return an iterable. They are declared using the <strong><em>sync*</em></strong> keyword (similar to the way you would declare an asynchronous function or a stream generator, which is quite similar to normal generators). But what is so special about them?</p><p>Well, when using generators, instead of ending the execution and returning the value using the return keyword, you output a value using the <strong><em>yield </em></strong>keyword. But what’s the difference? Well, up to right now not a lot. However, the difference comes when you want to iterate over it. Because when you will try to get the next element, the execution of the function will begin right after the yield statement. Let’s take an example:</p><pre>Iterable&lt;int&gt; createIterable(int max) sync* {<br>  for (int i = 0; i &lt; max; i++) {<br>    yield i;<br>    print(&quot;yielded $i&quot;);<br>  }<br>}<br><br>void main() {<br>  final iterable = createIterable(10);<br><br>  for (final i in iterable) {<br>    print(i);<br>  }<br>}</pre><p>In this snippet, we create a generator function that will give us an iterable of ints from 0 to <em>max.</em> If we try to go over this iterable using a <strong><em>for</em></strong>, we will print out values from 0 to <em>max</em>. If you run this, you will notice that the <strong><em>“yielded $i”</em></strong> message will always come after the <strong><em>print(i)</em></strong> in the main loop. That is because once you yield a value if you request the next value (in this case requesting is done by the for in the background) the generator will begin execution right after the last yield. We can also convert this iterable to a list.</p><pre>final iterable = createIterable(10);<br><br>print(List.from(iterable)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre><p>In this case, the list constructor will repeatedly call the generator function and “consume” the values generated by appending them to the list.</p><p>Iterables are a difficult concept to wrap your head around, but once you do you can use them to create efficient generators and list processors. One of the big advantages of iterables is that they are lazily generated. If let’s say you only need half of the values, you can just not request the next ones and they will not get computed. This is not useful in our example, but when the generation of these numbers is costly, then it would be helpful to not perform costly work. You can watch this amazing video from the Flutter official youtube channel to get a better grasp on generator functions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTF-TBsgIErY%3Flist%3DPLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTF-TBsgIErY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTF-TBsgIErY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/80785ee7f9d3c02c1abd8d9187ac5a0a/href">https://medium.com/media/80785ee7f9d3c02c1abd8d9187ac5a0a/href</a></iframe><p>Now, let’s see how we can use these generator functions to implement the <strong><em>cycle()</em></strong> function from Dartx. The cycle function is called on a list and will generate a new iterable which will cycle over that list indefinitely.</p><pre>extension Cycler&lt;E&gt; on Iterable&lt;E&gt; {<br>  Iterable&lt;E&gt; cycle() sync* {<br>    var it = iterator;<br>    if (!it.moveNext()) return;<br><br>    yield it.current;<br>    while (true) {<br>      while (it.moveNext()) {<br>        yield it.current;<br>      }<br>      it = iterator;<br>    }<br>  }<br>}<br><br>void main() {<br>  final iterable = [1, 2, 3, 4].cycle();<br><br>  for (int i in iterable) {<br>    print(i); // 1 2 3 4 1 2 3 4 1 2 ... forever<br>  }<br>}</pre><p>To implement that function, we will make use of the iterator object of the iterable we extend. <strong><em>iterator</em></strong> is a getter on the iterable which returns an object with two important members. The <strong><em>current </em></strong>member will give you the current value of the iterator, firstly 1. When we call <strong><em>moveNext()</em></strong> the current value of the iterator becomes the next value in the list, 2 in this case, and so on…</p><p>The function is implemented by simply moving with the iterator through the iterable and yielding the values. Once we reach the end of the list (<strong><em>moveNext()</em></strong> returns false) we will reinitialize the <strong><em>it </em></strong>object with the iterator of the iterable and begin again.</p><blockquote><strong>Note: </strong>If we call such a generator in a for loop, we will continuously get values forever, because of the infinite loop in the generator function. However, the generator returns an iterable which again can be iterated through using an iterator, thus we could use the values and then stop at any time we want. Remember, the generator function will run only when we request another value from it. Otherwise, it will not.</blockquote><h4>Extensions on Datetime</h4><p>Using Dartx will automatically import the time.dart package, which is an amazing set of utility functions that simplify working with dates. These extensions overload the operators on Datetime so we may add and subtract durations and get the resulting DateTime objects. This is how they did it:</p><pre>extension AddSub on DateTime {<br>  DateTime operator +(Duration duration) =&gt; add(duration);<br><br>  DateTime operator -(Duration duration) =&gt; subtract(duration);<br>}<br><br>void main() {<br>  DateTime a = DateTime.now();<br><br>  print(a);                      // 2023-05-01 13:30:06<br>  print(a + Duration(hours: 1)); // 2023-05-01 14:30:06<br>}</pre><blockquote>Note how we used the keyword <strong>operator </strong>followed by the operator itself to declare an overload on the operator. The return type is the result of the addition, while the argument is the other operand. (in this case <strong>Duration(hours:1)</strong>)</blockquote><p>You can see that the code is quite simple because Dart already implements functions to safely add/subtract duration to a DateTime, however, by overloading operators in the extension, we create a more straightforward way of adding and subtracting time.</p><p>You could say that it is more unintuitive like this, which is a fair criticism, especially if coming from the Java world. However, as you try to perform more and more complex operations on dates, you begin to see the drawbacks of using functions. The code becomes jumbled and hard to read. While with this, we can take advantage of the mathematical operation evaluation order and, once we know the meaning of the operators, we can tell more quickly what the code is trying to achieve.</p><h3>Conclusion</h3><p>Dartx and Time.dart are two packages that expose a set of extensions that simplify the way we write code and make it more readable. As we have seen, these complex functions were actually implemented using some of the base functionalities of the Dart programming language and anyone can implement them if they need to, however, why do that when you have this amazing package?</p><p><em>🔥 If you enjoyed this article and want to support such a style of deep dives into Flutter &amp; Dart packages and learn more of the things that are going on behind the scenes, please consider following me on Medium and hitting the 👏 button. ‘Tis greatly appreciated. Cheers!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e0c34e2832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dartx: The powerful dart package that will simplify your day-to-day developer life.]]></title>
            <link>https://christiannitas.medium.com/dartx-the-powerful-dart-package-that-will-simplify-your-day-to-day-developer-life-e009defd12b?source=rss-b3da5aae4241------2</link>
            <guid isPermaLink="false">https://medium.com/p/e009defd12b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[christiannitas]]></dc:creator>
            <pubDate>Sat, 06 May 2023 15:15:12 GMT</pubDate>
            <atom:updated>2023-05-06T15:15:12.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dartx: The powerful dart package that will simplify your day-to-day developer life. — Package Showcase.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sgT_EO5p1OdUL_8p" /><figcaption>Photo by <a href="https://unsplash.com/es/@roketpik?utm_source=medium&amp;utm_medium=referral">Artur Shamsutdinov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Dart is a powerful language that supports Object-Oriented patterns through features like inheritance and polymorphism, as well as some functional patterns when it comes to lists. I love it because it is expressive, high level, and gives you a pleasant programming experience, especially when writing flutter code.</p><p>However, if you ever felt like you needed some utility functions to streamline your logic, or perhaps you missed some features from other languages, a cool package worth checking out is Dartx.</p><p>Dartx is a package available on <a href="https://pub.dev/packages/dartx">pub.dev</a>. It comprises a set of extension functions that simplify and solve all the little tasks you do not want to do. In this article, I will showcase a few examples of how I use Dartx in my day-to-day life as a Flutter Developer.</p><p><a href="https://pub.dev/packages/dartx">dartx | Dart Package</a></p><h3>Lists and Iterables</h3><p>When it comes to lists, other languages have some very handy utility functions and features that help to work with them, like Java’s streams. With Dartx, we also have access to a set of useful functions that make working with lists a breeze.</p><h4>All / None</h4><p>The <strong><em>all()</em></strong> function can be called on lists and can be used to check whether all the elements satisfy a given criterion (passed as a function argument). The inverse function is <strong><em>none()</em></strong> which returns true if none of the elements satisfy the condition. It is useful when let’s say we have a list of results that can be null, and we want to check that none of the elements are null before proceeding.</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final list = [1, 2, 3, 4, 5, 6];<br><br>  list.all((x) =&gt; x &gt; 3); // false<br>  list.all((x) =&gt; x &gt; 0); // true<br><br>  list.none((x) =&gt; x == null); // true<br><br>  final listWithNulls = [1, 2, null, 4, 5, 6, null];<br><br>  listWithNulls.none((x) =&gt; x == null); // false<br>}</pre><h4>Slices</h4><p>If you’re a fan of Python’s or Go’s slices on lists and arrays respectively, then you’re going to love this extension function added by Dartx. When you call the <strong><em>slice()</em></strong> method, you can extract sublists from the current list. You can skip the first element, select the first two elements, select the final element (by passing an index of -1), or even the final two or three. The possibilities extend beyond that. And the awesome part about it is that the return type of the slice operation is an Iterable, so you can chain other operations with it, like <strong><em>map()</em></strong> or <strong><em>where()</em></strong> functions that come by default with dart lists.</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final list = [1, 2, 3, 4, 5, 6, 7];<br><br>  list.slice(0, 2); // [1, 2, 3]<br>  list.slice(2); // [3, 4, 5, 6, 7]<br>  list.slice(-1); // [7]<br>  list.slice(-2); // [6, 7]<br>  list.slice(-3, -2); // [5, 6]<br><br>  //chaining multiple operations<br>  list.slice(0, 2).map((e) =&gt; e * e); // [1, 4, 9]<br>}</pre><h4>List operations with index</h4><p>Have you ever encountered a problem where you wanted to map over a list, but you also needed the index of the current element?</p><p>You would have to give up the high-level approach to solving the problem and resort to an old-fashioned for loop. However, Dartx solves this problem by extending a few functions in dart:core to include also the index. These functions are <strong><em>mapIndexed()</em></strong>, <strong><em>whereIndexed(),</em></strong> and <strong><em>forEachIndexed()</em></strong>.</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final list = [1, 2, 3, 4, 5, 6, 7];<br><br>  list.mapIndexed((index, x) =&gt; index * x); // (0, 2, 6, 12, 20, 30, 42)<br><br>  list.whereIndexed((x, index) =&gt; index.isEven); // (1, 3, 5, 7)<br>  //note: we are checking if the index is even, not the number. Index starts from 0<br><br>  list.forEachIndexed((element, index) {<br>    print(&#39;($element, $index)&#39;);<br>  });<br>  // (1, 0)<br>  // (2, 1)<br>  // (3, 2)<br>  // (4, 3)<br>  // (5, 4)<br>  // (6, 5)<br>  // (7, 6)<br>}</pre><blockquote>Notice how I used string interpolation to print the element and its index in the forEachIndexed() function. Also note that as of this version, the index and element are reversed when using the <strong>mapIndexed()</strong> function. This might be fixed in later versions.</blockquote><h4>Zipping lists together.</h4><p>By now you may have noticed that Dartx provides a lot of functional patterns to solve problems. One of these patterns is also the <strong><em>zip()</em></strong><em> </em>function. This function exists in Python as well and provides a powerful way of creating lists of tuples on which further processing can be done.</p><p>As of now, Dart does not have support for tuples, but that will change soon with the apparition of records in the next major version of Dart. Check <a href="https://stevenosse.com/dart-3-in-depth-records">this article</a> out for more info.</p><p>Until then, we have access to the <strong><em>zip()</em></strong> function in Dartx. How it works is that when called on a list with another iterable as an argument and a combination function, it will return the result of the combination function applied for each pair of elements taken from the two lists. Let’s see an example:</p><p>We want to compute the element-wise sum of two lists. We can use zip to do that:</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final list = [1, 2, 3, 4];<br>  final other = [5, 6, 7, 8];<br><br>  list.zip(other, (a, b) =&gt; a + b); // [6, 8, 10, 12]<br>}</pre><p>Or we could do something similar to strings. Let us say you have a list of first names and last names and you want to combine them together into a list of full names. <strong><em>zip()</em></strong> makes that a piece of cake!</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final first = [&quot;Chris&quot;, &quot;Ana&quot;, &quot;Alex&quot;];<br>  final last = [&quot;Nitas&quot;, &quot;Jhonson&quot;, &quot;Fisher&quot;];<br><br>  first.zip(last, (f, l) =&gt; &quot;$f $l&quot;); // (Chris Nitas, Ana Jhonson, Alex Fisher)<br>}</pre><p>And once that’s done, it returns an iterable (notice the round brackets instead of the square ones when printing the value). After getting the values, we can apply more processing, like filtering the data.</p><p>You can see the power of Dartx when it comes to list processing, but it is not everything that the package has to offer. Now we will look at some other features that I use to write clean and concise code.</p><h3>String operations</h3><h4>Verifications</h4><p>Dartx provides some useful extension methods to perform easy verification of the contents of a string. Here are a few examples:</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  //Check if blank<br>  &quot;Ana has apples.&quot;.isBlank; // false<br>  &quot;  \n     &quot;.isBlank; // true<br>  //Check upper case<br>  &quot;HELLO THERE&quot;.isUpperCase; // true<br>  &quot;HELLO THERE&quot;.isLowerCase; // false<br><br>  //Check for non-latin letters<br>  &quot;mămăligă&quot;.isLatin1; // false<br><br>  //Check using regex<br>  &quot;19203019&quot;.matches(RegExp(r&#39;[1-9]+&#39;)); // true<br>}</pre><p>This shows the spirit of Dartx, which is to abstract the low-level operations so that you can focus more on what your code needs to do, rather than how.</p><h4>Converting from strings to other data types</h4><p>Converting from string to other basic data types is implemented very nicely in Dartx. You can convert strings to doubles, ints, or floats just by calling a function on the object you want to decode. From then on, you can chain other logic to your operation. Here are a few examples of what you can do with Dartx:</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() {<br>  final numDouble = &quot;3.23&quot;;<br>  final badDouble = &quot;38.a38&quot;;<br>  final numInt = &quot;32&quot;;<br><br>  numDouble.toDouble(); // 3.23<br>  numDouble.isDouble; // true<br><br>  numDouble.isInt; // false<br>  numInt.isInt; // true<br><br>  badDouble.toDoubleOrNull(); // null<br><br>  numInt.toInt(); // 32<br>}</pre><h4>Easy hashing of passwords</h4><p>Hashing is a powerful tool that has many applications in the software world. One of these uses is hashing passwords in a database so that someone who retrieves the records doesn’t have access to the raw content. Dartx makes that simple by just creating an extension to compute the md5 hash of a string. You can read more about the applications of md5 in <a href="https://infosecscout.com/where-is-md5-used/">this article</a>.</p><pre>String a = &quot;Ana has apples.&quot;;<br>a.md5; // 095441e8b417fe681ea3a0083b865483</pre><h3>Time Utilities</h3><p>Finally, one of my favorite utilities from Dartx is how it simplifies operations with time. Let us say you want to create a duration of 5 minutes. You would have to write something like this:</p><pre>final duration = Duration(minutes: 5);</pre><p>However, using Dartx, you can define durations much more easily:</p><pre>final duration = 5.minutes;</pre><p>Do you see how simple that is? And that returns a valid duration of 5 minutes. Let us say we wanted to create a delay and await it. Traditionally, we would write something like this:</p><pre>import &#39;package:dartx/dartx.dart&#39;;<br><br>void main() async {<br>  await Future.delayed(Duration(minutes: 5));<br>}</pre><p>However, using Dartx we would write that line like this:</p><pre>void main() async {<br>  await 5.minutes.delay;<br>}</pre><p>This accomplishes the same thing, without that extra boilerplate. The code is straightforward and tells you exactly what it does.</p><p>And the best part is that the package exports <a href="https://github.com/jogboms/time.dart">time.dart</a>, which offers some amazing operator overloading for durations. So you could do stuff like this to calculate dates by adding or subtracting durations:</p><pre>DateTime expirationDate = DateTime.now() + 1.month;<br><br>DateTime nextExam = 2.days.fromNow;</pre><p>I do not even have to explain what the code does. You just look at it and figure it out. That is the power of extensions when used right!</p><h3>Conclusions</h3><p>Dartx provides a set of extensions that are so useful and seem so natural that you will be surprised they are not included in the core package. What we have covered here barely touches the surface of what Dartx can do. I encourage you to add it to your project and try it yourself!</p><p>From list processing utilities to time utilities, whenever I start a new Flutter project, this package will always have a special place in my dependencies!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e009defd12b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>