<?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 Sandro Lovnički on Medium]]></title>
        <description><![CDATA[Stories by Sandro Lovnički on Medium]]></description>
        <link>https://medium.com/@slovnicki?source=rss-aa0978f75af8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bt7HKSXdNYPJbBLWAgZ7AQ.jpeg</url>
            <title>Stories by Sandro Lovnički on Medium</title>
            <link>https://medium.com/@slovnicki?source=rss-aa0978f75af8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:01:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slovnicki/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[Blocs with Reactive Repository]]></title>
            <link>https://medium.com/flutter-community/blocs-with-reactive-repository-5fd440d3b1dc?source=rss-aa0978f75af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd440d3b1dc</guid>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sandro Lovnički]]></dc:creator>
            <pubDate>Thu, 19 May 2022 12:23:06 GMT</pubDate>
            <atom:updated>2025-01-17T17:09:23.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Inspired by the updated section on “(Avoiding) Bloc-to-Bloc communication” at <a href="https://bloclibrary.dev/architecture/#bloc-to-bloc-communication">https://bloclibrary.dev/architecture/#bloc-to-bloc-communication</a>, we’ll explore a use case where “reactive repository” solution is very elegant, if not the only one that covers all cases.</p><p>You can find the entire application code at <a href="https://github.com/slovnicki/reactive_repositories">https://github.com/slovnicki/reactive_repositories</a></p><p>Here’s a diagram of what we want to accomplish, so let’s start with <strong>why</strong> do we want to accomplish that :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*HstK_rqZbkXag-ARqrKmZA.png" /></figure><h3>The problem</h3><p>Consider an application where we have a screen with a list of items that are sorted based on some property a user can toggle, but the toggling is done inside another route (a screen, dialog or bottom sheet) and should rebuild the route below to reflect the updated item and ordering of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*8FkezolcdpBqmDIzSQ_qBA.png" /></figure><h4>Architecture</h4><ul><li>2 main Widgets: ListScreen and DetailsModal which are shown on separate routes</li><li>2 Cubits: one that rebuilds the ListScreen and one that rebuilds the DetailsModal</li><li>1 Repository which both Cubits can use to fetch and update items</li></ul><h4>Intended behavior</h4><p>When we click on “Toggle favorite” for Burrito, we would like to trigger a rebuild of ListScreen to show the updated list of items where Burrito is appropriately placed further up than it was before, because we sort items by the isFavorite property we’re toggling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GCCdUWw-xaSEQd0y5bp00A.gif" /></figure><h4>Approaches</h4><p>It would seem we need to trigger the ListCubit from successful toggle action on DetailsCubit. The mentioned section on Bloc-to-Bloc communication (<a href="https://bloclibrary.dev/#/architecture?id=bloc-to-bloc-communication">https://bloclibrary.dev/#/architecture?id=bloc-to-bloc-communication</a>) tells us that we should handle this either</p><ul><li>by using BlocListener to listen for success state on DetailsCubit and then triggering ListCubit explicitly</li><li>by having our ListCubit listen to a Stream from ItemsRepository which adds new values to the stream after each successful toggling</li></ul><p>First approach can get a bit tricky when we’re dealing with different routes that don’t share context and if we’re using declarative navigation and/or deep-linking where it’s not straightforward to provide both routes with the same instance of ListCubit (if we don’t want it above entire app).</p><p>We’re now going to explore the second solution — “reactive repository”.</p><h3>The solution</h3><p>Let’s look at the diagram again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*HstK_rqZbkXag-ARqrKmZA.png" /></figure><h4>Cubit</h4><p>The basic idea is for ListCubit, instead of depending on someone explicitly calling loadItems on it, to emit new states (thus rebuilding the ListScreen) whenever the ItemsRepository adds a new list of items to the stream. We can achieve that by having our ListCubit subscribe to the stream.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2fd40f1248b4c0d66c339897999b0c/href">https://medium.com/media/ea2fd40f1248b4c0d66c339897999b0c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IycvmgUIjeipxezmJipEVQ.jpeg" /></figure><h4>Repository</h4><p>In our abstract repository, we’re exposing a Stream called items, the one that the ListCubit is subscribing to in the above snippet.</p><p><em>We’re exposing a broadcast stream because repository doesn’t know how many subscribers will it have and should generally support many.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e23c06a4464cabc9bdee24b397251a/href">https://medium.com/media/b0e23c06a4464cabc9bdee24b397251a/href</a></iframe><p>Now in the implementation (FakeItemsRepository for this example), we are adding new lists of items to the stream on two occasions, but the second one is of more interest to us in this article.</p><ul><li>On initial fetch</li><li><strong>Every time an item is successfully toggled</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fcb5f3055a83ac3bc079e8ae5814d8c/href">https://medium.com/media/5fcb5f3055a83ac3bc079e8ae5814d8c/href</a></iframe><h3>The code</h3><p>You can find the entire application code at <a href="https://github.com/slovnicki/reactive_repositories">https://github.com/slovnicki/reactive_repositories</a>. Feel free to create PRs, issues or contact me on Twitter for any further discussions: <a href="https://twitter.com/slovnicki">https://twitter.com/slovnicki</a></p><p>Follow Flutter Community on Twitter: <a href="https://www.twitter.com/FlutterComm">https://www.twitter.com/FlutterComm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd440d3b1dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/blocs-with-reactive-repository-5fd440d3b1dc">Blocs with Reactive Repository</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beamer v1.0.0 is out! What’s new and how to migrate]]></title>
            <link>https://medium.com/flutter-community/beamer-v1-0-0-is-out-whats-new-and-how-to-migrate-b251b3758e3c?source=rss-aa0978f75af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b251b3758e3c</guid>
            <category><![CDATA[router]]></category>
            <category><![CDATA[navigator]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[package]]></category>
            <dc:creator><![CDATA[Sandro Lovnički]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 03:53:23 GMT</pubDate>
            <atom:updated>2021-12-06T18:52:33.021Z</atom:updated>
            <content:encoded><![CDATA[<p>After being on <a href="https://pub.dev/packages/beamer">pub.dev</a> for almost a year, tested and used by many individuals and companies, the long-awaited <em>v1.0.0</em> is finally released<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7UvDQpsDxAY5hdBLQLkCA.png" /></figure><h3>Table of Contents</h3><ul><li><a href="#386a"><strong>Introduction</strong></a></li><li><a href="#9ec6"><strong>What’s new after v0.14.1</strong></a></li><li><a href="#3c37"><strong>How to migrate</strong></a></li><li><a href="#6234"><strong>Final thoughts</strong></a></li></ul><h3>Introduction</h3><p>Beamer is a routing package for all platforms that lets you navigate through guarded page stacks and URLs using the Router and Navigator’s Pages API, aka “Navigator 2.0”.</p><p>If you are unfamiliar with these navigation concepts, <a href="https://medium.com/flutter/learning-flutters-new-navigation-and-routing-system-7c9068155ade">Learning Flutter’s new navigation and routing system</a> is a great article to start with. The rest of this article assumes familiarity with said concepts and <em>some</em> familiarity with Beamer whose README can be read in the link below.</p><p><a href="https://pub.dev/packages/beamer">beamer | Flutter package</a></p><p>There are 2 main ideas that guided Beamer’s inception:</p><ul><li>Make the use of Router API easier, especially for beginners</li><li>Segregate the responsibility of creating a page stack, for intermediate and advanced usage</li></ul><p>First point is solved by having default implementations for RouterDelegate and RouteInformationParser , i.e. BeamerDelegate and BeamerParser . Both can take various parameters for customization. Having named routes showed to be a desired feature at the very beginning, so there is a RoutesLocationBuilder that can be configured with a familiar routes Map. After the setup, navigation can be done via something like Beamer.of(context).beamToNamed(&#39;/my/page/2&#39;) which made the transition from Navigator.of(context).pushNamed(&#39;/my-page&#39;) very natural for newcomers.</p><p>Second point is accomplished by the concept of a BeamLocation that is responsible for deciding, based on its state, which pages should BeamerDelegate put into Navigator.pages when (re)building it. The idea here is to define a different BeamLocation for a different “area/location/world” inside the app. For example, we can have BooksBeamLocation that will handle all combination of books-related pages in a stack and an ArticlesBeamLocation that will handle all article-related pages in a stack. Benefits of this approach can be seen very soon when having to build an application containing 10+ screens organized in a couple of “contextually different” page stacks.</p><p>When defining your BeamLocation , the state used for it can be either the default BeamState (that holds various route parameters important for decisions on how to build a page stack) or a completely custom state object, even (but not necessary) a ChangeNotifier . When using a custom ChangeNotifier for the state of BeamLocation , one can accomplish pure declarative navigation. Still, even with ChangeNotifier state, one is able to navigate imperatively just the same. Beamer does not prefer one over the other and handles both similarly under the hood. The next goal may be to make the default BeamState be a ChangeNotifier , but that’s a topic for the next article :)</p><p>The flow of what happens after each navigation action can be seen in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*QOY4BnFGo54YqbsHsRqdkg.png" /></figure><h3>What’s new after v0.14.1</h3><p>A complete CHANGELOG can be seen <a href="https://pub.dev/packages/beamer/changelog">here at pub.dev</a>, so we’ll go over the reasons behind each breaking change and some notable mentions.</p><h4>Changes on BeamState</h4><ol><li>It is now mixed with RouteInformationSerializable, a mixin defined in Beamer that every state for BeamLocation must mix with</li><li>pathBlueprintSegments is renamed to pathPatternSegments</li></ol><h4>Changes on BeamerDelegate</h4><ol><li>Some of you may notice, especially if using Beamer.of(context).update directly, that BeamerDelegate also stores its “state”. This was a BeamState called state until now, but that didn’t feel quite right. Now this is a RouteInformation called configuration to be named the same as it’s in RouterDelegate</li><li>All of the beaming parameters such as transitionDelegate, beamBackOnPop and others have been extracted into a BeamParameters object. This is not a breaking change as these parameters stayed the same in beaming functions, but is a change that, together with above change, influenced following changes</li><li>The locationBuilder now takes RouteInformation and BeamParameters instead of BeamState. This is a natural consequence of above changes, but also an improvement because it provides an ability to save BeamParameters into history, something that was not possible before</li><li>beamStateHistory and beamLocationHistory have been replaced with beamingHistory that is a List&lt;BeamLocation&gt; and each BeamLocation has history that is List&lt;HistoryElement&gt; where HistoryElement holds RouteInformation and BeamParameters. That sentence escalated quickly, but now we have a very stable and well-structured beaming history</li><li>listener is renamed to routeListener and a new buildListener is added. This way we can listen both on incoming routes (before build) and at build (where we also have access to pages)</li></ol><h4>Changes on BeamLocation</h4><ol><li>Because of the changes on BeamerDelegate, the constructor now takes optional RouteInformation and BeamParameters</li><li>A type T for state now must mix with RouteInformationSerializable and a generic type for state must be specified when extending the BeamLocation, even when using the default BeamState</li><li>pathBlueprints is renamed to pathPatterns and is a List&lt;Pattern&gt;</li></ol><h4>Changes on SimpleLocationBuilder</h4><ol><li>Renamed to RoutesLocationBuilder. This was due to discussions at <a href="https://github.com/flutter/uxr/wiki/Navigator-2.0-API-Usability-Research">Navigator 2.0 API Usability Research</a></li><li>The values of routes now also receive the Object? data parameter.</li></ol><h4>Changes on BeamPage</h4><ol><li>pageRouteBuilder is replaced with more generic routeBuilder</li><li>We have a const constructor now</li><li>A static routePop is added that can be used instead of default pathSegmentPop for onPopPage</li></ol><h4>Changes on BeamGuard</h4><ol><li>pathBlueprints renamed to pathPatterns</li><li>beamTo and beamToNamed now also receive origin and target which are BeamLocations of where it’s being beamed from and where it’s being beamed to (which was guarded)</li></ol><h4>Additions to examples</h4><ul><li>G<a href="https://github.com/slovnicki/beamer/tree/master/examples/guard_riverpod">uard riverpod example</a></li><li><a href="https://github.com/slovnicki/beamer/tree/master/examples/firebase_core">Firebase core example</a></li><li><a href="https://github.com/slovnicki/beamer/tree/master/examples/firebase_auth">Firebase auth example</a></li><li><a href="https://github.com/slovnicki/beamer/tree/master/examples/change_notifier_custom_state">ChangeNotifier custom state example</a></li></ul><h3>How to migrate</h3><p>Although there have been a lot of changes, migration is pretty straightforward. We’ll go through 2 migrating scenarios; when using the SimpleLocationBuilder and when using a custom BeamLocation.</p><h4>SimpleLocationBuilder</h4><p>As we mentioned above, SimpleLocationBuilder was renamed to RoutesLocationBuilder. That’s 50% of migration done and we only need to add data parameter to the routes, but let’s write some code.</p><p>Previously we had something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f62b369dfb80ae60b8a39d4a3b37f275/href">https://medium.com/media/f62b369dfb80ae60b8a39d4a3b37f275/href</a></iframe><p>After the migration, we should have something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df11db13021a94745f98f3159095a8a2/href">https://medium.com/media/df11db13021a94745f98f3159095a8a2/href</a></iframe><h4>Custom BeamLocation</h4><p>As mentioned, we’ll have to rename pathBlueprints to pathPatterns and put a concrete state type when extending BeamLocation.</p><p>On v0.14.1 we could have</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d608ca1317d04e54c417400aa4d5b356/href">https://medium.com/media/d608ca1317d04e54c417400aa4d5b356/href</a></iframe><p>Now we have</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d0a2f684847373cf4c6258924780a8/href">https://medium.com/media/14d0a2f684847373cf4c6258924780a8/href</a></iframe><p>Note how we can now use const constructor of BeamPage instead of needing to use it on all properties (if we develop with prefer_const_constructors linter rule).</p><h4>Miscellaneous</h4><p><strong>Accessing currentBeamLocation.state<br></strong>Now the state type cannot be automatically inferred (even if it’s a default BeamState) so we need to cast it manually to be able to access desired attributes of its type.</p><p>Before we could do</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a24053e63be0a8a1a02dd8763a621ad4/href">https://medium.com/media/a24053e63be0a8a1a02dd8763a621ad4/href</a></iframe><p>Now we must</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/345fa228138e961ab07d4545dc853fa2/href">https://medium.com/media/345fa228138e961ab07d4545dc853fa2/href</a></iframe><p><strong>BeamGuard<br></strong>As in BeamLocation, pathBlueprints is renamed to pathPatterns and beamTo/ beamToNamed got 2 parameters.</p><p>Before we had</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b12d1e2ff3688c9a8cbd5e2c16452a7c/href">https://medium.com/media/b12d1e2ff3688c9a8cbd5e2c16452a7c/href</a></iframe><p>Now we have it like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f16ee0a804b2fb0b080dc307b87337/href">https://medium.com/media/12f16ee0a804b2fb0b080dc307b87337/href</a></iframe><h3>Final thoughts</h3><p>I hope this article was helpful to anyone already using Beamer or even to someone thinking of starting the journey towards new navigation concepts. It sure was (and is) fun for me and I plan to write some more about it in the future.</p><p>Feel free to visit Beamer’s <a href="https://github.com/slovnicki/beamer">GitHub repository</a> or <a href="https://discord.gg/8hDJ7tP5Mz">Discord server</a> for further discussions and questions you may have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b251b3758e3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/beamer-v1-0-0-is-out-whats-new-and-how-to-migrate-b251b3758e3c">Beamer v1.0.0 is out! What’s new and how to migrate</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pLam: A mighty tool for learning and exploring pure λ-calculus]]></title>
            <link>https://medium.com/@slovnicki/plam-a-mighty-tool-for-learning-and-exploring-pure-%CE%BB-calculus-45b53be6f238?source=rss-aa0978f75af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b53be6f238</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[lambda-calculus]]></category>
            <dc:creator><![CDATA[Sandro Lovnički]]></dc:creator>
            <pubDate>Sun, 25 Aug 2019 15:06:37 GMT</pubDate>
            <atom:updated>2019-08-26T20:21:52.728Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore the basics of λ-calculus and how to evaluate cool expressions with pLam.</p><p>The source code, examples and documentation for pLam can be found <a href="https://github.com/sandrolovnicki/pLam">here at GitHub</a></p><h3>What is λ-calculus?</h3><p>λ-calculus is a formal system for expressing computation via function abstraction and application. Much like Turing Machine is a (more famous) framework for expressing computation, so is λ-calculus. Both of them are universal models of computation (i.e. they are equivalent in power) and can simulate each other.</p><p>It was invented by Alonzo Church in the 1930s as an attempt to formalize mathematics and to answer the question “Can everything be computed?”. I will not go into historical details of this quest for truth, but the answer to the question is “no”. There are things that are not computable. Interested reader can learn more about those topics starting, for example, at<a href="https://en.wikipedia.org/wiki/Computability"> Wikipedia page about Computability</a>.</p><p>In later years, Church’s student Alan Turing came up with the idea of modeling computation with some more machine-like apparatus for which they together proved it was equivalent in power to λ-calculus. Turing’s idea was the foundation for building a modern computer architecture and a basis for imperative programming languages (C, C++, Java, Python, …) which all use statements that change some shared global memory.</p><p>On the other hand, λ-calculus became a foundation for functional programming languages (Lisp, Haskell, …) that compute by composing and applying functions. Many imperative languages today have support for functional style programming with “anonymous functions”.</p><h4>Syntax and semantics of λ-calculus</h4><p>There are only 3 entities in λ-calculus; <strong>variable</strong>, <strong>abstraction</strong> and <strong>application</strong>. We call them λ-expressions.</p><ul><li>variable is represented with single character, e.q. x.</li><li>abstraction is a definition of a function and is written as λx. L, where x is a variable (“the input”) and L is some λ-expression (the body, “the output”). You can think of it like a mathematical function f(x) = L , where L can be something like x+5, i.e. the part you “get” when you plug in something for x.</li><li>application is two λ-expressions side-by-side, written as M N , meaning that M is applied to N. Application is left associative, i.e. X Y Z means (X Y) Z</li></ul><p>The procedure of computation in λ-calculus is done by a rewriting rule called <strong>β-reduction</strong>. It is performed when we have an application where first expression (M) is an abstraction. Then, the second member of application (N) gets replaced into abstractions’s body in place of abstraction’s variable (x) contained (if at all) inside abstraction’s body (L).</p><p>You can think of it like plugging a value into a function. For example, let&#39;s take f(x) = x + 5 and we want to plug the value 3 for x. Writing it more in the syntax of λ-calculus calculus, we would have (λx. x+5) 3 which is an application (M = (λx. x+5) and N = 3) of abstraction (variable is x and body is x+5) to the 3 . β-reduction rule tells us that we reduce this by taking the body of abstraction (x+5) and replacing occurrences of x with 3 . We get 3+5 .</p><p>And this is it. We don’t go further with this example because object 3+5 is not λ-expression and there is nothing to do here regarding λ-calculus. It was just an example of how λ-calculus computes by replacing variables with λ-expressions.</p><p>Another example; (λx. (x y x)) N gets β-reduced into (N y N)</p><p>I will stop here with λ-calculus because I intended this article to be more about pLam, with the assumption that readers are familiar enough with λ-calculus. Nevertheless, you can continue reading more about λ-calculus <a href="https://en.wikipedia.org/wiki/Lambda_calculus">here at Wikipedia</a> if interested. That Wikipedia page about λ-calculus is a great resource and I personally started my learning about the topic there.</p><h3>pLam</h3><p>pLam (<strong>p</strong>ure <strong>Lam</strong>bda calculus) is a tool to explore, test and implement various λ-expressions. Code written in pLam can be executed interactively within pLam’s shell or stored in a file with .plam extension and run anytime. There are also many useful expressions inside plam’s import/ directory that can be used as needed.</p><p>Let’s see a gif of pLam’s usage to get the basic idea of how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvkYo_ICTLRqMCxhrHY5-A.gif" /></figure><p>A guide on how to install and use pLam can be found <a href="https://github.com/sandrolovnicki/pLam#prerequisites">here in project’s README</a> and we will not go into those details here.</p><h3>Syntax and semantics</h3><p>pLam’s syntax and semantics are pretty much the same as in pure λ-calculus.</p><h4>Variable</h4><p>λ-variable is required to be lowercase and a single letter. For example, x is a good λ-variable for pLam and X, var,... are not. There are also environment variables (names for defined λ-expressions) which are every string that is not parsed as λ-variable, λ-abstraction or λ-application.</p><h4>Abstraction</h4><p>λ-abstraction is written the same as in the language of pure (untyped) λ-calculus, except that pLam treats a symbol \ as λ and it is required to write a space after .. For example, λx.λy.x would be written \x. \y. x in pLam. One can also write λ-abstraction in the „uncurried“ form: \xy. x or \x y. x.</p><h4>Application</h4><p>λ-application is written like 2 λ-expressions separated by a space, for example (\x. x) (\xy.x) or (\x. x) MyExpression or myexp1 myexp2. Brackets ( and ) are used as usual and are not required to be written for application association; the default association is to the left, so M N P is parsed as (M N) P and one only needs to specify with brackets if the intended expression should be M (N P).</p><h3>Commands</h3><p>A block of code in pLam is a line, and possible lines (commands) are the following:</p><h4>Define</h4><ul><li>syntax: &lt;string&gt; = &lt;λ-expression&gt;</li><li>semantics: let the &lt;string&gt; be a name for &lt;λ-expression&gt;.</li><li>examples: T = \x y. x, myexpression = T (T (\x. x) T) T</li><li>restriction: &lt;string&gt; needs to be of length&gt;1 or starting with uppercase letter</li></ul><h4>Evaluate</h4><ul><li>syntax: &lt;λ-expression&gt; or :d &lt;λ-expression&gt;</li><li>semantics: reduce the &lt;λ-expression&gt; to β-normal form. If :d is put in front of expression, all the reduction steps will be shown (manually or automatic, depends on what one chooses when asked)</li><li>example: \x y. x, :d T (T (\x. x) T) T</li><li>restriction: none</li></ul><h4>Import</h4><ul><li>syntax: :import &lt;string&gt;</li><li>semantics: put all the expressions defined in the file import/&lt;string&gt;.plam into the list of environment variables.</li><li>example: :import std</li><li>restriction: &lt;string&gt;.plam has to be inside import/ directory within the pLam project directory</li></ul><h4>Comment</h4><ul><li>syntax: --&lt;string&gt;</li><li>semantics: a comment line</li><li>example: -- this is a comment</li><li>restriction: none</li></ul><h4>Run</h4><ul><li>syntax: :run &lt;string&gt;</li><li>semantics: runs a .plam file with relative path &lt;string&gt;.plam</li><li>example: :run &lt;relative-path-to-plam&gt;/examples/2.5.2</li><li>restrictions: ~ for home does not work</li></ul><h4>Print</h4><ul><li>syntax: :print &lt;string&gt;</li><li>semantics: prints &lt;string&gt; to a new line. It mostly makes sense to use it in .plam programs to be executed, not in interactive mode where a comment should do the job better.</li><li>example: :print this is a message</li><li>restrictions: none</li></ul><h3>Syntactic Sugars</h3><p>pLam is equipped with some optional shortcuts to work with often used expressions.</p><h4>Church numerals</h4><p>Church numerals can be typed as 0, 1, 2,... and pLam parses those integers as λfx. x, λfx. f x, λfx. f (f x), ...</p><h4>Binary numerals</h4><p>Similar to handling Church numerals, pLam also handles binary numerals from binary.plam library. You can type them as 0b, 1b, 2b, ... which is them parsed as λp. p (λxy. y) (λexy.x), λp. p (λxy. x) (λexy.x), λp. p (λxy. y) (λp. p (λxy. x) (λexy.x)), ...<br>Note that binary numerals are nothing standard, but something I implemented, so I suppose the only documentation for them is pLam.</p><h4>Lists</h4><p>List encoding is pretty standard; empty = T, append = λhtfl. l h t, and you can use syntactic sugar which parses [1,2] into λfl. l 1 (λfl. l 2 empty), [T,\x.x] into λfl. l T (λfl. l (λx.x) empty) and so on...</p><h3>Examples</h3><p>Many examples of pLam programs to get you started, from beginner to advanced level, can be found <a href="https://github.com/sandrolovnicki/pLam#examples">here in project’s README</a>.</p><p>For example, in the bellow image we :import useful expressions (T, F, and , ...) from pLam’s std library and then evaluate expression and (or T F) T with :d keyword to see the details of all reduction steps.</p><p>pLam gives us the number of reductions, β-normal form of the result and (in the third yellow line of output) tries to find a name (in space of previously defined expressions) for the result, or at least for sub-expressions in the result. In this case, it finds a name for the entire result which is T (true).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3SMKlzL0Jovy4FRwPPvpw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b53be6f238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter BottomNavigationBar with BLoC pattern]]></title>
            <link>https://medium.com/@slovnicki/flutter-bottomnavigationbar-with-bloc-pattern-bba6f13d49f3?source=rss-aa0978f75af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba6f13d49f3</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[bottom-navigation]]></category>
            <category><![CDATA[example]]></category>
            <dc:creator><![CDATA[Sandro Lovnički]]></dc:creator>
            <pubDate>Sun, 11 Aug 2019 14:40:47 GMT</pubDate>
            <atom:updated>2019-08-12T14:42:30.294Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will be building a simple example application with Flutter demonstrating the usage of BottomNavigationBar widget with BLoC design pattern.</p><p>Full source of this app can be found <a href="https://github.com/sandrolovnicki/bottom_navigation_bloc">here at GitHub</a>.</p><p>If you are unfamiliar with BLoC pattern, you can read more at <a href="http://flutterdevs.com/blog/bloc-pattern-in-flutter-part-1/">http://flutterdevs.com/blog/bloc-pattern-in-flutter-part-1/</a>. The basic idea of BLoC pattern is based on Streams and Sinks which are used to provide and consume a continuous flow of data. Dealing with Streams and Sinks directly can be cumbersome, so we will be using some great packages; <a href="https://pub.dev/packages/bloc">bloc</a> and <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>.</p><p>Our app should look something like this when finished:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Mlg4fHOFijX0cRnZdwT2xg.gif" /></figure><h3>Let’s get started</h3><p>First things first, let’s add our packages to pubspec.yaml under ‘dependencies’. Notice that we are also adding an <a href="https://pub.dev/packages/equatable">equatable</a> and <a href="https://pub.dev/packages/meta">meta</a> packages. Equatable is very useful in reducing the amount of boilerplate code for determining whether the two objects are equal regarding their properties, and this package is from the same developer as bloc and flutter_bloc. Meta is used for annotating parts of code.</p><pre><strong>dependencies</strong>:<br>  <strong>flutter</strong>:<br>    <strong>sdk</strong>: flutter<br><br>  <strong>bloc</strong>: ^0.14.0  <em># https://pub.dev/packages/bloc<br>  </em><strong>flutter_bloc</strong>: ^0.19.0  <em># https://pub.dev/packages/flutter_bloc<br>  </em><strong>equatable</strong>: ^0.3.0  <em># </em><a href="https://pub.dev/packages/equatable"><em>https://pub.dev/packages/equatable</em></a><em><br>  </em><strong>meta</strong>: ^1.1.6  <em># https://pub.dev/packages/meta</em></pre><h4>Directory structure</h4><p>Although it is not necessary to have so much separation for this small example app, I think this structure is a very good practice as projects get bigger. Our lib/ will look something like this when we finish making the app.</p><pre>lib/<br>  | repositories/<br>    | api/<br>    | models/<br>    | repositories.dart<br>    | first_page_repository.dart<br>    | second_page_repository.dart<br>  | blocs/<br>    | bottom_navigation/<br>      | bottom_navigation.dart<br>      | bottom_navigation_event.dart<br>      | bottom_navigation_state.dart<br>      | bottom_navigation_bloc.dart<br>  | ui/<br>    | pages/<br>      | pages.dart<br>      | first_page.dart<br>      | second_page.dart<br>    | app_screen.dart<br>  | main.dart</pre><p>repositories/ should be for fetching and storing data, blocs/ for different blocs that manipulate objects between repositories and UI and ui/ for UI components.</p><p>We will have nothing inside api/ and models/, but they can be used by the *_repository.dart files for fetching and storing data in appropriate format. Our page data will be just String and int that we will generate locally within repository files.</p><h3>Repositories</h3><p>Our FirstPageRepository class will be responsible for providing data contained in the first page and SecondPageRepository will provide data for second page. Simple enough. Let’s implement those classes:</p><pre><strong>class </strong>FirstPageRepository {<br>  String _data;<br><br>  Future&lt;<strong>void</strong>&gt; fetchData() <strong>async </strong>{<br>    // simulate real data fetching<br>    <strong>await </strong>Future.delayed(Duration(milliseconds: 600));<br>    // store dummy data<br>    _data = &#39;First Page&#39;;<br>  }<br><br>  String <strong>get </strong>data =&gt; _data;<br>}</pre><p>And the second…</p><pre><strong>import </strong>&#39;dart:math&#39;;<br><br><strong>class </strong>SecondPageRepository {<br>  int _data;<br><br>  Future&lt;<strong>void</strong>&gt; fetchData() <strong>async </strong>{<br>    // simulate real data fetching<br>    <strong>await </strong>Future.delayed(Duration(milliseconds: 600));<br>    // store dummy data<br>    _data = Random().nextInt(1000);<br>  }<br><br>  int <strong>get </strong>data =&gt; _data;<br>}</pre><p>These classes and their methods will be used by our BottomNavigationBloc which we will see soon enough.</p><h3>Bottom Navigation BLoC</h3><p>The main things to implement here are Events, States and a method mapEventToState to transform Events to States.</p><h4>Events</h4><p>bloc package is designed to convert Events into States. Event is considered to be some user interaction with UI (e.g. button press) and State is a product of this interaction that gets sent back to the UI for its rebuild based on data the State is carrying (explicitly or implicitly).</p><p>Our only* Event will be PageTapped which will also carry information which page was tapped; first or second. Well, we will also add an Event AppStarted for the sake of diversity, but this Event should usually be a part of some other BLoC.</p><pre><strong>import </strong>&#39;package:meta/meta.dart&#39;;<br><strong>import </strong>&#39;package:equatable/equatable.dart&#39;;<br><br><strong>abstract class </strong>BottomNavigationEvent <strong>extends </strong>Equatable {<br>  BottomNavigationEvent([List props = <strong>const </strong>[]]) : <strong>super</strong>(props);<br>}<br><br><strong>class </strong>AppStarted <strong>extends </strong>BottomNavigationEvent {<br>  @override<br>  String toString() =&gt; &#39;AppStarted&#39;;<br>}<br><br><strong>class </strong>PageTapped <strong>extends </strong>BottomNavigationEvent {<br>  <strong>final </strong>int index;<br><br>  PageTapped({@required <strong>this</strong>.index}) : <strong>super</strong>([index]);<br><br>  @override<br>  String toString() =&gt; &#39;PageTapped: $index&#39;;<br>}</pre><p>We have our base class BottomNavigationEvent that extends Equatable (for reasons mentioned at the beginning of this article) and our two Events extend this further. We are overriding toString methods because we will see later how to use BlocDelegate to print our Event-State transitions as they are happening.</p><h4>States</h4><p>Now we need to think in what States will our app be regarding these Events, i.e. what changes should happen in the UI.</p><p>As our app has the BottomNavigationBar with highlighted current tab, we need to let the UI know when this has been changed. For this, we will have CurrentIndexChanged state which will carry the currentIndex to the UI. Also, when we switch the tab, some data should be loaded and drawn. For the loading State, we have PageLoading and for the loaded States, we have FirstPageLoaded and SecondPageLoaded which will carry the page’s data.</p><pre><strong>import </strong>&#39;package:meta/meta.dart&#39;;<br><strong>import </strong>&#39;package:equatable/equatable.dart&#39;;<br><br>@immutable<br><strong>abstract class </strong>BottomNavigationState <strong>extends </strong>Equatable {<br>  BottomNavigationState([List props = <strong>const </strong>[]]) : <strong>super</strong>(props);<br>}<br><br><strong>class </strong>CurrentIndexChanged <strong>extends </strong>BottomNavigationState {<br>  <strong>final </strong>int currentIndex;<br><br>  CurrentIndexChanged({@required <strong>this</strong>.currentIndex}) : <strong>super</strong>([currentIndex]);<br><br>  @override<br>  String toString() =&gt; &#39;CurrentIndexChanged to $currentIndex&#39;;<br>}<br><br><strong>class </strong>PageLoading <strong>extends </strong>BottomNavigationState {<br>  @override<br>  String toString() =&gt; &#39;PageLoading&#39;;<br>}<br><br><strong>class </strong>FirstPageLoaded <strong>extends </strong>BottomNavigationState {<br>  <strong>final </strong>String text;<br><br>  FirstPageLoaded({@required <strong>this</strong>.text}) : <strong>super</strong>([text]);<br><br>  @override<br>  String toString() =&gt; &#39;FirstPageLoaded with text: $text&#39;;<br>}<br><br><strong>class </strong>SecondPageLoaded <strong>extends </strong>BottomNavigationState {<br>  <strong>final </strong>int number;<br><br>  SecondPageLoaded({@required <strong>this</strong>.number}) : <strong>super</strong>([number]);<br><br>  @override<br>  String toString() =&gt; &#39;SecondPageLoaded with number: $number&#39;;<br>}</pre><p>The implementation of BottomNavigationState is very similar in approach as was for BottomNavigationEvent .</p><h4>BLoC</h4><p>The last thing to do is to implement the logic for converting Events to States. This is done by extending a Bloc class provided by bloc package and overriding initialState and mapEventToState .</p><pre><strong>import </strong>&#39;dart:async&#39;;<br><br><strong>import </strong>&#39;package:bloc/bloc.dart&#39;;<br><br><strong>import </strong>&#39;bottom_navigation_event.dart&#39;;<br><strong>import </strong>&#39;bottom_navigation_state.dart&#39;;<br><strong>import </strong>&#39;package:bottom_navigation_bloc/repositories/first_page_repository.dart&#39;;<br><strong>import </strong>&#39;package:bottom_navigation_bloc/repositories/second_page_respository.dart&#39;;<br><br><strong>class </strong>BottomNavigationBloc <strong>extends </strong>Bloc&lt;BottomNavigationEvent, BottomNavigationState&gt; {<br>  <strong>final </strong>FirstPageRepository firstPageRepository;<br>  <strong>final </strong>SecondPageRepository secondPageRepository;<br>  int currentIndex = 0;<br><br>  BottomNavigationBloc({<br>    <strong>this</strong>.firstPageRepository,<br>    <strong>this</strong>.secondPageRepository<br>  }) : <strong>assert</strong>(firstPageRepository != <strong>null</strong>),<br>        <strong>assert</strong>(secondPageRepository != <strong>null</strong>);<br><br>  @override<br>  BottomNavigationState <strong>get </strong>initialState =&gt; PageLoading();<br><br>  @override<br>  Stream&lt;BottomNavigationState&gt; mapEventToState(BottomNavigationEvent event) <strong>async* </strong>{<br>    <strong>if </strong>(event <strong>is </strong>AppStarted) {<br>      <strong>this</strong>.dispatch(PageTapped(index: <strong>this</strong>.currentIndex));<br>    }<br>    <strong>if </strong>(event <strong>is </strong>PageTapped) {<br>      <strong>this</strong>.currentIndex = event.index;<br>      <strong>yield </strong>CurrentIndexChanged(currentIndex: <strong>this</strong>.currentIndex);<br>      <strong>yield </strong>PageLoading();<br><br>      <strong>if </strong>(<strong>this</strong>.currentIndex == 0) {<br>        String data = <strong>await </strong>_getFirstPageData();<br>        <strong>yield </strong>FirstPageLoaded(text: data);<br>      }<br>      <strong>if </strong>(<strong>this</strong>.currentIndex == 1) {<br>        int data = <strong>await </strong>_getSecondPageData();<br>        <strong>yield </strong>SecondPageLoaded(number: data);<br>      }<br>    }<br>  }<br><br>  Future&lt;String&gt; _getFirstPageData() <strong>async </strong>{<br>    String data = firstPageRepository.data;<br>    <strong>if </strong>(data == <strong>null</strong>) {<br>      <strong>await </strong>firstPageRepository.fetchData();<br>      data = firstPageRepository.data;<br>    }<br>    <strong>return </strong>data;<br>  }<br><br>  Future&lt;int&gt; _getSecondPageData() <strong>async </strong>{<br>    int data = secondPageRepository.data;<br>    <strong>if </strong>(data == <strong>null</strong>) {<br>      <strong>await </strong>secondPageRepository.fetchData();<br>      data = secondPageRepository.data;<br>    }<br>    <strong>return </strong>data;<br>  }<br>}</pre><p>Notice that we have here our repositories as members so BLoC doesn’t have to deal with how the data is being fetched, via network or locally and what not. BLoC’s responsibility is to get the data, decide what to do with it and send appropriate states to the UI. This is done inside mapEventToState method.</p><h3>UI</h3><p>The last thing to do is to write the UI components for this app.</p><h4>Pages</h4><p>We start of with pages. They will be StatelessWidget that just render themselves with data they are constructed with.</p><pre><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>class </strong>FirstPage <strong>extends </strong>StatelessWidget {<br>  <strong>final </strong>String text;<br><br>  FirstPage({<strong>this</strong>.text}) : <strong>super</strong>();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      body: Center(<br>        child: Text(&#39;My text is: $text&#39;),<br>      ),<br>    );<br>  }<br>}</pre><p>And the second…</p><pre><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>class </strong>SecondPage <strong>extends </strong>StatelessWidget {<br>  <strong>final </strong>int number;<br><br>  SecondPage({<strong>this</strong>.number}) : <strong>super</strong>();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>Scaffold(<br>      body: Center(<br>        child: Text(&#39;My number is: $number&#39;),<br>      ),<br>    );<br>  }<br>}</pre><h4>AppScreen</h4><p>This StatelessWidget redraws its body and bottomNavigationBar depending on the state yielded from BottomNavigationBloc , by using the BlocBuilder from flutter_bloc package.</p><p>Also, bottomNavigationBar dispatches the PageTapped Events to the BottomNavigationBloc .</p><pre><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>import </strong>&#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br><strong>import </strong>&#39;package:bottom_navigation_bloc/blocs/bottom_navigation/bottom_navigation.dart&#39;;<br><strong>import </strong>&#39;package:bottom_navigation_bloc/ui/pages/pages.dart&#39;;<br><br><strong>class </strong>AppScreen <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>final </strong>BottomNavigationBloc bottomNavigationBloc = BlocProvider.<em>of</em>&lt;BottomNavigationBloc&gt;(context);<br><br>    <strong>return </strong>Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Bottom Navigation with BLoC&#39;),<br>      ),<br>      body: BlocBuilder&lt;BottomNavigationEvent, BottomNavigationState&gt;(<br>        bloc: bottomNavigationBloc,<br>        builder: (BuildContext context, BottomNavigationState state) {<br>          <strong>if </strong>(state <strong>is </strong>PageLoading) {<br>            <strong>return </strong>Center(child: CircularProgressIndicator());<br>          }<br>          <strong>if </strong>(state <strong>is </strong>FirstPageLoaded) {<br>            <strong>return </strong>FirstPage(text: state.text);<br>          }<br>          <strong>if </strong>(state <strong>is </strong>SecondPageLoaded) {<br>            <strong>return </strong>SecondPage(number: state.number);<br>          }<br>          <strong>return </strong>Container();<br>        },<br>      ),<br>      bottomNavigationBar: BlocBuilder&lt;BottomNavigationEvent, BottomNavigationState&gt;(<br>          bloc: bottomNavigationBloc,<br>          builder: (BuildContext context, BottomNavigationState state) {<br>            <strong>return </strong>BottomNavigationBar(<br>              currentIndex: bottomNavigationBloc.currentIndex,<br>              items: <strong>const </strong>&lt;BottomNavigationBarItem&gt;[<br>                BottomNavigationBarItem(<br>                  icon: Icon(Icons.<em>home</em>, color: Colors.<em>black</em>),<br>                  title: Text(&#39;First&#39;),<br>                ),<br>                BottomNavigationBarItem(<br>                  icon: Icon(Icons.<em>all_inclusive</em>, color: Colors.<em>black</em>),<br>                  title: Text(&#39;Second&#39;),<br>                ),<br>              ],<br>              onTap: (index) =&gt; bottomNavigationBloc.dispatch(PageTapped(index: index)),<br>            );<br>          }<br>      ),<br>    );<br>  }<br>}</pre><h4>main.dart</h4><p>The last thing we will go through is the main.dart which initializes and runs our MaterialApp. Here, we also initialized an instance of BlocDelegate I mention earlier, which is responsible to print every Event-State transition that is happening in our app.</p><p>For the home of our MaterialApp we used BlocProvider to provide the BottomNavigationBloc instance to its child (with necessary instances of FirstPageRepository and SecondPageRepository). As far as the UI is concerned, the home of MaterialApp is AppScreen.</p><pre><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>import </strong>&#39;package:bloc/bloc.dart&#39;;<br><strong>import </strong>&#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br><strong>import </strong>&#39;package:bottom_navigation_bloc/repositories/repositories.dart&#39;;<br><strong>import </strong>&#39;package:bottom_navigation_bloc/blocs/bottom_navigation/bottom_navigation.dart&#39;;<br><strong>import </strong>&#39;package:bottom_navigation_bloc/ui/app_screen.dart&#39;;<br><br><strong>class </strong>SimpleBlocDelegate <strong>extends </strong>BlocDelegate {<br>  @override<br>  <strong>void </strong>onTransition(Bloc bloc, Transition transition) {<br>    <strong>super</strong>.onTransition(bloc, transition);<br>    print(transition);<br>  }<br>}<br><br><strong>void </strong>main() {<br>  BlocSupervisor.<em>delegate </em>= SimpleBlocDelegate();<br>  runApp(App());<br>}<br><br><strong>class </strong>App <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return </strong>MaterialApp(<br>      home: BlocProvider&lt;BottomNavigationBloc&gt;(<br>        builder: (context) =&gt; BottomNavigationBloc(<br>          firstPageRepository: FirstPageRepository(),<br>          secondPageRepository: SecondPageRepository(),<br>        )<br>          ..dispatch(AppStarted()),<br>        child: AppScreen(),<br>      )<br>    );<br>  }<br>}</pre><h3>Conclusion</h3><p>The usage of BLoC pattern leads to a very clean application structure and really good responsibility distribution among objects. Packages like bloc and flutter_bloc make the implementation of BLoC pattern a breeze.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba6f13d49f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>