<?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 Luan Nico on Medium]]></title>
        <description><![CDATA[Stories by Luan Nico on Medium]]></description>
        <link>https://medium.com/@luanpotter27?source=rss-ed18caa6506c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iSDW044g0wrIZBJg.</url>
            <title>Stories by Luan Nico on Medium</title>
            <link>https://medium.com/@luanpotter27?source=rss-ed18caa6506c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 06:29:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luanpotter27/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[How we tamed Hibernate ORM in Kotlin with Project Yawn]]></title>
            <link>https://craft.faire.com/how-we-tamed-hibernate-orm-in-kotlin-with-project-yawn-17692cbbad0e?source=rss-ed18caa6506c------2</link>
            <guid isPermaLink="false">https://medium.com/p/17692cbbad0e</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[Luan Nico]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 19:35:58 GMT</pubDate>
            <atom:updated>2025-12-19T18:47:31.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>Plus, a big announcement about Faire’s open source initiatives</h4><figure><img alt="Abstract vector illustration including database, code and gear iconography, serving as cover image for the article." src="https://cdn-images-1.medium.com/max/1024/1*ZqYLmzC9EmrSQHQY_I0nTQ.jpeg" /></figure><p>At <a href="https://www.faire.com/">Faire</a>, we have a very robust <a href="https://craft.faire.com/how-faire-uses-kotlin-to-power-our-small-business-marketplace-3c3c7cafe4ec">Kotlin backend service infrastructure</a> that we’ve carefully honed over the years, powered by a collection of established libraries and frameworks used by the broader open-source community, all coupled with some special Faire glue to make it all work. And as many within the JVM world, for ease of database access without writing and mapping SQL queries to models by hand, we use <a href="https://hibernate.org/">Apache Hibernate</a>. The Hibernate ORM is probably the most famous (infamous?) ORM framework of all time, and it has set the standard — and many of the pain points — for ORMs in general for several decades (yep, I know — feeling old yet?). It’s a polarizing topic. The discourse is often that people hate it but still use it, which leads me to compare it with that old democracy adage: it’s the worst way to do things, except for all of those other ways that have been tried from time to time.</p><p>It’s undeniable how easy Hibernate can make setting up basic database access, especially for smaller CRUD applications, by directly mapping tables to your POJOs, requiring very little boilerplate and glue. But it can lead to many issues that lead a lot of people to choose alternatives. But we’re not here today to talk about those, or discuss how to do ORMs or DB access in general (I leave that for the philosophers in the comments). Instead, I wanted to share a small way in which we made our usage of Hibernate, specifically the legacy Criteria API that we still use, a little bit better at Faire — taming one of its pain points with a creative solution. <em>Hint: it will involve type-safety and KSP ;)</em></p><h3>The Criteria API</h3><p>The Criteria API is a legacy way of building queries. There are newer alternatives on newer Hibernate versions, including some that aim to fix this exact pain point we’re going to talk about. But if you’re in a large codebase that has evolved and adapted around the Criteria API, you might find newer alternatives can actually be more verbose, or require a bigger paradigm shift or migration that your team might not be ready or willing to accept. In which case, you will probably be familiar with your code for building queries currently looking something like:</p><pre>criteria.add(Restrictions.eq(&quot;column&quot;, value))</pre><p>If that looks anything familiar — this article is for you. Now, at Faire, we already had, for quite a while, a wrapper over this to make it nicer to use with Kotlin:</p><pre>session.query&lt;Book&gt;<br>	.addEq(&quot;name&quot;, &quot;Lord of the Rings&quot;)<br>	.list() // returns a List&lt;Book&gt;</pre><p>That is a very thin wrapper we’ve been using and maintaining internally for years. However, it always bothered us that while we get back a fully typed List&lt;Book&gt;, consistent with the full-type-safety we know and expect in Kotlin, the actual arguments to the query were, let’s say, not ideal.</p><p>The column names are just String, and, even worse, the values are Any (that is from our Kotlin wrapper; the underlying Java API is just Object of course). If you make an incorrect assumption about your table, the best case-scenario is only catching that later on with unit tests (and that is the <em>best</em> scenario). After seeing again and again bugs and developer productivity hits, we had a dream of making this better.</p><p>But, as you can imagine, it was never a priority on top of other much-needed infrastructure improvements we’re always doing. Well, that all changed during one of our glorious <a href="https://craft.faire.com/crafting-a-hack-week-that-people-love-b0c2afe2e639">Hack Weeks</a> (an internal annual hackathon where everyone at Faire can participate and form teams to work on whatever projects their heart desires). And you can bet just what our heart desired.</p><p>So, during that pivotal Hack Week, we built a functional prototype of what would eventually replace our wrapper; a brand-new Hibernate Criteria API wrapper, with basically the same syntax we already knew and loved, minimally amended to provide one key benefit: <strong>full type-safety</strong>.</p><p>And over the course of the following 2 years (!!), we, slowly, whenever we had some spare time, migrated 61% of all queries across the entire codebase to the new infrastructure. As of now, we’re happy to say more than 11 of our production services are fully migrated. Given that, alongside the fact that all new queries are type-safe, we were able to reduce the number of magic-string induced incidents (and associated developer frustration only caught during tests) to zero.</p><p>As we rolled out this migration, we had to add support for different types of queries, refining the code-generation to power it, fixing bugs, listening to internal feedback, and thus homing in on what we now call, and are happy to introduce: <strong>Project Yawn</strong>.</p><h3>Introducing: Project Yawn</h3><p>This is what a Yawn query looks like:</p><pre>session.query(BookTable) { books -&gt;<br>	addEq(books.name, &quot;Lord of the Rings&quot;)<br>}</pre><p>That’s right! You get an object representing your Hibernate entity (BookTable), with all its fields. That means you get auto-complete, <em>intellisense,</em> and compile-time checks. But that’s not all—Yawn also knows the types of your columns, so it makes sure that the name column on the books table expects a String, and nothing else.</p><p>“But that is not going to cut it”, you might say, “I need complex queries!” Yawn has you covered — basically any query that can be written with Hibernate’s Criteria API can be written with Yawn, including complex and nested joins, projections, etc.</p><p>For example, here are the e-mails of all authors in the database whose favourite book is their own writing:</p><pre>val emails = session.project(PersonTable) { people -&gt;<br>	val favoriteBooks = join(people.favoriteBook)<br>	val favoriteBooksAuthors = join(favoriteBooks.author)<br>	addIn(people.name, authors)<br>	addEq(people.name, favoriteBooksAuthors.name)<br><br>	project(people.email)<br>}.list()</pre><p>And we support much more: projection to data classes, sub-queries (detached and correlated), join references, and much more.</p><p>And that was all thanks to…</p><h3>The magic of KSP</h3><p>In order to power the creation of the meta-model representations of our tables based on our Hibernate entities, we use the power of <a href="https://kotlinlang.org/docs/ksp-overview.html">Kotlin Symbol Processing</a>, the official meta-programming framework in Kotlin. That means we hook up compilations steps to the compiler itself — no external tools, no scripts. It is pure Kotlin code that is automatically run when you add the Yawn dependency, and integrates well with IntelliJ or your preferred editor (references and go to definition all work out-of-the-box).</p><p>We have generators that scan through any entities Foo annotated with @YawnEntity on our Gradle module and generate a FooTable definition to be used for queries, maintaining the same visibility modifiers as the original class. It has references to columns and relationships, allowing for type-safe joins, and works with all Hibernate use-cases we had so far in our vast codebase (the hardest technical challenges were settling the exact shape and design of our APIs to support these edge cases such as embedded entities, composite keys, references with different foreign keys, etc).</p><p>After a period of tweaking the interfaces to be more ergonomic, fighting with the underlying Hibernate implementations, and wrangling some complex generics, the generators are now just plain Kotlin code, so they’re easily amendable by the entire team if there’s any feature missing.</p><p>We’ve tinkered with and refined it as we added to more usages and more complex use cases. But we wanted more — we wanted to share what we did with the community, in case other projects using Hibernate could benefit (and contribute!) to Yawn. So… we did.</p><h3>OSS</h3><p>We are thrilled to announce that we are officially <a href="https://github.com/Faire/yawn/">fully open-sourcing Project Yawn under the MIT license</a>! We believe in the power and community of open source, and while we use many tools and libraries, we want to contribute back with something we could share from our work.</p><p>You can check out the repository at <a href="http://github.com/faire/yawn">github.com/faire/yawn</a> for instructions on how to get started. We also welcome contributions and constructive feedback, and would love if you could give us a star!</p><p>And that’s not all — this is just one of a few pieces we’re happy to announce as part of a broader company-wide commitment to open-source and the developer community. We’ve started to build a dedicated public-facing OSS page at <a href="http://faire.tech/open-source">faire.tech/open-source</a> where we aim to collect and catalogue projects we have (or have yet to) publish, as well as other contributions we’ve made over the years to existing and established libraries and tools we use every day.</p><p>If you’re interested in our other projects, I’d recommend checking out our <a href="https://github.com/Faire/faire-detekt-rules/">faire-detekt-rules</a>, a curated and opinionated collection of custom Detekt rules and configs that we use on our Kotlin modules. You can opt in many of the rules that help us catch bugs early on, standardize best practices, and just keep our code looking pristine.</p><p>If you’re looking to write more complex queries that Hibernate and Yawn can’t support, we highly recommend <a href="https://github.com/sqldelight/sqldelight">sqldelight</a> (which, fun fact, also uses KSP under the hood), in which case you might want to check out the <a href="https://github.com/faire/sqldelight-cockroachdb-dialect">CRDB connector we open-sourced a while ago.</a></p><p>This is just the beginning of how we think Faire can contribute to the broader OSS community — stay tuned for new additions very soon as we work to extract other pieces of our codebase and infrastructure.</p><p><em>Many thanks to everyone at Faire and elsewhere that has helped us along the way, including, but not limited to, </em><a href="https://www.linkedin.com/in/adrielmartinez/"><em>Adriel Martinez</em></a><em>, </em><a href="https://www.linkedin.com/in/emilycoleary/"><em>Emily O’Leary</em></a><em>, </em><a href="https://www.linkedin.com/in/jeanyang0/"><em>Jean Yang</em></a><em>, </em><a href="https://www.linkedin.com/in/kevinbrightwell/"><em>Kevin Brightwell</em></a><em>, </em><a href="https://www.linkedin.com/in/micahbeech/"><em>Micah Beech</em></a><em>, </em><a href="https://www.linkedin.com/in/oren-kislev-99506a77/"><em>Oren Kislev</em></a><em>, </em><a href="https://www.linkedin.com/in/quinn-budan/"><em>Quinn Budan</em></a><em>, </em><a href="https://www.linkedin.com/in/stanislav-novosad-04861b161/"><em>Stas Novosad</em></a><em>, and </em><a href="https://www.linkedin.com/in/zhipingcai/"><em>Zhiping Cai</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17692cbbad0e" width="1" height="1" alt=""><hr><p><a href="https://craft.faire.com/how-we-tamed-hibernate-orm-in-kotlin-with-project-yawn-17692cbbad0e">How we tamed Hibernate ORM in Kotlin with Project Yawn</a> was originally published in <a href="https://craft.faire.com/">The Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flame 1.0 is here!]]></title>
            <link>https://medium.com/flame-engine/flame-1-0-is-here-8a7967c37566?source=rss-ed18caa6506c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7967c37566</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[flame]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Luan Nico]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 19:36:01 GMT</pubDate>
            <atom:updated>2021-12-08T19:36:01.103Z</atom:updated>
            <content:encoded><![CDATA[<p>This article was <a href="https://dev.to/blue-fire/flame-10-is-here-430n">originally posted on dev.to</a>.</p><p>Hi there, folks! It’s been a while since our last article, but if you are following <a href="https://github.com/flame-engine/flame">Flame on GitHub</a> or participating in our <a href="https://discord.gg/pxrBmy4">Discord</a>, you know very well that we have not been idle. Far from it. In fact, you might have noticed more and more Release Candidates being put out regularly, mostly with some needed updates and cleanups, a few new core features, bug fixes, and incorporating valuable feedback from our amazing Game Jam. That is because both the team and the community have been working together, relentlessly, to make Flame the best it can be.</p><p>And, first of all, I would like to make it very clear that we are not done with this goal, not even close — the pile of things we know could be improved, extended or added is only shadowed by the mountain that we don’t even know about yet. So the first thing I would like to reassure everyone, with this article, is that nothing really changes in that regard. We will still be putting out PRs, receiving invaluable help from the community, making improvements, new features, bug fixes. We will still be at discord, helping out new people, having deep, productive discussions with veterans, and collaborating together to keep growing and enhancing all Blue Fire’s projects.</p><p>That being said, we do have a key milestone to share. You might have already heard about it on the <a href="https://medium.com/flutter/announcing-flutter-2-8-31d2cb7e19f5">Flutter 2.8 release article</a>, or maybe got a sneak peek on pub; but, regardless, we wanted to double down and proudly announce we just released Flame 1.0.0. Yes, it’s official, and finally here! What an end-of-year holiday gift to us to finally be able to say that, given all the work that has been put into it! We are very happy with the current state of our code and the capabilities provided, and we think it’s time to make this commitment. Thank you so much for every single one of you, that contributed with PRs, discussions, questions (that led us to improve some docs or reconceptualize some API), monetary donations via our <a href="https://www.patreon.com/bluefireoss">Patreon</a>, or that used Flame, made something great, participated in any way, gave us a star on <a href="https://github.com/flame-engine/flame">GitHub</a>, or just for reading and sharing this article. Thank you, from the bottom of our hearts.</p><p>And let me reiterate; we are still going to keep improving, updating, fixing, enhancing Flame. In fact, I hope version 1.0.0 lives very briefly on pub, to be replaced with 1.0.1, 1.1.0, whichever comes first, very soon. This just means we believe the current API is stable, and we won’t be making big, breaking changes that often, or without warning. Expect more structured, stable updates, especially new features. It also means we can focus our attention now to improving our docs, bridge packages, tooling, examples and tutorials to make sure this awesome ecosystem that came about works seamlessly and frictionlessly, and that people can easily welcome people to join and learn. We are also happy to have established and to carry on this partnership with the Flutter team to make sure we all pave a future together for Flame and our beloved community.</p><p>And on that note, we ask you to update your dependency, head over to <a href="https://discord.gg/pxrBmy4">Discord</a> to continue the discussion, and if you haven’t, please check <a href="https://medium.com/flutter/announcing-flutter-2-8-31d2cb7e19f5">Flutter’s article</a> about all the amazing things packed on Flutter 2.8, and let us know if you have any feedback! Thanks everyone again for everything, and have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7967c37566" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flame-engine/flame-1-0-is-here-8a7967c37566">Flame 1.0 is here!</a> was originally published in <a href="https://medium.com/flame-engine">Blue Fire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five features I wish Dart had]]></title>
            <link>https://medium.com/flame-engine/five-features-i-wish-dart-had-beb0e574bf00?source=rss-ed18caa6506c------2</link>
            <guid isPermaLink="false">https://medium.com/p/beb0e574bf00</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Luan Nico]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 14:38:43 GMT</pubDate>
            <atom:updated>2021-03-29T14:38:43.238Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article was originally <a href="https://dev.to/luanpotter/five-features-i-wish-dart-had-58l7"><em>published at</em> dev.to</a>.</blockquote><p>The Dart programming language has recently undergone a major version update, 2.12, which brought sound null-safety to the ecosystem. With the recent announcement of Flutter 2.0, supporting web and desktop alongside mobile, this new version of the language has been gaining a lot of traction as project maintainers such as myself start or continue to migrate their packages to support it.</p><p>And the first thing I have to say about it is that it’s great. I already loved Dart before, and this was definitely one of the most important things on the roadmap. I particularly love typed languages; after many years working with Javascript, which I also really like, I came to the realization that the extra cost of typing pays off (and the recent popularity of Typescript helps to substantiate this point). And Dart has built-in type safety, which is great. But after a lot of time using Kotlin and Swift, that not only offer types but null-safe types, I realized, on the same vein, how important this feature is for writing great, resilient applications, help developers avoid mistakes, code quickly and safely.</p><p>And I realize one big burden (on the other side) of types is the extra verbosity it inherently introduced. For example, whenever I coded in Java in the past I was very happy with the security and stableness types provided but it just felt like a lot of extra work compared to JS. But it doesn’t have to be that much, and Kotlin, Swift, and the newer versions of Java showed me that, if you bring (1) yes, types but also (2) a lot of (sometimes small) language improvements, syntax sugars, helping features, you can get the benefits of types with very little overhead. And that is where I think they shine. Now, the same thing is true for null safety. Imagine if we didn’t have the Elvis operator in Dart, for example. Would be much more painful to write proper null safe code, up to a point it starts to compete with the benefits in the first place. Granted the pros and cons are in different areas (ease of coding vs stability and fewer bugs), and that is why this is ultimately a matter of opinion. But the better the language is at providing the right features that allow developers to write pretty, understandable code easily and quickly (like by adding the Elvis/null aware operators), the more attractive it becomes to be on that side of the scale.</p><p>And, again, I really like Dart and all it has to offer, and I am totally in favor of type and null safety being on the language. But having spent some time migrating packages and apps, I believe there are a few things that would make everyone life’s much better. These are relatively small, non-disruptive, non-breaking, incremental changes that are not necessarily directly related to null safety but that, especially if you worked with languages like Kotlin and Swift before (my main sources of inspiration), you might miss when migrating code. The fact that null safety inevitably adds some extra level of boilerplate helped expose these needs more clearly to me, in a way that I hadn’t necessarily craved them before.</p><p>My goal with this article is far from bashing Dart (I think I made it more than clear how I feel about it!) or to mourn the unchangeable fate of the universe, or anything like that. In fact, I currently use Dart in my free time purely because I like it. But rather my goal is for this to be a proposal, both for the community and (hopefully!) for the Dart team, a set of ideas that can be picked from, studied, mix and matched. A showcase of, in my opinion, great things other languages have to offer (for those unfamiliar). A collection of wishes and anecdotes.</p><p>And I should try to finally get to my clickbait-y title quickly because I’ve been vaguely rambling for a while putting a lot of trust in your patience with my digressions. And I swear it’s coming and they are going to be very concrete, specific things (now I am just building anticipation). But the last thing I wanted to mention before getting right into it, and there is no way I can omit this reference, is the library <a href="https://gitlab.com/wolfenrain/dartlin">Dartlin</a>.</p><p>Full disclaimer, Dartlin was created by my friend <a href="http://gitlab.com/wolfenrain">Jochum</a>, and I have contributed to it after I learned of its existence (since, as you can imagine by this article, I loved the idea). It is basically a Kotlin inspired set of features, built in the library level (using for example things like Extension Functions) that aim to bring great features from Kotlin to Dart. I will mention on some of these features how the proposed effect could be accomplished with Dartlin. However, no matter how clever Jochum gets at the library level to replicate some features, it can never be as good, as simple, easy to use as a native feature. Also bear in mind adding extra functions, lambdas, et cetera to emulate non-native concepts has a performance overhead, so I definitely endorse Dartlin but I recommend making sure it’s not causing an application critical bottleneck (and there could be a whole other article about what really matters for performance of a given app versus premature optimizations).</p><p>Now, with all that out of the way, finally, here are 5 features I wish Dart had (natively), in no particular order:</p><h3>1. Kotlin’s let</h3><p>A very famous construct in Kotlin is the let function. Basically, it is one of the more famous so-called Scope Functions. And it&#39;s particularly useful for null-safe code. The implementation is deceptively simple; it&#39;s an extension function on Any that invokes a lambda where the first argument is this callee. Seems useless? Well, one simple use case where it has a small role could be this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c58c20469ae33758ebf756cbcd03874/href">https://medium.com/media/6c58c20469ae33758ebf756cbcd03874/href</a></iframe><p>Instead of having to name a variable with a meaningless identifier, this one-liner is easy to read and a quite nice use of let. But where it shines, as I mention, is in the NS world, when paired with ?.. But let&#39;s get there through an example. Imagine you are converting Dart function on the codebase to null-safe Dart:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5e346d5f65a141e265a9c2098a3b2d/href">https://medium.com/media/6b5e346d5f65a141e265a9c2098a3b2d/href</a></iframe><p>Seems like a totally reasonable function, but actually, in the null-safe world, it’s a bad pattern. Because once you convert it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65756de3873b7886e72567952e07d732/href">https://medium.com/media/65756de3873b7886e72567952e07d732/href</a></iframe><p>You see the issue. This function is a black hole! It’s destroying information. Imagine you have a totally legit, verified, safe and sound int variable. Non-null certified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896989c1b8e93b20a1f34bff60a0f450/href">https://medium.com/media/896989c1b8e93b20a1f34bff60a0f450/href</a></iframe><p>If the argument is already a nullable variable there is no issue, but if your parameter is non-null, that precious information is lost forever. So normally, you should not take a nullable parameter in a function if (1) the output of a null parameter is always null and (2) the only case where null is returned is with the null parameter. You are much better off having:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21aafb465c25d8681ce9cbbca35b74d/href">https://medium.com/media/c21aafb465c25d8681ce9cbbca35b74d/href</a></iframe><p>And let the callee deal with its nulls. Witch is fine if the variable you have is non-null. But on the other hand,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e9f855e64433930a1354d3f7d77029/href">https://medium.com/media/b9e9f855e64433930a1354d3f7d77029/href</a></iframe><p>Is a bit of a mouthful. So imagine you could do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3d8f6c1b8f45198242512720651afe2/href">https://medium.com/media/d3d8f6c1b8f45198242512720651afe2/href</a></iframe><p>Cool huh? When you think about it it’s an extension of `?.`; where `?.` allows you to optionally call a property of an object, `?.let` allows you to optionally call a function with an object. You can also use it with a lambda:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf1adbfff4f5ecf451065ca3ad46999/href">https://medium.com/media/edf1adbfff4f5ecf451065ca3ad46999/href</a></iframe><p>Basically, you can look at it as a map operation if you look at the optional as a monad. And map could possibly be a better name in the Dart world, though it would conflict with the List.map.</p><p>But the best part of this list item is that let, as I first said, is just an extension function. So this is one case where <a href="https://pub.dev/packages/dartlin">Dartlin</a> is able to simply add it. No caveats, no hacks. It will work just like the examples! Just drop in the dependency on your pubspec.yaml and import the control flow sub library.</p><h3>2. Swift’s if let</h3><p>Dart (since the beginning) has had type promotion (also known as smart cast in other languages). In simple terms, if you assert a type to be of a more specific subtype, you don’t need to cast it in that context. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f049dbb6b30d493a1e7b121f144d9edd/href">https://medium.com/media/f049dbb6b30d493a1e7b121f144d9edd/href</a></iframe><p>Which is great when you think about null-safety is just an extension on the type system. Dog? is just a supertype of Dog. So, similarly, when you do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001b128c48ef4762250930fe5b77f319/href">https://medium.com/media/001b128c48ef4762250930fe5b77f319/href</a></iframe><p>However, you can’t be too clever with it. Smart-cast only works for local variables and parameters. It just cannot work for fields, because:</p><ul><li>fields can be changed by other functions called in your context</li><li>fields can potentially be changed by other threads (not currently a problem in Dart because it’s single-threaded)</li><li>fields can be functions with custom getters that can return arbitrary results</li></ul><p>There are many threads and issues on GitHub about this, asking for smart cast to be, well, smarter. But there is no way to do it safely. It’s just too complex for the compiler to check these things. Kotlin also does not provide smart cast for fields. And I don’t think this feature is worth having an unsound type system (going back to my initial rambling). But we don’t need to. Swift offers a very elegant solution to this problem, which I think is just cleaner than smart casting altogether: if let.</p><p>In Swift you can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d48c06609a7299737cbd1dca8f729bab/href">https://medium.com/media/d48c06609a7299737cbd1dca8f729bab/href</a></iframe><p>Alternatively, you can use the same variable name (for, say, a null check):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fea08c43c6d1c0a2f58751b1d9c7ad7/href">https://medium.com/media/5fea08c43c6d1c0a2f58751b1d9c7ad7/href</a></iframe><p>Basically, you don’t need smart cast if you can easily declare a new local variable. Instead of doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b79327468985c3f8fef8fbb9f31248f9/href">https://medium.com/media/b79327468985c3f8fef8fbb9f31248f9/href</a></iframe><p>We could do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f398bbc6852a89aaa818aba0982a16c6/href">https://medium.com/media/f398bbc6852a89aaa818aba0982a16c6/href</a></iframe><p>or</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2e917679557dd6739a87a321dccdc8e/href">https://medium.com/media/e2e917679557dd6739a87a321dccdc8e/href</a></iframe><p>That is clear, concise, and doesn’t do any magic; it’s explicit that it’s creating a copy because of the variable declaration syntax, which also can save on performance if it’s an expensive getter. It is also perfectly clear the scope in which the copy lives. No need to jeopardize the type safety with clever heuristics that work 99% of the time to introduce smart cast to fields!</p><p>Note as well that the for statement already allows you to declare new variables that only exist within its block, so this is quite intuitive (despite uncommon in other languages). This doesn&#39;t introduce any new keywords, and it&#39;s just an extension to the capabilities of the if statement.</p><p>I’m not suggesting smart casting to be removed altogether by the way, of course it can be left as an even easier alternative for local variables and parameters only. In fact, let me abuse this list item to share a small nit that I have related to smart cast: for some reason, it doesn’t work for this. If you think about it, just like a local variable or parameter, this can never change types during the execution of a method. You might be thinking that is useless because this can never be null (it can, in a very specific scenario that I leave to you as a puzzle to figure out). But where this would really come in handy would be for mixins; imagine being able to do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001201e05985e452d21e2b6227d44599/href">https://medium.com/media/001201e05985e452d21e2b6227d44599/href</a></iframe><p>Of course the addition of if let would mitigate this pain, but still it&#39;s just one tiny nit with the existing type promotion.</p><h3>3. Kotlin’s ?: hidden power</h3><p>The famous “Elvis” operator is present in many languages in several different forms, and nowadays it’s basically an umbrella term for “null-aware operators using question marks”. There is the almost omnipresent ?., to optionally access properties, and many others, but one of the most iconic has to be the coalesce operator, that I like to read as “or else”, which is ?? on Dart and Swift and ?: on Kotlin. In very simple terms, it’s equivalent to “left operand OR ELSE right operand (if left operand is null)”. For example, in Dart:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9896cfac55e26102d1578b82be6f89d5/href">https://medium.com/media/9896cfac55e26102d1578b82be6f89d5/href</a></iframe><p>Simple and effective. However, in Kotlin, the ?: has a special feature that I think no other language has (that I know of). More eagle-eyed observers might have noticed that I didn&#39;t mentioned Swift&#39;s guard let on the previous list item. That&#39;s because I believe Kotlin has it figured out. We don&#39;t need to introduce a new keyword guard if we allow the right operand of ?: to throw or return. How does it work? You can do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/853dfcf1bfe627b8f9dfa9b4dcdcdcb1/href">https://medium.com/media/853dfcf1bfe627b8f9dfa9b4dcdcdcb1/href</a></iframe><p>It’s so sweet that if you know the regular `?:`/`??` operators you can figure out what it does. And you can `throw` too! Imagine doing this on dart:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02a1d7c3b0605cd7f17af04e0955d1a2/href">https://medium.com/media/02a1d7c3b0605cd7f17af04e0955d1a2/href</a></iframe><p>There are so many possibilities! And this is just a small extension over the existing coalesce operator that is very intuitive if you already know its regular usage.</p><h3>4. Null-safe methods on collections</h3><p>As I said I have been converting a lot of packages to null-safety recently, and this issue got me puzzled for a while; a package had the following non-safe code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efcef2d5c25b953d2c37f59b9886b3c4/href">https://medium.com/media/efcef2d5c25b953d2c37f59b9886b3c4/href</a></iframe><p>Seems like a pretty reasonable code, regardless of safety. But it breaks down when you notice that the new null-safe signature of firstWhere returns T(and not T?). Which makes sense if you don’t want to add a lot of !to your code; sometimes you just know the element will be there, and otherwise throwing an error is ok. But sometimes you expect it might not be there. And I could not for the life of me find a simple small one-liner to do what I wanted in the first place!</p><p>That is why, especially now with NS, we need new collection methods. If you look at Swift and Kotlin for inspiration, we can find some very useful additions (in particular in Kotlin).</p><p>For this example, take a look at Swift’s first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dfaa6579dd9bfa7015c459b749bd43c/href">https://medium.com/media/1dfaa6579dd9bfa7015c459b749bd43c/href</a></iframe><p>It just returns nil instead of throwing. If we had that on Dart, plus our improved ?? operator, you could do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e977840276c4b9c0fb1fd26f70a9ccf/href">https://medium.com/media/5e977840276c4b9c0fb1fd26f70a9ccf/href</a></iframe><p>Which just covers both use cases with a single function. But better not to change the definition and behavior of the existing Dart functions to avoid confusion. So we can look at Kotlin instead. firstWhere is just called first (with optional lambda) and it does throw. But there is a firstOrNull version, that returns null if not find. We could have that with an optional lambda:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d89a86c0ba89f3b64da4060ace539d6/href">https://medium.com/media/8d89a86c0ba89f3b64da4060ace539d6/href</a></iframe><p>Now we have all 4 options! The existing first and firstWhere, and the proposed firstOrNull to cover both other cases. Similarly, we could have a singleOrNull function with optional test lambda, identical to Kotlin&#39;s.</p><p>Another one that is extremely handy is getOrNull: just takes an index and returns null if out-of-bounds (instead of throwing). Again, on the NS land, returning null, especially when you pair it with NS-operators, is a blessing.</p><p>Swift’s maxBy/minBy can also be handy, as it&#39;s a bit more clearer and less verbose than trying to replicate with reduce. And particularly useful for safety is the compactMap (or mapNotNull on Kotlin) that maps and filters null values in one batch, meaning that it can chain to T instead of T? (if you just do filter((e) =&gt; e != null) the compiler doesn&#39;t know the subsequent sequence/stream is NS).</p><p>The great news about this one item list as well is that these are just proposals to add functions to the SDK, which, as we already learned, can be easily done with extension functions. That is where <a href="https://pub.dev/packages/dartlin">Dartlin</a> comes to rescue again, providing all the aforementioned functions (with the Kotlin nomenclature) and even more (like the handy associate or groupBy). Another useful bit of code can be found on my ordered_set package&#39;s <a href="https://github.com/luanpotter/ordered_set/blob/master/lib/comparing.dart">Comparing class</a>, to be used alongside functions that take sorting orders. So you can get all these goodies right now, but would be even better to have them standardized into the SDK.</p><h3>5. Statements as expressions</h3><p>This one is pretty straightforward. Unlike Swift, Dart, or JS, in a few languages, like Kotlin and Rust, if and switch statements are expressions. For me, that is just a bonus that brings no hindrance. It&#39;s like adding sauce to your pasta. And it&#39;s optional of course. Use it if you want.</p><p>Now, you are definitely thinking right now, we have had the ternary operator (a ? b : c) since the primeval C language. And yes, the reason why Kotlin’s if in particular is an expression is because Kotlin doesn&#39;t have the ternary operator. And they have their reasons, which you can read on the <a href="https://discuss.kotlinlang.org/t/ternary-operator/2116/6">discussion thread</a> about it. So that is it? List item 5 is a hoax? Not so fast.</p><p>First of all, I like the ternary. I’m not saying, at all, to remove it from Dart. But it has a few small issues that could be complemented by having both. When starting with Kotlin most people miss the ternary, but once you realize the language has if statements as expressions, you barely miss it anymore. What&#39;s the difference?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b3365657e463fbed96ba0c7604e2a5/href">https://medium.com/media/62b3365657e463fbed96ba0c7604e2a5/href</a></iframe><p>In that case pretty much nothing (I don’t think small preferences of expressiveness vs succinctness are enough to propose Dart to change). Where the if gets the better of the regular ternary though, is when the expression is not so short. If it doesn&#39;t fit in a line. Imagine this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc0dbbf0718296ed9e713c7e7ce6978d/href">https://medium.com/media/dc0dbbf0718296ed9e713c7e7ce6978d/href</a></iframe><p>Because we don’t have if-expressions, I am forced to declare that variable i as var instead of final, even though I don’t plan on modifying it. I could get all the benefits from the compiler by marking it as final if the compiler was able to understand this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a40a5cae4e21c14b08a2987cdeb296a/href">https://medium.com/media/0a40a5cae4e21c14b08a2987cdeb296a/href</a></iframe><p>And yes, that can be done with the ternary, but if the bodies of one or both of the paths are big, you can get multi-line (or worse, nested) ternaries, which are particularly hard to understand and format in a pretty way. You could extract the blocks to functions, but sometimes to do that you are forced to pick very long names because those blocks weren’t easily describable (which is why they weren’t functions, to begin with). And with long names on the 3 operators (plus the output variable name in this case), you can easily get past your preferred line length even with the succinct 2-character operator.</p><p>And that is not the only reason Kotlin opted for statements-as-expressions instead of ternary; while the ternary can replace the if statement, Kotlin has an extremely powerful when statement, similar to the famous switch. And even though Dart’s switch is fairly inflexible, being able to do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a06e35dc0369e285adf9565772e7de00/href">https://medium.com/media/a06e35dc0369e285adf9565772e7de00/href</a></iframe><p>That is a very type-safe and concise way of mapping values, which would be just terrible to write with nested ternaries (and not type-safe when using a Map, because switches guarantee exhaustion).</p><p>Now, I would love to see more options for Dart’s switch, so it could be as powerful as Kotlin&#39;s or even Haskell&#39;s case. But that is a much bigger change, that would require a lot of thought and profound decisions, since other than enums, who would more benefit from compile-time guaranteed exhaustion and pattern matching could be things like sealed classes or union types. And I think that is definitely something worth exploring, but not in this article; I am focusing on small, (hopefully) not very controversial changes that are for the better, in my opinion.</p><p>And finally the last statement that I would like to mention is the try. Having try as expressions is incredibly handy and cannot be replaced by any other feature Dart currently has. It leads to much cleaner and readable code, for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da57f45af5ef4cf42ec8c7eecbd3540c/href">https://medium.com/media/da57f45af5ef4cf42ec8c7eecbd3540c/href</a></iframe><p>Again, preventing you from having non-final variables that you then have to guess if they have been initialized or not — have the compiler deal with that for you.</p><p>This list item is a language-level proposal, not an API change, so you would think there would be no package dependency mention here. Well, turns out Dartlin provides if, when, and try as expressions via functions. I won&#39;t delve much into how it works but if you are curious (I know you are), check out <a href="https://gitlab.com/wolfenrain/dartlin">the readme</a> for more details. This is also possibly the biggest change of the bunch because it introduces this concept of implicitly returning the last expression on the block of these statements, but I believe it&#39;s quite intuitive to pick up and would make a good addition as well.</p><p>And with that, I conclude this article. I mentioned 5 (relatively) small and (hopefully) simple features that I wish Dart had. Features that are optional, backwards compatible, and, IMHO, don’t stray too further from what Dart already has to offer. Some can be emulated with different levels of fidelity using external libraries, like Dartlin, or clever workarounds, but in general, I believe adding these (or a subset, at least) to the language should be seriously considered, especially in the new Null-Safe world. Finally, I would like to thank all the people on the Dart team that helped make NS a reality and all the awesome package maintainers and contributors that are tirelessly converting their and other people’s code to make sure everyone in the community has an even better experience with this awesome language. And I hope you liked this short read and maybe even learned something new and cool about the sprawling, creative world of programming languages.</p><p>This article was originally <a href="https://dev.to/luanpotter/five-features-i-wish-dart-had-58l7">published at dev.to</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beb0e574bf00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flame-engine/five-features-i-wish-dart-had-beb0e574bf00">Five features I wish Dart had</a> was originally published in <a href="https://medium.com/flame-engine">Blue Fire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sprite Sheet Animations in Flutter]]></title>
            <link>https://medium.com/flutter-community/sprite-sheet-animations-in-flutter-1b693630bfb3?source=rss-ed18caa6506c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b693630bfb3</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flame]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Luan Nico]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 20:59:01 GMT</pubDate>
            <atom:updated>2019-02-12T19:56:30.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZKHKQzacnyqZvGGSGuC3Q.gif" /></figure><h3><strong>Introduction</strong></h3><p>Flutter provides lots of cool and slick animations out of the box, most related to movement and tweens (continuous changes in size, position, color, et cetera). However, one particular thing that it’s really hard to do using only the native APIs is a simple sprite sheet animation. Or any sprite sheet handling, for that matter.</p><p>A sprite sheet is a single image that has multiple images (Sprites) inside, each one being accessed via it’s defining rectangle (x, y, width, and height). Maybe every sprite inside has the same size, like a tileset; for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*iL9VddUNxOAF3rtfyxGLMQ.png" /><figcaption>This is the Dunjo Tileset, it was created by <a href="https://arks.itch.io/dungeon-platform-tileset">arks</a>.</figcaption></figure><p>Let’s say you want to have several icons in your app. Instead of loading to memory dozens of small images, you can load a single one and use Sprites to refer to each icon. That’s how fonts work under the hood (though normally those are SVG nowadays).</p><p>This practice is very common in web development, because of the infamous request overhead. Making a single request is (used to be? HTTP2 tries to solve this) way faster than several requests each with headers, wrappers, TCP/IP protocol packages and shenanigans you don’t really see happening. But it’s also very common in game development, and might be useful for your packaged mobile assets, because of how graphics cards work. Without digging too much into the topic, basically loading a single image is faster because the GPU doesn’t need to keep switching the loaded images. Maybe some modern GPUs might even optimize this for multiple images, but having control over what gets bundled with what might be crucial if want to hit that sweet sweet 60 FPS mark.</p><p>Finally, especially when talking about animations, images of the sort are all distributed in sprite sheet format, and it’s easier to add to your folder structure, understand and maintain, than having hundreds of files mixed up and needing to keep adding entries to your pubspec.yaml.</p><p>But I digress, this is an article about how to make Sprite Sheet animations, so if the title wasn’t enough to encourage you to do so, nor this brief explanation of the concept, let’s see if some graphics are.</p><p>There are a lot of websites out there that provide a plethora of assets, some cheap, some free, some even free for commercial usage, assets being sprite sheets for animations, tilesets, icon sets and much more. One that I highly recommend is <a href="https://github.com/luanpotter/flame/blob/0.11.0-rc/doc/animation_widget_article/itch.io">itch.io</a>. It’s an awesome community of people who really love indie gaming, and I do recommend to check it out rather than Steam next time you want a more innovative title to play. But not only complete and WIP games are cataloged, but also resources and assets. There is a large collection of commercially free sprite sheets, like the Dunjo Tileset of the image before.</p><p>For our example, let’s say you want to animate a mighty minotaur in your regular Flutter app. We go to itch.io and find this awesome asset pack, that comes, as expected, in sprite sheet format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*v2-F_nKqfrkJlQAeKCJowQ.gif" /><figcaption>GIF showcasing the awesome minotaur animations created by <a href="https://elthen.itch.io/2d-pixel-art-minotaur-sprites">elthen</a>.</figcaption></figure><p>I’m actually gonna crop and paste using imagemagick just the frames we are going to actually use, but that’s just for simplicity and reducing the app size; remember, with sprite sheets, you decide what you use. Of course, you don’t need to have stuff you never use in your sheets. Here is the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cl7RSztaiTJRYy-qF4tYEA.png" /><figcaption>Spritesheet extract by me from the original files, available in the examples for the Flame repository. All credits to <a href="https://elthen.itch.io/">elthen</a>.</figcaption></figure><p>Now, how are we going to render this as an animation, updating the frames clockwork, to have a fluid, functional, sprite sheet animation? Enters <a href="https://github.com/luanpotter/flame">flame</a>, the modular game engine. Yes, it’s a game engine, but it’s very small and modular, so you can easily pick and choose. I’m assuming your app isn’t an actual game, though if it’s a more interactive style experience, with game loops, updates, and renderers, you should consider using 100% flame instead (or alongside) of Flutter widgets. For a tutorial on game development on Flame, I do recommend the more up-to-date article posted by the awesome folks at <a href="https://blog.geekyants.com/@geekyants">GeekyAnts</a>: <a href="https://blog.geekyants.com/building-a-2d-game-in-flutter-a-comprehensive-guide-913f647846bc">Building A 2D game in Flutter</a>.</p><p>If you don’t have a Flame game, don’t worry. Flame allows you to embed complete and complex games right inside your widget tree from regular Flutter apps. And now there are some brand new helpers to allow you to easily do the most simple and request things flame provides: drawing sprite sheet animations. How come? Well, let’s get right into it.</p><h3>Importing the Spritesheet</h3><p>First things off, get a hold of your sprite sheet. That can be most images format, but since this is pixel art, a PNG is a must. We have our minotaur sample, you can choose other of your liking. Wanna add a ticking clock with fancy effects or a bomb that goes off? You can find all those beautiful assets online. The simplest way is to have a row of sprites of the same size, in the animation order, though it’s fully configurable. Firstly, the folder structure. Flutter expects you to have an assets folder on your project root, and Flame expects an images folder, because you might have audio, fonts and other sorts of assets. Inside, put your image files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdXWrs0Xr8aM7Qx6IlkMiw.png" /><figcaption>This is the folder structure to create. animation_widget is the root folder (created by flutter create), inside an assets/images folder, and inside, all your assets.</figcaption></figure><p>Also, don’t forget to add everything to the pubspec.yml, where every asset must be declared; it should look something like this:</p><pre>flutter:<br>  assets:<br>    - assets/images/minotaur.png</pre><h3>Adding Flame</h3><p>Flame’s latest release is 0.10.1, but this feature is available since 0.10.0. Add the latest dependency to your dependencies in pubspec file and don&#39;t forget to run a flutter pub get to download everything:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flame: 0.10.1<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter</pre><h3>Adding the animation to the tree</h3><p>Let’s you have your build method in one of your pages; pretty normal Flutter stuff. This a column filled with texts, that I copied from the example in the flame repository:</p><pre>@override<br>  Widget build(BuildContext context) {<br>    final key = new GlobalKey&lt;ScaffoldState&gt;();<br>    return Scaffold(<br>      key: key,<br>      appBar: AppBar(<br>        title: Text(&#39;Animation as a Widget Demo&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Text(&#39;Hi there! This is a regular Flutter app,&#39;),<br>            Text(&#39;with a complex widget tree and also&#39;),<br>            Text(&#39;some pretty sprite sheet animations :)&#39;),<br>            // magic!<br>            Text(&#39;Neat, hum?&#39;),<br>            Text(&#39;Sprites from Elthen\&#39;s amazing work on itch.io:&#39;),<br>            Text(&#39;https://elthen.itch.io/2d-pixel-art-minotaur-sprites&#39;),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; _clickFab(key),<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }</pre><p>Note that it could be any component, however complex, inside your widgets tree. Note also that I have omitted the “magic” of the equation here. How is it that we create a component for an animation? Very basically (more details in the flame tutorial), Flame provides components, one of which is the AnimationComponent that receives an Animation object describing the animation and does exactly what we want. All components live inside a Game instance, that can add custom logic relating to the game loop. For our case, we just want to create a simple, empty game and add a single AnimationComponent with a simple Animation inside. So Flame provides a helper to do that, the Flame.util.animationAsWidget method. It takes the size of the object as a Flame&#39;s Position instance (a generic class to represent a pair of doubles), and also takes in an Animation instance representing our frame list.</p><p>To use that, let&#39;s import both Flame and the Animation class. However, since Flutter adds it&#39;s own animation classes, let&#39;s use an alias in order to not mess up the names. Therefore, add these imports to the top of the file:</p><pre>import &#39;package:flame/animation.dart&#39; as animation; // imports the Animation class under animation.Animation<br>import &#39;package:flame/flame.dart&#39;; // imports the Flame helper class<br>import &#39;package:flame/position.dart&#39;; // imports the Position class</pre><p>How we do the magic then? Just add the following to your widget tree:</p><pre>Flame.util.animationAsWidget(Position(WIDTH, HEIGHT), animation.Animation.sequenced(&#39;minotaur.png&#39;, AMOUNT, textureWidth: FRAME_WIDTH))</pre><p>The first parameter’s WIDTH and HEIGHT are the actual size of the widget on the screen. This does not need to match the sprite size, as Flame will scale it for you. You might, however, wanna keep the aspect, so things don&#39;t get distorted. In your case, the minotaur asset is a row of 96x96 pixels, so squares, therefore we can scale keeping WIDTH/HEIGHT = 1. We will choose the size as 256 px. The sequenced constructor is a helper that easily creates the animation assuming equal-sized frames in a row, in order. You can configure the start x, start y, texture width and height, but those will default gracefully to (0,0) and the actual width and height of the file. You can create your animation passing in the frame list, each frame with a different step time and Sprite (source rectangle).</p><p>In our case, we only need to set the textureWidth to 96.0, as the original width for the image is actually 19 x 96. Don&#39;t mix up texture coordinates, or source coordinates, that&#39;s the x, y inside the sprite sheet image and the size relating to that file, and the actual place and size the image/animation is going to be drawn on screen! Those are two very distinct things. We don&#39;t need to set the actual position as the widget tree will dictate that for us, we just provide the size as it&#39;s going to be a fixed size widget.</p><h3>Results</h3><p>Now, just run your app, and, hurray!, we get a slick animation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*QsvjV5PgGk15sNyqlAtmKQ.gif" /><figcaption>The final result, as recorded in the emulator!</figcaption></figure><p>Pretty sweet, huh? And that’s just the beginning. Explore Flame to add more complex, dynamic, even interactive animations, with different timings, behaviors and effects. You can start and stop your animations based on commands. You can do much, much more. Populate your apps with prettiness :)</p><p>Already thinking about the neat graphics you’ll add to your apps? Be sure to check flame as an actual game engine, there is much more complex and cool stuff, that can work both as a standalone game or inside a Flutter widget tree (all features are like that). Also, Flame is built in a modular way, so you pick and choose, and also, I strongly encourage you to go through the implementation and see how things are done. If you want to change any details, you might get a lot of insight from the source code.</p><p>This whole example is inside the examples folder for flame, and you can see the code, if you have any doubts, <a href="https://github.com/luanpotter/flame/tree/master/doc/examples/animation_widget">here</a>. This whole article is also commited <a href="https://github.com/luanpotter/flame/tree/master/doc/animation_widget_article">here</a>.</p><p>If you liked Flame, leave your clap, star on GitHub, and please check out our <a href="https://github.com/luanpotter/flame">repository</a> with full docs, examples, and issues you can ask. Also, for more in-depth questions, be sure to check our <a href="https://discord.gg/pxrBmy4">Discord channel</a>, where we try to answer questions and solve problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b693630bfb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/sprite-sheet-animations-in-flutter-1b693630bfb3">Sprite Sheet Animations in Flutter</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[A Comprehensive Flame Tutorial (or How To Make Games With Flutter)]]></title>
            <link>https://medium.com/@luanpotter27/a-comprehensive-flame-tutorial-or-how-to-make-games-with-flutter-74f22c4ecbfa?source=rss-ed18caa6506c------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f22c4ecbfa</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Luan Nico]]></dc:creator>
            <pubDate>Fri, 03 Nov 2017 09:55:17 GMT</pubDate>
            <atom:updated>2017-11-03T09:55:17.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hello, everyone! I’m Luan, and welcome to this first comprehensive Flame tutorial.</p><p>Flame is a minimalist Flutter game engine that provides a few modules to make a Canvas-based game.</p><p>In this tutorial, we are going to create a very simple game, where boxes will fall and the goal is to destroy them before they hit the bottom of the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*D_lXgIIDyH_Xnl0x.png" /><figcaption>This is how the game will look like</figcaption></figure><p>You can check the game yourself to see what we are up to installing <a href="https://github.com/luanpotter/flame-example/raw/master/tutorial/flame_example.apk">this APK</a>, or installing it <a href="https://play.google.com/store/apps/details?id=xyz.luan.flame.example">from the Play Store</a>.</p><p>This will allow us to cover all the features provided by the framework, and demonstrate how to perform the most basic operations: rendering, sprites, audio, text, animations, and more.</p><p>Why did we select this game though? Apart from being very simple yet complete for exploration of the framework, one good factor is that we have the resources to do it!</p><p>For this game, we are going to use the following resources: one crate sprite, one explosion sprite (with animation), an explosion sound, a ‘miss’ sound (for when the box is not hit), a background music and also a pretty font for rendering the score.</p><p>It’s hard to find good resources commercially available on the Internet, but we found everything (except the font) in <a href="http://opengameart.org/">this awesome site</a>. They are really great, absolutely recommended.</p><p>As for now, sprite sheets are not supported, so, first, we need to convert all the resources to appropriated formats. Also, we need to convert all the audio for MP3 (OGG is also supported; WAV is not). That being all done, you can download a bundle with everything you will need resource-wise <a href="https://github.com/luanpotter/flame-example/raw/master/tutorial/bundle.zip">here</a>.</p><p>Also worth mentioning, everything described here is committed, as a fully-functional complete version, on <a href="https://github.com/luanpotter/flame-example">GitHub</a>. You can always take a look when in doubt. Also, the example was created following this exact steps, and taking frequent commits as snapshots. Throughout the tutorial, I will link the specific commits that advance the repository to the stage in question. This will allow you to make checkpoints and browse the old code to see anything that wasn’t clear.</p><p>One last thing; you can check the full documentation for Flame <a href="https://github.com/luanpotter/flame/blob/master/README.md">here</a>. If you have any questions, suggestions, bugs, feel free to open an issue or contact me.</p><p>Apart from that, you will also need Flutter and Dart installed. If it suits you, you can also have IntelliJ IDEA, which is a very good place to write your code. In order to install this stuff, you can check out a plethora of tutorials out there, like <a href="https://flutter.io/setup/">this one</a>.</p><h3>Basics</h3><p>So, for now, I’ll assume you have everything ready. So, just run the following and open it up!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd9f71c3f11cebcf840a622eff5c8fcb/href">https://medium.com/media/fd9f71c3f11cebcf840a622eff5c8fcb/href</a></iframe><p>The first thing you need to do is to add the flame dependency. Go to your pubspec.yaml file and make sure the dependencies key lists flame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03a8d7a70760bd5d8378df9982509c9b/href">https://medium.com/media/03a8d7a70760bd5d8378df9982509c9b/href</a></iframe><p>Here we are using the latest version, 0.5.0, but you can also choose a new one if available.</p><p>Now, your main.dart file has a lot of stuff already: a ‘main’ method that needs to be kept; and a subsequent call to runApp method. This method takes Widgets and other Flutter components that are used to make app screens. Since we are making a game, we are going to draw everything on the Canvas, and won’t use these components; so strip all that out.</p><p>Our main method is now empty, and we are going to add two things; first, some configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4fcece990aa9ce2f0c0a663309add2e/href">https://medium.com/media/e4fcece990aa9ce2f0c0a663309add2e/href</a></iframe><p>The flame.dart import gives access to the Flame static class, which is just a holder for several useful other classes. We will be using more of this later. For now, we are calling two methods in this Flame class.</p><p>The last one is self-explanatory, it disables some of the logging from audioplayers plugin. Now, shortly we will be adding audio to the game, and if it doesn&#39;t work, that&#39;s where you need to comment in order to troubleshoot. But we will get there eventually.</p><p>The first line is more complex. Basically, some crucial functionality from Flutter is absent because we are not using the runApp method. This enableEvents call does a bit of a workaround to get what is essential for every application, without the need of using Widgets.</p><p>Finally, we need to start our game. In order to do that, we are going to add one more class to the import list, the Game class. This class provides the abstraction necessary to create any game: a game loop. It must be subclassed so that you are required to implement the basis of any game: an update method, which is called whenever convenient and takes the amount of time passed since last update, and a render method, which has to know how to draw the current state of the game. The inner-workings of the loop are left for the Game class to solve (you can take a look, of course, it’s very simple), and you just need to call start to, well, start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0e632cf8fea8f132b69503f7586bfb/href">https://medium.com/media/7a0e632cf8fea8f132b69503f7586bfb/href</a></iframe><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/599f8090478e0597d1ee939b9b13c895f7314875"><em>599f809</em></a></blockquote><p>Right now, the render doesn’t do anything, so, if you boot it up, it should run, but give you a black screen. Sweet! So we got a functional app without any widgets and whatnot, and a blank canvas to start drawing our app.</p><h3>Rendering Shapes</h3><p>And how is drawing done? Let’s draw a simple rectangle to see it in action. Add the following to your render method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6104e73cecd66895cebdd9a4cd593c0e/href">https://medium.com/media/6104e73cecd66895cebdd9a4cd593c0e/href</a></iframe><p>Here, as you can see, we define a rectangle, based on screen positions. The following image shows how to rules are oriented. Basically, the origin is in the top left corner, and the axis increase to the right and downwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*ND7lnzcwIX2LmHQE.png" /></figure><p>Also, note that most draw methods take a Paint. A Paint is not just a single color, but could be a Degradè or some other textures. Normally, you would either want a solid color or go straight to a Sprite. So we just set the color inside the paint to an instance of Color.</p><p>Color represents a single ARGB color; you create it with an integer that you can write down in hex for easier reading; it’s in the format A (alpha, transparency, normally 0xFF), and then two digits for R, G and B in that order.</p><p>There is also a collection of named colors; it’s is inside material package though. Just beware to import just the Colors module, as not to accidentally use something else from the material package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f67b3ef7131a8518aedc3e9a348e123/href">https://medium.com/media/5f67b3ef7131a8518aedc3e9a348e123/href</a></iframe><p>So, great, now we have a square!</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/4eff3bf1eebb60ca4fd070b183b94950229ac8ae"><em>4eff3bf</em></a></blockquote><p>We also know how the rulers work, but we don’t know the screen dimensions! How are we going to draw something in the other three corners without this information? Fear not, as Flame has a method to fetch the actual dimension of the screen (that’s because there is a documented <a href="https://github.com/flutter/flutter/issues/5259">issue around that</a>.</p><p>Basically, the async method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b868dc323fdf0ee75186e6a1757b2e/href">https://medium.com/media/31b868dc323fdf0ee75186e6a1757b2e/href</a></iframe><p>Note that the await keyword, just like in JavaScript, can only be used in an async function, so make sure to make your main async (Flutter won’t care).</p><p>The next checkpoint will fetch the dimensions once in the main method and store them inside our Game class, because we are going to need them repeatedly.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/a1f9df377d6a608df7f89bfdf557f6a25f057556"><em>a1f9df3</em></a></blockquote><h3>Rendering Sprites</h3><p>Finally, we know how to draw any shape, anywhere on the screen. But we want sprites! The next checkpoint adds some of the assets we are going to use in the appropriate assets folder:</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/92ebfd96333a0df9f68f11f0b469c56ab0132771"><em>92ebfd9</em></a></blockquote><p>And the next one does one crucial thing you <strong>cannot</strong> forget: add everything to your pubsepc.yaml file. When your code is being built, Dart will only bundle the resources you specify there.</p><blockquote><em>Checkpoint </em><a href="https://github.com/luanpotter/flame-example/commit/cf5975fd7d17a4be3b7fbb6511c6dbfb3d2d508a"><em>cf5975f</em></a></blockquote><p>Finally, we are ready to draw our sprite. The basic way Flame allows you to do that is to expose a Flame.images.load(&#39;path from within the images folder&#39;) method that returns a promise for the loaded image, which can be then drawn with the canvas.drawImage method.</p><p>However, in the case of drawing a crate, it’s very simpler to do, because we can use the SpriteComponent class, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85f5c03e0674d5fe3568f9f070b3cb2b/href">https://medium.com/media/85f5c03e0674d5fe3568f9f070b3cb2b/href</a></iframe><p>The abstract Component class is an interface with two methods, render and update, just like our game. The idea is that the Game can be composed of Component’s that have their render and update methods called within the Game’s methods. SpriteComponent is an implementation that renders a sprite, given its name and size (square or rectangular), the (x, y) position and the rotation angle. It will appropriately shrink or expand the image to fit the size desired.</p><p>In this case, we load the ‘crate.png’ file, that must be in the assets/images folder, and have a Crate class that draws boxes of 128x128 pixels, with rotation angle 0.</p><p>We then add a Crate property to the Game, instantiate it on the top of the screen, centered horizontally, and render it in our game loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1768e59b8f6fc4953275541894d9cc7a/href">https://medium.com/media/1768e59b8f6fc4953275541894d9cc7a/href</a></iframe><p>This will render our Crate! Awesome! The code is pretty succinct and easy to read as well.</p><blockquote><em>Checkpoint </em><a href="https://github.com/luanpotter/flame-example/commit/7603ca48859056f5811f0a0e11100c395b507355"><em>7603ca4</em></a></blockquote><h3>Updating State in the Game Loop</h3><p>Our crate is all but stopped in the air. We want to move it! Every crate is going to fall with constant speed, downwards. We need to do that in our update method; just change the Y position of the single Crate we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38d836829ae4b6513c6bfe0fa795e41/href">https://medium.com/media/d38d836829ae4b6513c6bfe0fa795e41/href</a></iframe><p>This method takes the time (in seconds) it took from the last update. Normally this is going to be very small (order of 10 ms). So the SPEED is a constant in those units; in our case, SPEED = 100 pixels/second.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/452dc4054e2162b9ff09468517ba1c9ae8ae13e4"><em>452dc40</em></a></blockquote><h3>Handling Input</h3><p>Hurray! The crates fall down and disappear, but you cannot interact with them. Let’s add a method to destroy the crates we touch. For that, we are going to use a window event. The window object is available in every Flutter project globally, and it has a few useful properties. We are going to register on the main method an onPointerDataPacket event, that is, when the user taps the screen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbe29aee01f85a104f5f498fc801c69d/href">https://medium.com/media/dbe29aee01f85a104f5f498fc801c69d/href</a></iframe><p>We just extract the (x,y) coordinate of the click and pass it straight to our Game; that way the Game can handle the click without worrying about events detail.</p><p>In order to make things more interesting, let’s also refactor the Game class to have a List of Crates, instead of a single one. Afterall, that’s what we want. We replace render and update methods with a forEach over the Crates, and the new input method becomes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f863bdd4a6418a4514e26f34a087eb68/href">https://medium.com/media/f863bdd4a6418a4514e26f34a087eb68/href</a></iframe><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/364a6c20cc096050503c9dbca9797c68a9b13738"><em>364a6c2</em></a></blockquote><h3>Rendering Multiple Sprites</h3><p>There is one <strong>crucial point</strong> to mention here, and it’s regarding the <strong>render method</strong>. When we render a Crate, the state of the Canvas is translated and rotate arbitrarily, in order to enable drawing. Since we are going to draw several crates, we need to <strong>reset the Canvas between each drawn</strong>. That is made with the methods save, that saves the current state, and restore, that restores the previously saved state, deleting it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d609fe8f2f397f7d185248a0a1c27f6d/href">https://medium.com/media/d609fe8f2f397f7d185248a0a1c27f6d/href</a></iframe><p>This is an important remark, as it is the source of many weird bugs. Maybe we should do that automatically in each render? I don’t know, what do you think?</p><p>Now we want more Crates! How to do that? Well, the update method can be our timer. So we want a new Crate to be added to the list (spawned) every second. So we created another variable in the Game class, to accumulate the delta times (t) from each update call. When it gets over 1, it&#39;s reset and a new crate spawned:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/714d662abe2d351513ecfdb3c2aba114/href">https://medium.com/media/714d662abe2d351513ecfdb3c2aba114/href</a></iframe><p>Don’t forget to keep the previous update, so the crates don’t stop falling. Also, we change the speed to 250 pixels/second, to make things a little more interesting.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/3932372f737c1dc442f812e25be9598750d19d01"><em>3932372</em></a></blockquote><h3>Rendering Animations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*r_SVivJI2Td2Ycfl.png" /><figcaption><em>This should be a GIF, right? We are working on a setup for better screenshots and GIFs for this tutorial!</em></figcaption></figure><p>Now we know the basics of Sprite Handling and Rendering. Let’s move to the next step: Explosions! What game is good without ‘em? The explosion is a beast of a different kind, because it features an animation. Animations in Flame are done simply by rendering different things on render according to the current tick. The same way we added a hand-made timer to spawn boxes, we are going to add a lifeTime property for every Explosion. Also, Explosion won’t inherit from SpriteComponent, as for the latter can only have one Sprite. We are going to extend the superclass, PositionComponent, and implement rendering with Flame.image.load.</p><p>Since every explosion has lots of frames, and they need to be drawn responsively, we are going to pre-load every frame once, and save in a static variable within Explosion class; like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ca465dfc9a3fb7c85ea4dfb2b4fcd2/href">https://medium.com/media/b1ca465dfc9a3fb7c85ea4dfb2b4fcd2/href</a></iframe><p>Note that we load every one of our 7 animation frames, in order. Then, in the render method, we make a simple logic to decide which frame to draw:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88a3d637a58a803e7a9d102705bda9c0/href">https://medium.com/media/88a3d637a58a803e7a9d102705bda9c0/href</a></iframe><p>Note that we are drawing ‘by hand’, using drawImageRect, as explained earlier. This code is similar to what SpriteComponent does under the hood. Also note that, if the image is not in the array, nothing is drawn — so after TIME seconds (we set it to 0.75, or 750 ms), nothing is rendered.</p><p>That’s well and good, but we don’t want to keep polluting our explosions array with exploded explosions, so we also add a destroy() method that returns, based on the lifeTime, whether we should destroy the explosion object.</p><p>Finally, we update our Game, adding a List of Explosion, rendering them on the render method, and updating then on the update method. They need to be updated to increment their lifeTime. We also take this time to refactor what was previously in the Game.update method, i.e., makes the boxes fall, to be inside the Crate.update method, as that’s a responsibility of the Crate. Now the game update only delegates to others. Finally, in the update, we need to remove from the list what has been destroyed. For that, List provides a very useful method, removeWhere:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73712538759abc9baa3b445152eb1f69/href">https://medium.com/media/73712538759abc9baa3b445152eb1f69/href</a></iframe><p>We already used that on the input method, to remove the boxes that were touched from the array. There is also where we will create an explosion.</p><p>Take a look at the checkpoint for more details.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/d8c30adca502ae5f7548dfcb40e715db348fa944"><em>d8c30ad</em></a></blockquote><h3>Playing Audio</h3><p>In the next commit, we are finally going to play some audio! To do so, you need to add the file to the assets folder, inside assets/audio/. It must be an MP3 or an OGG file. Then, anywhere in your code, run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bbb8f34fb77d362f0883baf20fb2ceb/href">https://medium.com/media/6bbb8f34fb77d362f0883baf20fb2ceb/href</a></iframe><p>Where filename.mp3 is the name of the file inside. In our case, we will play the explosion.mp3 sound when we click in a box.</p><p>Furthermore, let’s start awarding punctuation. We add a points variable to hold the current number of points. It starts with zero; we get 10 points per box clicked, and lose 20 when the box hit the ground.</p><p>We now have an obligation to deal with runaway boxes. Based on what we did to the Explosion class, we add a destroy method for the Crate, that is going to return whether they are out of the screen. This is starting to become a pattern! If destroyed, we remove from the array and adjust the points.</p><p>For now, the scoring is working, but it’s not being shown anywhere; that will come soon.</p><p>The audio will not work in this next checkpoint because I forgot to add the files and put them in the pubspec.yaml; that&#39;s done in the following commit.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/43a7570304d954a8cb38b76f863d73bc7d75d081"><em>43a7570</em></a></blockquote><p>Now we want more sounds! The audioplayers (mind the s) lib the Flame uses allow you to play multiple sounds at once, as you might already have noticed if you went click frenzy, but now let&#39;s use that to our advantage, by playing a miss sound, when the box hits the ground (destroy method of the Crate), and a background music.</p><p>In order to play the background music on a loop, use the loop method, that works just like before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ac28ad083e196b754dc60329e6fae4b/href">https://medium.com/media/0ac28ad083e196b754dc60329e6fae4b/href</a></iframe><p>In this commit, we also fix the destroy condition for the Crates, that we missed in the previous commit (because there was no way to know, now there is sound).</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/f575150a2fbcad7ea6b19bff08c6d289ed8d5404"><em>f575150</em></a></blockquote><h3>Rendering Text</h3><p>Now that we have all the audio we want (background, music, sound effects, MP3, OGG, loop, simultaneously), let’s get into text rendering. We need to see that score, after all. The way this is done ‘by hand’ is to create a Paragraph object and use the drawParagraph of the Canvas. It takes a lot of configuration and it’s a rather confusing API, but can be accomplished like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d6b665995da6e54fce5b45ee5374cb/href">https://medium.com/media/13d6b665995da6e54fce5b45ee5374cb/href</a></iframe><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/e09221e86c8f959bab1870173fa856f7f00f1951"><em>e09221e</em></a></blockquote><p>This is drawn in the default font, and you can use the fontFamily property to specify a different common system font; though, probably, in your game, you will want to add a custom one.</p><p>So I headed to 1001fonts.com and got <a href="https://gist.github.com/www.1001fonts.com/halo3-font.html">this pretty commercial free Halo font</a> as a TTF. Again, just drop the file in assets/fonts, but now it must be imported differently in the pubspec.yaml file. Instead of adding one more asset, there is a dedicated font tag, which is commented by default with complete instructions on how to add the fonts. So, assign it a name and do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e34c4a301d3dd5175f9091dbf2fe15/href">https://medium.com/media/76e34c4a301d3dd5175f9091dbf2fe15/href</a></iframe><p>This extra abstraction layer is from Flutter itself and allows you to add several files to the same font (to define bold, bigger sizes, etc). Now, back to our Paragraph, we just add the property fontFamily: &#39;Halo&#39; to the TextStyle constructor.</p><p>Run and you will see the pretty Halo font!</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/3155bdaaf1ad35325e55ef7c08457c2d7350a9d6"><em>3155bda</em></a></blockquote><p>This method described will give you more control, if you want multiple styles in the same paragraph, for example. But if you want, like in this case, a single styled simple paragraph, just use the Flame.util.text helper to create it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96640720cbac7b4170de7fb5052f7d28/href">https://medium.com/media/96640720cbac7b4170de7fb5052f7d28/href</a></iframe><p>This single line replaces those previous 4, and exposes the most important features. The text (first argument) is required, and all the rest are optional, with sensible defaults.</p><p>For the color, again we are using the Colors.white helper, but we can also use new Color(0xFFFFFFFF) if you want a specific color.</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/952a9dfd753d7e335359b4f7327e4f2bbc2938be"><em>952a9df</em></a></blockquote><p>And there you have it! A complete game with sprite rendering, text rendering, audio, game loop, events and state management.</p><h3>Release</h3><p>Is your game ready to release?</p><p>Just follow <a href="https://flutter.io/android-release/">these few simple steps</a> from the Flutter tutorial.</p><p>They are all pretty straightforward, as you can see in this final checkpoint, except for the Icons part, which might cause a bit of a headache. My recommendation is to make a big (512 or 1024 px) version of your icon, and use the <a href="https://makeappicon.com/">Make App Icon</a> website to generate a zip with everything you need (iOS and Android).</p><blockquote><em>Checkpoint: </em><a href="https://github.com/luanpotter/flame-example/commit/2974f29804d548c33fa9a736d1d3744414aaba0f"><em>2974f29</em></a></blockquote><h3>What Else?</h3><p>Did you enjoy Flame? If you have any suggestions, bugs, questions, feature requests, or anything, please feel free to contact me!</p><p>Want to improve your game and learn more? How about adding a Server with Firebase and Google Sign In? How about putting ads in? How about setting up a Main Menu and multiple screens?</p><p>There’s a lot to improve, of course — this is just an example game. But it should have given a basic idea of the core concepts of game development with Flutter (with or without Flame).</p><p>Hope everyone enjoyed it!</p><p><em>Originally published </em><a href="https://github.com/luanpotter/flame-example/blob/master/tutorial/article.md"><em>at GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f22c4ecbfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>