<?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[ICNH - Medium]]></title>
        <description><![CDATA[ICNH is an app development company located in Kiel and Hamburg. We develop native, x-platform and web applications for Android and iOS. For more information: http://icnh.de - Medium]]></description>
        <link>https://medium.com/icnh?source=rss----c4bdd4301276---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>ICNH - Medium</title>
            <link>https://medium.com/icnh?source=rss----c4bdd4301276---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:41:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/icnh" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Forth in Dart]]></title>
            <link>https://medium.com/icnh/implementing-forth-in-dart-f636bad7c07c?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/f636bad7c07c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[forth]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 10:10:48 GMT</pubDate>
            <atom:updated>2023-08-11T10:10:48.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>A humorous response to the question asked in the Flutter subreddit about the best language to use for mobile apps.</h4><p>The best programming language is <a href="http://ratfactor.com/forth/the_programming_language_that_writes_itself.html">Forth</a> for obvious reasons. Hence, it’s also the best programming language for developing mobile apps. We can use <a href="https://dart.dev/">Dart</a> to implement it.</p><p>Let’s define</p><pre>typedef Impl = void Function(Forth f);</pre><p>and create a class called Forth that encapsulates a stack to which we can push() values and from which we can pop() values</p><pre>class Forth {<br>  final stack = &lt;dynamic&gt;[];<br>  void push(dynamic value) =&gt; stack.add(value);<br>  dynamic pop() =&gt; stack.removeLast();</pre><p>and that defines a so called vocabulary of predefined words (of type Impl)</p><pre>  final Map&lt;String, Impl&gt; vocab = {<br>    &#39;+&#39;: (f) =&gt; f.push(f.pop() + f.pop()),<br>    &#39;.&#39;: (f) =&gt; print(f.pop()),<br>  };</pre><p>Also define a run() method to execute the words one by one:</p><pre>  List&lt;String&gt; words = [];<br>  void run(String input) {<br>    words = input.split(&#39; &#39;);<br>    while (words.isNotEmpty) {<br>      final word = words.removeAt(0);<br>      final impl = vocab[word] ?? lit(num.parse(word));<br>      impl(this);<br>    }<br>  }</pre><p>The lit method automatically converts words that look like numbers into Impl instances that push that number’s value to the stack so that all numbers are implicitly predefined</p><pre>  Impl lit(dynamic value) =&gt; (f) =&gt; f.push(value);</pre><p>which completes the Forth class definition</p><pre>}</pre><p>Now we can execute exepressions like Forth().run(‘1 2 3 + + .’) to print 6.</p><h4>New Words</h4><p>We need a way to define our own words like : twice dup + ; for which we need to extend the Forth class by adding : and ;</p><pre>class Forth {<br>  ...<br>  List&lt;Impl&gt;? code;<br>  Map&lt;String, Impl&gt; vocab = {<br>    ...<br>    &#39;:&#39;: (f) {<br>      final name = f.words.removeAt(0);<br>      final code = &lt;Impl&gt;[];<br>      f.vocab[name] = (f) =&gt; code.forEach((impl) =&gt; impl(f));<br>      f.code = code;<br>    },<br>    &#39;;&#39;: (f) =&gt; f.code = null,</pre><p>as well as dup which my example above also used</p><pre>    &#39;dup&#39;: (f) =&gt; f.push(f.stack.last),<br>  }</pre><p>and we need to change run to not immediately call each Impl instance when compiling code, but collecting those objects in the list set up by :</p><pre>  ...<br>  void run(String input) {<br>    words = input.split(&#39; &#39;);<br>    while (words.isNotEmpty) {<br>      final word = words.removeAt(0);<br>      final impl = vocab[word] ?? lit(num.parse(word));<br>      if (code != null &amp;&amp; word != &#39;;&#39;) {<br>        code!.add(impl);<br>      } else {<br>        impl(this);<br>      }<br>    }<br>  }</pre><p>Actually, we should distinguish between normal Impls and <em>immediate</em> Impls like ; which must be executed even when compiling, but I hardcoded it. In just a moment, I will have to also make &quot; and [ and ] immediate.</p><h4>New Apps</h4><p>However, I did brag about using Forth to create a mobile app. Here’s the code of the popular counter application</p><pre>V: count 5 !<br>: inc dup @ 1 + ! ;<br>[ [ text ] count builder<br>[ count inc ] &quot; Increment text button ] list column app run</pre><p>which should be easy to understand. I define a variable called count by assigning 5. I then define an inc word that can be applied to such a variable to increment its value by 1 and then I define a column widget with a text widget built from the variable’s value and a button widget that does the increment, wrapped as an app.</p><p>Let’s start with V:. which defines a word that pushes a ValueNotifier to the stack and also pushes that instance so it’s easier to initialize it</p><pre>    &#39;V:&#39;: (f) {<br>      final name = f.words.removeAt(0);<br>      final value = ValueNotifier&lt;dynamic&gt;(null);<br>      f.vocab[name] = f.lit(value);<br>      f.push(value);<br>    },</pre><p>The ! word expects a ValueNotifier and a value on the stack, removes both and assigns the value to the notifier, like this:</p><pre>    &#39;!&#39;: (f) =&gt; ((dynamic v) =&gt; (f.pop() as ValueNotifier&lt;dynamic&gt;).value = v)(f.pop()),</pre><p>The @ word also expects a ValueNotifier on the stack, which is replaced by the notifier’s value</p><pre>    &#39;@&#39;: (f) =&gt; f.push((f.pop() as ValueNotifier&lt;dynamic&gt;).value),</pre><p>The [ and ] words are again <em>immediate</em> words that even work even when compiling a word with :. However instead of compiling Impl instances into the currently defining word, a new list is set up up so that run writes into a so-called <em>quotation</em> which then forms a block of code that is pushed to the stack and can be explicitly executed later.</p><pre>    &#39;[&#39;: (f) {<br>      f.push(f.code);<br>      f.code = &lt;Impl&gt;[];<br>    },<br>    &#39;]&#39;: (f) {<br>      final quot = f.code;<br>      if (quot == null) throw Exception(&#39;] without [&#39;);<br>      f.code = f.pop() as List&lt;Impl&gt;?;<br>      f.add(quot);<br>    },</pre><p>The &quot; word is also an <em>immediate</em> word that pushes the next word to the stack without executing it, that is, pushes just a string.</p><pre>    &#39;&quot;&#39;: (f) =&gt; f.add(f.words.removeAt(0)),</pre><p>Here is the new add method:</p><pre>  void add(dynamic value) =&gt; code != null ? code!.add(lit(value)) : push(value);</pre><p>To deal with an expandable list of immediate words, let’s change run</p><pre>  ...<br>  final immediate = {&#39;;&#39;, &#39;&quot;&#39;, &#39;[&#39;, &#39;]&#39;};<br>  void run(String input) {<br>    words = input.split(&#39; &#39;);<br>    while (words.isNotEmpty) {<br>      final word = words.removeAt(0);<br>      final impl = vocab[word] ?? lit(num.parse(word));<br>      if (immediate.contains(word) || code == null) {<br>        impl(this);<br>      } else {<br>        code!.add(impl);<br>      }<br>    }<br>  }</pre><p>To later execute a quotation, we use this exec method:</p><pre>void exec(List&lt;Impl&gt; quot) {<br>    for (final impl in quot) {<br>      impl(this);<br>    }<br>  }</pre><p>Let’s create widgets.</p><p>The builder word expects a ValueNotifier and a quotation and sets up a ValueListenableBuilder Flutter widget so that the quotation is executed every time the notifier’s value changes.</p><pre>    &#39;builder&#39;: (f) {<br>      final vl = f.pop() as ValueNotifier&lt;dynamic&gt;;<br>      final quot = f.pop() as List&lt;Impl&gt;;<br>      f.push(ValueListenableBuilder(<br>        valueListenable: vl,<br>        builder: (context, value, _) {<br>          f.push(value);<br>          f.exec(quot);<br>          return f.pop() as Widget;<br>        },<br>      ));<br>    },</pre><p>Then we need words to create Flutter Text and Column and MaterialApp widgets, which should contain no surprises at this point.</p><pre>    &#39;text&#39;: (f) =&gt; f.push(Text(&#39;${f.pop()}&#39;)),<br>    &#39;button&#39;: (f) {<br>      final child = f.pop() as Widget;<br>      final quot = f.pop() as List&lt;Impl&gt;;<br>      f.push(ElevatedButton(onPressed: () =&gt; f.exec(quot), child: child));<br>    },<br>    &#39;column&#39;: (f) =&gt; f.push(Column(children: (f.pop() as List).cast&lt;Widget&gt;())),<br>    &#39;app&#39;: (f) =&gt; f.push(MaterialApp(home: Scaffold(body: f.pop() as Widget))),</pre><p>Last but not least, we can run the Flutter widget on the stack:</p><pre>    &#39;run&#39;: (f) =&gt; runApp(f.pop() as Widget),</pre><p>And that’s all we need to create a working Flutter application in Forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*e5ThedQzOc9AmLO-HEYI2g.png" /><figcaption>A counter app in action</figcaption></figure><p>If you’re interesting in the running example, <a href="https://dartpad.dev/?id=1a46f7f36d8d5d791230d036459e8a02">here is a Dart pad</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f636bad7c07c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/implementing-forth-in-dart-f636bad7c07c">Implementing Forth in Dart</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A TYON implementation in Dart written by ChatGPT]]></title>
            <link>https://medium.com/icnh/a-tyon-implementation-in-dart-written-by-chatgpt-aea6b4bc73ba?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/aea6b4bc73ba</guid>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 08:46:56 GMT</pubDate>
            <atom:updated>2023-08-10T17:00:16.263Z</atom:updated>
            <content:encoded><![CDATA[<h4>(It cannot deal with typed TYON values)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nsan_ThRHY6RdesO" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here is a ChatGPT experiment that might even result in something useful.</p><p><strong>I did this experiment on the 15th of April 2023, so the current version of ChatGPT 4 may have a different behaviour or may already be out of date.</strong></p><p>I recently saw a mention on HackerNews of a JSON-like data format called <a href="https://github.com/defiant00/tyon">TYON</a> and thought that a parser written in Dart might be quite useful. It shouldn’t be too difficult to write by hand, but why not let ChatGPT 4 do the job?</p><p>Basically, in addition to JSON, TYON allows for Lisp-style comments, doesn’t require &quot; for its values and starts with an implicit object so you need no top level {}. It also supports type definition that can be used to build objects from just data.</p><p>Here’s my prompt:</p><blockquote><em>Please write a parser in Dart for a file format according the specification below. Parsing a string of TYON should return a </em><em>Map&lt;String, dynamic&gt; where </em><em>dynamic is really either a </em><em>String, another of such maps or a </em><em>List&lt;dynamic&gt; where each element is again either a string, a map or a list.</em></blockquote><p>Then I appended the whole <a href="https://github.com/defiant00/tyon/blob/main/SPECIFICATION.md">specification</a> to my prompt and pressed RETURN and waited while our future overlord slowly emitted its wisdom.</p><p>ChatGTP starts with a school-book solution using a lexer and a parser:</p><pre>Map&lt;String, dynamic&gt; parseTYON(String input) {<br>  final lexer = _TYONLexer(input);<br>  final parser = _TYONParser(lexer);<br>  return parser.parse();<br>}</pre><p>The lexer is also very classical in that it stores the _input and maintains an _index of a current character (_peek) which can be consumed (_consume):</p><pre>class _TYONLexer {<br>  static const _specialChars = &#39;()[]=/;&#39;;<br><br>  String _input;<br>  int _index;<br><br>  _TYONLexer(String input)<br>      : _input = input,<br>        _index = 0;<br><br>  String _consume() {<br>    if (_index &lt; _input.length) {<br>      return _input[_index++];<br>    }<br>    return null;<br>  }<br><br>  String _peek() {<br>    if (_index &lt; _input.length) {<br>      return _input[_index];<br>    }<br>    return null;<br>  }<br><br>  ...</pre><p>Note, that ChatGPT doesn’t know about Dart’s <em>null safety</em>, so the _peek and _consume methods should be of type String?, but that&#39;s easy to fix. And _input should probably be final.</p><p>A nextToken method will return the next token from the input (again, it should have the return type String?). As you see, it will skip whitespace and return null if the end of the input has been reached. Otherwise it will skip comments or either return a syntax token, a quoted string or a literal:</p><pre>  String nextToken() {<br>    String char = _peek();<br>    while (char != null &amp;&amp; _isWhitespace(char)) {<br>      _consume();<br>      char = _peek();<br>    }<br><br>    if (char == null) {<br>      return null;<br>    }<br><br>    if (char == &#39;;&#39;) {<br>      while (char != null &amp;&amp; char != &#39;\n&#39;) {<br>        _consume();<br>        char = _peek();<br>      }<br>      return nextToken();<br>    }<br><br>    if (_specialChars.contains(char)) {<br>      _consume();<br>      return char;<br>    }<br><br>    if (char == &#39;&quot;&#39;) {<br>      _consume();<br>      return _readQuotedString();<br>    }<br><br>    return _readLiteral();<br>  }</pre><p>The _isWhitespace method does the obvious thing. Hence, I omitted the code.</p><p>The _readQuotedString method, however, doesn&#39;t follow the specification which says that a &quot; must be escaped as &quot;&quot;. Instead, it implements the usual \ quoting. That&#39;s something I will fix later.</p><p>A literal, according to the specification, cannot start with &quot; or /, but can contain it. This is something ChatGTP also overlooked in _readLiteral. I didn&#39;t bother.</p><p>The parser declares two methods to interact with the lexer, but only ever uses _nextToken (again, we need to add ? for <em>null safety</em> and a final to make the linter happy):</p><pre>class _TYONParser {<br>  _TYONLexer _lexer;<br><br>  _TYONParser(this._lexer);<br><br>  String _peekToken() =&gt; _lexer._peek();<br><br>  String _nextToken() =&gt; _lexer.nextToken();<br><br>  ...</pre><p>Let’s have a look at parse which drives the whole process:</p><pre>  Map&lt;String, dynamic&gt; parse() {<br>    Map&lt;String, dynamic&gt; result = HashMap&lt;String, dynamic&gt;();<br>    String? token = _nextToken();<br><br>    while (token != null) {<br>      if (token == &#39;(&#39; || token == &#39;[&#39;) {<br>        throw FormatException(&#39;Unexpected opening bracket&#39;);<br>      }<br><br>      String key = token;<br>      token = _nextToken();<br><br>      if (token == &#39;=&#39;) {<br>        token = _nextToken();<br><br>        if (token == &#39;(&#39; || token == &#39;[&#39;) {<br>          result[key] = _parseValue(token);<br>        } else {<br>          result[key] = token;<br>        }<br>      } else {<br>        throw FormatException(&#39;Expected &quot;=&quot; after key&#39;);<br>      }<br><br>      token = _nextToken();<br>    }<br><br>    return result;<br>  }</pre><p>It will read as many tokens as it finds. It correctly knows that a ( or [ would be illegal while expecting a property name. Actually any syntax character is invalid at this point, not just those two. It simply assumes that the token is the key. That assumption is incorrect if it&#39;s a = or ) or whatever. Also, because the lexer already removes the &quot; from quoted strings, a perfectly valid expression like &quot;[&quot; = &quot;]&quot; would be invalid. It then expects a = and tries to parse values in [ ] or () or assumes that the token must be a literal value without checking that. The code is okayish but could be improved.</p><p>Here is _parseValue:</p><pre>  dynamic _parseValue(String token) {<br>    if (token == &#39;(&#39;) {<br>      return _parseMap();<br>    } else if (token == &#39;[&#39;) {<br>      return _parseList();<br>    } else {<br>      return token;<br>    }<br>  }</pre><p>Depending on the token, it will parse a map or a list, which is correct. However, anything but a literal or quoted string (something the lexer doesn’t know) would be invalid at this point. There is absolutely no need to test for ( and [ twice. Either don&#39;t do it in parse or embed the code from _parseValue.</p><p>Parsing a list ist rather simple. It assumes tokens which are either new maps, lists or literals:</p><pre>  List&lt;dynamic&gt; _parseList() {<br>    List&lt;dynamic&gt; list = [];<br>    String? token = _nextToken();<br><br>    while (token != null &amp;&amp; token != &#39;]&#39;) {<br>      if (token != &#39;(&#39; &amp;&amp; token != &#39;[&#39;) {<br>        list.add(token);<br>      } else {<br>        list.add(_parseValue(token));<br>      }<br>      token = _nextToken();<br>    }<br>    return list;<br>  }</pre><p>Parsing a map would be more difficult, if the code would try to deal with types. But it completely ignores that and just assumes, that a map consists of key-value pairs separated by =.</p><pre>  Map&lt;String, dynamic&gt; _parseMap() {<br>    Map&lt;String, dynamic&gt; map = HashMap&lt;String, dynamic&gt;();<br>    String key;<br>    dynamic value;<br>    String? token = _nextToken();<br><br>    while (token != null &amp;&amp; token != &#39;)&#39;) {<br>      key = token;<br>      token = _nextToken();<br><br>      if (token == &#39;=&#39;) {<br>        token = _nextToken();<br><br>        if (token == &#39;(&#39; || token == &#39;[&#39;) {<br>          value = _parseValue(token);<br>        } else {<br>          value = token!;<br>        }<br><br>        map[key] = value;<br>        token = _nextToken();<br>      } else {<br>        throw FormatException(&#39;Expected &quot;=&quot; after key&#39;);<br>      }<br>    }<br>    return map;<br>  }</pre><p>So it might be able to parse the map example from the specification, but not the more complex typed examples:</p><pre>person = (<br>   first = John<br>   last = Doe<br>   age = 42<br>   &quot;favorite numbers&quot; = [1 2 3]<br>)</pre><p>I get a “type ‘List’ is not a subtype of type ‘String’” error because the value variable in parse is of type String and not dynamic. I agree with ChatGPT that it would be so much nicer if Dart had a real lightweight sum type instead of having to use dynamic. But we have to work with what&#39;s available.</p><p>After fixing that, it works.</p><p>Parsing the other examples with the exception of the typed expressions like the one below also seem to work, too.</p><pre>/person = (first-name middle-initial last-name age)</pre><p>So, are you impressed by ChatGPT’s features?</p><p>Reprinting a standard parser doesn’t impress me much. But this does:</p><blockquote><em>Me: I think, </em><em>_readQuotedString is wrong. Can you double check?</em></blockquote><p>ChatGPT: You’re correct; I made a mistake in _readQuotedString. The method should handle escaped double quotes &quot;&quot; as a single double quote &quot; in the resulting string. I&#39;ve fixed the issue in the method below:</p><pre>String _readQuotedString() {<br>  StringBuffer buffer = StringBuffer();<br>  String char = _consume();<br><br>  while (char != null &amp;&amp; char != &#39;&quot;&#39;) {<br>    if (char == &#39;&quot;&#39;) {<br>      if (_peek() == &#39;&quot;&#39;) {<br>        buffer.write(&#39;&quot;&#39;);<br>        _consume(); // Consume the second quote<br>      } else {<br>        break;<br>      }<br>    } else {<br>      buffer.write(char);<br>    }<br>    char = _consume();<br>  }<br>  return buffer.toString();<br>}</pre><blockquote><em>Me: You’re correct, but that code isn’t.</em></blockquote><p>ChatGPT: Apologies for the confusion. I misunderstood your original concern. Here’s the corrected _readQuotedString method:</p><pre>String _readQuotedString() {<br>  StringBuffer buffer = StringBuffer();<br>  String char = _consume();<br><br>  while (char != null) {<br>    if (char == &#39;&quot;&#39;) {<br>      if (_peek() == &#39;&quot;&#39;) {<br>        _consume(); // Consume the second quote<br>        buffer.write(&#39;&quot;&#39;);<br>      } else {<br>        break;<br>      }<br>    } else {<br>      buffer.write(char);<br>    }<br>    char = _consume();<br>  }<br>  return buffer.toString();<br>}</pre><p>Now the nested strings are correctly parsed. (Let’s ignore the fact that strings in general are not correctly parsed because the lexer doesn’t distinguish them from syntax.)</p><blockquote><em>Me: I think, you forgot to implement typed lists</em></blockquote><p>Just watching the code slowly appearing in the chat windows makes me think that this is too difficult. This is not correct:</p><pre>String _parseTypeName(String token) {<br>  if (token.startsWith(&#39;/&#39;)) {<br>    return token.substring(1);<br>  }<br>  return null;<br>}</pre><p>And this is completely wrong:</p><pre>List&lt;dynamic&gt; _parseTypedList(String type) {<br>  String token = _nextToken();<br>  if (token == &#39;[&#39;) {<br>    List&lt;dynamic&gt; list = _parseList();<br>    list.insert(0, type); // Insert type as the first element<br>    return list;<br>  } else {<br>    throw FormatException(&#39;Expected &quot;[&quot; after type for list&#39;);<br>  }<br>}</pre><p>At least it adds: <em>Note that this implementation doesn’t support type definitions, as the example provided in the specification does not clearly demonstrate how these should be handled.</em></p><p>I, on the other hand, think, the specification is clear. Let’s try again:</p><blockquote><em>Me: I think, you forgot to implement typed lists. I’ll explain the syntax:</em></blockquote><blockquote><em>/name = (a b c) will declare a type &quot;name&quot; with three properties &quot;a&quot;, &quot;b&quot;, and &quot;c&quot;. Such a type definition can only be used on the top-level implicit map.</em></blockquote><blockquote><em>a typed value like </em><em>/(a b c)(1 2 3) is equivalent to </em><em>(a=1 b=2 c=3). Instead of using </em><em>/(a b c) to define a type &quot;inline&quot;, you can also refer to a type name like </em><em>/name(1 2 3) which, using the type definition from below, again create the map value </em><em>(a=1 b=2 c=3).</em></blockquote><blockquote><em>a typed list like </em><em>/(a b c)[(1 2 3) (3 4 5)] applies the type to each element - unless that element is explicitly typed. It is therefore equivalent to </em><em>[/(a b c)(1 2 3) /(a b c)(3 4 5)].</em></blockquote><p>It now (correctly) adds Map&lt;String, List&lt;String&gt;&gt; _types; to the parser to store type definitions and adds a method to parse them. However, it thinks (probably because I reached the token limit) that it lexes /(a b c) as a single token.</p><p>I tried to help with</p><blockquote><em>Me: remember that your </em><em>_TYONLexer class will correctly tokenize </em><em>/(a b c) as six tokens &quot;/&quot;, &quot;(&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;)&quot;.</em></blockquote><p>… but it gets only more wrong. I give up.</p><p>I need to do it myself or start again in a new session. But not today. When creating parsers, I like to work based on a EBNF grammar, so this is my last question:</p><blockquote><em>Me: please write an EBNF grammar for TYON</em></blockquote><pre>TYON          ::= { TypeDecl | KeyValuePair }<br>TypeDecl      ::= &#39;/&#39; Identifier &#39;=&#39; &#39;(&#39; { Identifier } &#39;)&#39;<br>KeyValuePair  ::= Key &#39;=&#39; Value<br>Key           ::= Literal | String<br>Value         ::= Literal | String | List | Map | TypedList | TypedMap<br>Literal       ::= ValidLiteralCharacters<br>String        ::= &#39;&quot;&#39; { AnyCharacterExceptDoubleQuote | &#39;&quot;&quot;&#39; } &#39;&quot;&#39;<br>List          ::= &#39;[&#39; { Value } &#39;]&#39;<br>Map           ::= &#39;(&#39; { KeyValuePair } &#39;)&#39;<br>TypedList     ::= InlineType &#39;[&#39; { Value } &#39;]&#39;<br>TypedMap      ::= TypeReferenceOrInlineType &#39;(&#39; { Value } &#39;)&#39;<br>InlineType    ::= &#39;/&#39; &#39;(&#39; { Identifier } &#39;)&#39;<br>TypeReferenceOrInlineType ::= InlineType | TypeReference<br>TypeReference ::= &#39;/&#39; Identifier<br>Identifier    ::= ValidIdentifierCharacters</pre><p>And this is rather great.</p><p>PS, <a href="https://gist.github.com/sma/cb281758b3dd1d3c1b9f151e6f141c75">here’s the original code</a>, in case somebody is interested.</p><p>PPS: I asked for a more compact lexer using regular expression to split the input into tokens and got this (I only added a final and made it null-safe). This is more to my liking, although the regexp is incorrect. I leave it as an exercise to the reader to fix it ;)</p><pre>class _TYONLexer {<br>  _TYONLexer(String input) : _iterator = _regex.allMatches(input).iterator;<br>  final Iterator&lt;RegExpMatch&gt; _iterator;<br><br>  static final RegExp _regex = RegExp(r&#39;[/()\[\]=]|&quot;(?:[^&quot;]|&quot;&quot;)*&quot;|;[^\n]*|\S+&#39;);<br><br>  String? nextToken() {<br>    if (!_iterator.moveNext()) return null;<br><br>    String token = _iterator.current[0]!;<br>    if (token.startsWith(&#39;;&#39;)) {<br>      return nextToken();<br>    } else if (token.startsWith(&#39;&quot;&#39;) &amp;&amp; token.endsWith(&#39;&quot;&#39;)) {<br>      return token.substring(1, token.length - 1).replaceAll(&#39;&quot;&quot;&#39;, &#39;&quot;&#39;);<br>    } else {<br>      return token;<br>    }<br>  }<br>}</pre><p><em>Originally published at </em><a href="https://gist.github.com/sma/cb281758b3dd1d3c1b9f151e6f141c75"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea6b4bc73ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/a-tyon-implementation-in-dart-written-by-chatgpt-aea6b4bc73ba">A TYON implementation in Dart written by ChatGPT</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reappearing App Bar Titles]]></title>
            <link>https://medium.com/icnh/reappearing-app-bar-titles-eff8b35f6826?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/eff8b35f6826</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 12:32:35 GMT</pubDate>
            <atom:updated>2019-03-21T22:29:11.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*WlYnTFFDb6nQZh_ypxzgmg.png" /><figcaption>I find it difficult to create good looking teaser images</figcaption></figure><p>Flutter’s SliverAppBar makes collapsing headers easy to create. Here is a basic example with a header expanded to 500 points. Instead of displaying a purple color, the FlexibleSpaceBar could of course feature some beautiful imagery. When scrolling, the header shrinks to become the standard AppBar.</p><pre>class HomePage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      drawer: Drawer(),<br>      body: CustomScrollView(<br>        slivers: &lt;Widget&gt;[<br>          SliverAppBar(<br>            primary: true,<br>            pinned: true,<br>            expandedHeight: 500,<br>            flexibleSpace: FlexibleSpaceBar(<br>              background: Container(<br>                color: Colors.purple,<br>              ),<br>            ),<br>          ),<br>          SliverList(<br>            delegate: SliverChildBuilderDelegate(<br>              (BuildContext context, int index) {<br>                return ListTile(<br>                  title: Text(&quot;List tile $index&quot;),<br>                );<br>              },<br>              childCount: 30,<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h4>The Problem We Want to Solve</h4><p>Let’s assume we don’t want to display the title if the header is expanded because that would disturb our beautiful imagery. But if collapsed, the app bar should display it as it would normally. To my knowledge, Flutter has no such behavior by default.</p><p>We can either add a title to the FlexibleSpaceBar which is then displayed at the bottom of the expanded header and animated to the usual position or to the SliverAppBar which then is displayed without animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*vrs8lL6J6kJeC5RW8-wDVg.gif" /><figcaption>Demonstrating both title variants</figcaption></figure><h4>Analyzing The Status Quo</h4><p>I browsed the Flutter source code for inspiration how to create a solution that doesn’t require replacing or modifying large parts of the SliverAppBar source code.</p><p>Fortunately, each widget inside a Scrollable widget can get access to that widget’s scroll position and if adding a listener to that position, it gets notified each time when the user scrolls the Scrollable widget which is a CustomScrollView in our case.</p><p>Also, a SliverAppBar creates a FlexibleSpaceBarSettings contextual widget for its FlexibleSpaceBar to internally get access to the minimum, maximum, and current height. We can use those values to determine whether the app bar is collapsed or not.</p><h4>Developing The Solution</h4><p>I wrap the normal title widget with another widget that only displays the title if it detects a collapsed app bar and hides the title otherwise. I call this wrapper SABT which is short for <em>sliver app bar title</em> (I know, an awful name)<em>.</em></p><p>Because we want to track scrolling using a listener on the scrollable’s position, the SABT needs to be a stateful widget.</p><p>There’s one problem, though. We cannot add the listener in the usual initState method because we cannot access the context at this point of time. It looks like didChangeDependencies is the right method to override. As this method is also called if the widget tree is reconfigured, we need to first remove the listener as shown in the code below. Otherwise we might end up with multiple listeners.</p><p>Here is the complete source code:</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>class SABT extends StatefulWidget {<br>  final Widget child;</pre><pre>  const SABT({<br>    Key key,<br>    <a href="http://twitter.com/required">@required</a> this.child,<br>  }) : super(key: key);</pre><pre>  @override<br>  _SABTState createState() {<br>    return new _SABTState();<br>  }<br>}</pre><pre>class _SABTState extends State&lt;SABT&gt; {<br>  ScrollPosition _position;<br>  bool _visible;</pre><pre>  @override<br>  void dispose() {<br>    _removeListener();<br>    super.dispose();<br>  }</pre><pre>  @override<br>  void didChangeDependencies() {<br>    super.didChangeDependencies();<br>    _removeListener();<br>    _addListener();<br>  }</pre><pre>  void _addListener() {<br>    _position = Scrollable.of(context)?.position;<br>    _position?.addListener(_positionListener);<br>    _positionListener();<br>  }</pre><pre>  void _removeListener() {<br>    _position?.removeListener(_positionListener);<br>  }</pre><pre>  void _positionListener() {<br>    final FlexibleSpaceBarSettings settings =<br>      context.inheritFromWidgetOfExactType(FlexibleSpaceBarSettings);<br>    bool visible = settings == null || settings.currentExtent &lt;= settings.minExtent;<br>    if (_visible != visible) {<br>      setState(() {<br>        _visible = visible;<br>      });<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Visibility(<br>      visible: _visible,<br>      child: widget.child,<br>    );<br>  }<br>}</pre><p>To integrate the SABT with our example, we simple add any title widget wrapped in the SABT widget like so:</p><pre>          SliverAppBar(<br>            primary: true,<br>            pinned: true,<br>            expandedHeight: 500,<br>            title: SABT(child: Text(&quot;The title&quot;)),<br>            flexibleSpace: FlexibleSpaceBar(<br>              background: Container(<br>                color: Colors.purple,<br>              ),<br>            ),<br>          ),</pre><p>If you like, feel free to add some kind of animation to the appearance and/or disappearance of the title by replacing the Visibility widget with for example an AnimatedOpacity widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*VAuqxj8J2WBi7aCxLQ87ag.gif" /><figcaption>Blending titles using AnimatedOpacity widgets</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eff8b35f6826" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/reappearing-app-bar-titles-eff8b35f6826">Reappearing App Bar Titles</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Lisp in less than 2K of Dart Code]]></title>
            <link>https://medium.com/icnh/a-lisp-in-less-than-2k-of-dart-code-950f92725aef?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/950f92725aef</guid>
            <category><![CDATA[interpreters]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[contests]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 12:30:41 GMT</pubDate>
            <atom:updated>2019-03-15T17:32:42.483Z</atom:updated>
            <content:encoded><![CDATA[<p>(Actually, less than 1K)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqVeFL-zWD4smqZWkF1tyQ.png" /></figure><p>For the 5K <strong>Flutter</strong> challenge, I tried to come up with a tiny scripting language implementation that fits in less than 2K. According to Greenspun’s 10th Rule, this had to be a minimal Lisp (or Scheme) interpreter. And according to McCarthy’s famous paper, implementing nine forms (atom, car, cdr, cond, cons, eq, label, lambda, and quote) should do the trick.</p><p>How hard can it be?</p><h3>Some Principles</h3><p>Lisp <em>S-expressions</em> consist of <em>atoms</em> and <em>lists</em> of more S-expressions. Atoms are mostly <em>symbols</em> but the <em>empty list</em> (a.k.a. nil) is also considered to be an atom. To represents symbols, I use Dart Strings, doubles, or bools. Dart’s List type shall represent lists. I don’t use a chain of <em>cons cells</em>. Unfortunately, I have to special case the empty list, for which otherwise the null value would have been the perfect fit.</p><p>The classic factorial implementation looks like this:</p><pre>[&#39;df&#39;, &#39;fac&#39;, [&#39;fn&#39;, [&#39;n&#39;],<br>  [&#39;?&#39;, <br>    [[&#39;=&#39;, &#39;n&#39;, 0], 1],<br>    [true, [&#39;*&#39;, &#39;n&#39;, [&#39;fac&#39;, [&#39;-&#39;, &#39;n&#39;, 1]]]]]]]</pre><p>To save precious characters in my interpreter, I use fn instead of lambda and df instead of define (or label as McCarthy called it). df will only support defining global variables and not functions ([&#39;df&#39;, [&#39;fac&#39;, &#39;n&#39;], ...]). Furthermore, I use = instead of eq and ? instead of cond. As an addition to McCarthy’s implementation, I have numbers and I intend to support * and - (and other arithmetic and comparison operations).</p><p>The eval function evaluates <em>S-expressions</em> (called e), using an <em>environment</em>, often called <em>rho</em> (so I will use r), for which the classic implementation is an association list of cons cells. I will use a Dart Map though, because nothing beats a datatype with a three-letter name.</p><p>Lists are either <em>special forms</em> and evaluated according to special rules described below or <em>regular forms</em> of which the first element is evaluated down to Dart a function which is then called with all other elements evaluated as S-expressions from left to right, forming a new list of argument values.</p><p>This means, internally, in addition to String, double, bool and List, there will also be Map and Function instances used in my interpreter.</p><p>But let’s start simple.</p><h3>Evaluating Values</h3><h4>Atoms</h4><p>By default, any value is evaluated to itself:</p><pre>eval(e, Map r) {<br>  return e;<br>}</pre><p>It’s good style to always write tests, so here are some trivial tests for my trivial implementation (let’s call this reverse test driven development):</p><pre>  test(&#39;atoms&#39;, () {<br>    var r = {};<br>    expect(eval(1, r), equals(1));<br>    expect(eval(false, r), equals(false));<br>    expect(eval([], r), equals([]));<br>  });</pre><h4>Symbols</h4><p>Dart strings, which represent symbols, are evaluated to their bound value in the provided environment, which, as mentioned above, is a Map from strings to any of the supported data types described above.</p><pre>eval(e, Map r) {<br>  if (e is String) return lookup(e, r);<br>  return e;<br>}</pre><pre>lookup(String s, Map r) {<br>  return r[s] ?? lookup(s, r[&#39;&#39;]);<br>}</pre><p>In lookup, we see a neat trick to chain environments as required by the semantics of Scheme. If the current environment doesn’t contain a value, lookup continues the lookup in the parent environment which is stored under the otherwise illegal symbol name &#39;&#39;. If no value is bound, this will result in some ugly runtime error (null does not have a [] method) but that’s the price for a minimal interpreter.</p><p>Here are more unit tests to keep us honest:</p><pre>  group(&#39;symbols&#39;, () {<br>    var r = {&#39;a&#39;: 2};<br>    test(&#39;bound&#39;, () {<br>      expect(eval(&#39;a&#39;, r), equals(2));<br>      expect(eval(&#39;a&#39;, {&#39;&#39;: r}), equals(2));<br>      expect(eval(&#39;a&#39;, {&#39;&#39;: r, &#39;a&#39;: 4}), equals(4));<br>    });<br>    test(&#39;unbound&#39;, () {<br>      expect(() =&gt; eval(&#39;b&#39;, r), throwsError);<br>    });<br>  });</pre><p>Note, my implementation makes null an invalid value which is the reason why I use [] as nil value and not null. Because two non-identical empty List instances aren’t equal in Dart, I have to special case empty lists once I will implement the = function. Here is the code to use:</p><pre>bool isNil(Object e) {<br>  return e is List &amp;&amp; e.isEmpty;<br>}</pre><pre>bool isEqual(Object e1, Object e2) {<br>  return e1 == e2 || isNil(e1) &amp;&amp; isNil(e2);<br>}</pre><h3>Evaluating Lists</h3><p>Non-empty lists are evaluated as follows: If the first element is a symbol denoting one of the four special forms df, fn, ?, or ! (short for quote), we process the special form accordingly. Otherwise, all list elements are evaluated and we expect that the first element evaluates to a Dart function which is then called with the remaining elements evaluated as a new list.</p><pre>eval(e, Map r) {<br>  if (e is String) return lookup(e, r);<br>  if (e is List &amp;&amp; !isNil(e)) return evalList(e, r);<br>  return e;<br>}</pre><pre>evalList(List e, Map r) {<br>  if (e[0] == &#39;!&#39;) return e[1];<br>  e = e.map((e) =&gt; eval(e, r)).toList();<br>  return e[0](e);<br>}</pre><h4>Quotations</h4><p>I started with implementing quote (or ! as I abbreviated it) because it’s the simplest of the special forms. I ignore the case that ! gets passed more than one argument. Let’s declare this is a feature to add comments. Without arguments, an error is thrown, though.</p><pre>  test(&#39;quote&#39;, () {<br>    var r = {&#39;a&#39;: 1};<br>    expect(eval([&#39;!&#39;, 2], r), equals(2));<br>    expect(eval([&#39;!&#39;, &#39;!&#39;], r), equals(&#39;!&#39;));<br>    expect(eval([&#39;!&#39;, &#39;a&#39;], r), equals(&#39;a&#39;));<br>    expect(eval([&#39;!&#39;, [&#39;!&#39;]], r), equals([&#39;!&#39;]));<br>    expect(eval([&#39;!&#39;, [&#39;a&#39;]], r), equals([&#39;a&#39;]));<br>    expect(eval([&#39;!&#39;, []], r), equals([]));<br>    expect(() =&gt; eval([&#39;!&#39;], r), throwsError);<br>  });</pre><h4>Applications</h4><p>I also already implemented normal function application. For this, we shall define the global environment R with car, cdr, cons, cond (which I abbreviate to ?), eq? (abbreviated to =) and atom. Actually, I will implement the negated function, that is list?, because I also need the same test in eval and can share some code this way.</p><pre>Map R = {<br>  &#39;car&#39;: (p) =&gt; p[1][0],<br>  &#39;cdr&#39;: (p) =&gt; p[1].sublist(1),<br>  &#39;cons&#39;: (p) =&gt; [p[1]] + p[2],<br>  &#39;=&#39;: (p) =&gt; isEqual(p[1], p[2]),<br>  &#39;list?&#39;: (p) =&gt; isList(p[1]),<br>};</pre><pre>bool isList(Object e) {<br>  return e is List &amp;&amp; !isNil(e);<br>}</pre><pre>eval(e, Map r) {<br>  if (e is String) return lookup(e, r);<br>  if (isList(e)) return evalList(e, r);<br>  return e;<br>}</pre><h4>car and cdr</h4><p>Here are the tests for car (first element of a list) and cdr (the remaining list without the first element):</p><pre>  test(&#39;car&#39;, () {<br>    expect(eval([&#39;car&#39;, [&#39;!&#39;, [1, 2]]], R), equals(1));<br>    expect(eval([&#39;car&#39;, [&#39;!&#39;, [2]]], R), equals(2));<br>    expect(() =&gt; eval([&#39;car&#39;, [&#39;!&#39;, []]], R), throwsError);<br>    expect(() =&gt; eval([&#39;car&#39;], R), throwsError);<br>  });</pre><pre>  test(&#39;cdr&#39;, () {<br>    expect(eval([&#39;cdr&#39;, [&#39;!&#39;, [1, 2]]], R), equals([2]));<br>    expect(eval([&#39;cdr&#39;, [&#39;!&#39;, [2]]], R), equals([]));<br>    expect(() =&gt; eval([&#39;cdr&#39;, [&#39;!&#39;, []]], R), throwsError);<br>    expect(() =&gt; eval([&#39;cdr&#39;, [&#39;!&#39;, 1]], R), throwsError);<br>    expect(() =&gt; eval([&#39;cdr&#39;], R), throwsError);<br>  });</pre><h4>cons</h4><p>Note, that for cons, I do not support <em>dotted pairs</em> (that is, the second argument must always be a list (empty or non-empty) and cannot be any other atom):</p><pre>  test(&#39;cons&#39;, () {<br>    expect(eval([&#39;cons&#39;, 3, [&#39;!&#39;, [1, 2]]], R), equals([3, 1, 2]));<br>    expect(eval([&#39;cons&#39;, 3, [&#39;!&#39;, []]], R), equals([3]));<br>    expect(() =&gt; eval([&#39;cons&#39;, 3, 4], R), throwsError);<br>    expect(() =&gt; eval([&#39;cons&#39;, 3], R), throwsError);<br>    expect(() =&gt; eval([&#39;cons&#39;], R), throwsError);<br>  });</pre><h4>=</h4><p>Note, that = will consider (as discussed above) two empty lists to be equal, but non-identical non-empty lists are never equal. I think, this is how eq? traditionally behaves.</p><pre>group(&#39;=&#39;, () {<br>    test(&#39;equal&#39;, () {<br>      expect(eval([&#39;=&#39;, [], []], R), equals(true));<br>      expect(eval([&#39;=&#39;, 0, 0], R), equals(true));<br>      expect(eval([&#39;=&#39;, false, false], R), equals(true));<br>      expect(eval([&#39;=&#39;, [&#39;!&#39;, &#39;a&#39;], [&#39;!&#39;, &#39;a&#39;]], R), equals(true));<br>    });<br>    test(&#39;unequal&#39;, () {<br>      expect(eval([&#39;=&#39;, [], [&#39;!&#39;, [1]]], R), equals(false));<br>      expect(eval([&#39;=&#39;, 0, 1], R), equals(false));<br>      expect(eval([&#39;=&#39;, true, false], R), equals(false));<br>      expect(eval([&#39;=&#39;, [&#39;!&#39;, &#39;a&#39;], [&#39;!&#39;, &#39;b&#39;]], R), equals(false));<br>      expect(eval([&#39;=&#39;, [&#39;!&#39;, [1]], [&#39;!&#39;, [1]]], R), equals(false));<br>      expect(eval([&#39;=&#39;, [&#39;!&#39;, [1]], [&#39;!&#39;, [2]]], R), equals(false));<br>    });<br>    test(&#39;errors&#39;, () {<br>      expect(() =&gt; eval([&#39;=&#39;, 3], R), throwsError);<br>      expect(() =&gt; eval([&#39;=&#39;], R), throwsError);<br>    });<br>  });</pre><h4>list?</h4><p>The last function to create unit tests for is list? which tests for non-empty lists:</p><pre>  test(&#39;list?&#39;, () {<br>    expect(eval([&#39;list?&#39;, [&#39;!&#39;, [1, 2]]], R), equals(true));<br>    expect(eval([&#39;list?&#39;, [&#39;cons&#39;, 1, []]], R), equals(true));<br>    expect(eval([&#39;list?&#39;, []], R), equals(false));<br>    expect(eval([&#39;list?&#39;, false], R), equals(false));<br>    expect(eval([&#39;list?&#39;, 0], R), equals(false));<br>    expect(eval([&#39;list?&#39;, [&#39;!&#39;, &#39;a&#39;]], R), equals(false));<br>    expect(() =&gt; eval([&#39;list?&#39;], R), throwsError);<br>  });</pre><p>Right now, my implementation needs only 670 characters — including all whitespace that could (and probably should) be stripped for a fair measurement. This feels good.</p><h3>Conditionals</h3><p>Let’s implement the next special form: cond (or ? as I call it).</p><p>But before that, I introduce a variant of eval called evalN which evaluates a sequence of expressions and which returns the result of the last evaluation. Without S-expressions, nil is returned.</p><pre>evalN(Iterable e, Map r) {<br>  return e.fold([], (_, e) =&gt; eval(e, r));<br>}</pre><p>The ? special form will take any number of S-expressions which must be lists that start with a predicate (something that evaluates to a boolean value) and continue with any number of S-expressions which are then evaluated by evalN. I add the code to evalList:</p><pre>evalList(List e, Map r) {<br>  if (e[0] == &#39;!&#39;) return e[1];<br>  if (e[0] == &#39;?&#39;) {<br>    for (e in e.skip(1))<br>      if (eval(e[0], r)) return evalN(e.skip(1), r);<br>    return [];<br>  }<br>  e = e.map((e) =&gt; eval(e, r)).toList();<br>  return e[0](e);<br>}</pre><p>It’s funny how the unit tests are much larger than the actual implementation:</p><pre>  group(&#39;cond&#39;, () {<br>    var r = {&#39;&#39;: R, &#39;a&#39;: 1};<br>    test(&#39;empty&#39;, () {<br>      expect(eval([&#39;?&#39;], r), equals([]));<br>    });<br>    test(&#39;single true&#39;, () {<br>      expect(eval([&#39;?&#39;, [true, 1]], r), equals(1));<br>      expect(eval([&#39;?&#39;, [true]], r), equals([]));<br>    });<br>    test(&#39;single false&#39;, () {<br>      expect(eval([&#39;?&#39;, [false, 1]], r), equals([]));<br>      expect(eval([&#39;?&#39;, [false]], r), equals([]));<br>    });<br>    test(&#39;first true&#39;, () {<br>      expect(eval([&#39;?&#39;, [true, 1], [true, 2]], r), equals(1));<br>      expect(eval([&#39;?&#39;, [true, 1], [false, 2]], r), equals(1));<br>    });<br>    test(&#39;second true&#39;, () {<br>      expect(eval([&#39;?&#39;, [false, 1], [true, 2]], r), equals(2));<br>    });<br>    test(&#39;multiple cases&#39;, () {<br>      expect(eval([&#39;?&#39;, <br>        [[&#39;=&#39;, &#39;a&#39;, 0], 0], <br>        [[&#39;=&#39;, &#39;a&#39;, 1], 1],<br>        [[&#39;=&#39;, &#39;a&#39;, 2], 2]], r), equals(1));<br>    });<br>    test(&#39;errors&#39;, () {<br>      expect(() =&gt; eval([&#39;?&#39;, 3], r), throwsError);<br>      expect(() =&gt; eval([&#39;?&#39;, []], r), throwsError);<br>    });<br>  });</pre><p>BTW, I also experimented with replacing the for loop by a clever <em>iterable expression</em>, but the result gets longer than the straight forward solution (mainly because of the cast I had to introduce — otherwise the Dart compiler insists in e being of type List&lt;String&gt;):</p><pre>    return evalN(e.cast&lt;dynamic&gt;().skip(1).firstWhere(<br>        (e) =&gt; eval(e[0], r), <br>        orElse: () =&gt; [[]]).skip(1), r);</pre><h3>User-Defined Functions</h3><p>Let’s tackle fn next. This returns a Dart Function which, when called like all other built-in functions, will create a new environment chained to the environment present at the time of the definition of fn in which the formal parameters of fn are bound to the evaluated arguments. And because I don’t use cons cells, I don’t have <em>improper lists</em> and therefore cannot use the same syntax as Scheme for a rest argument. Therefore, the special parameter name &amp; plays this role.</p><p>The implementation is added to evalList as before:</p><pre>evalList(List e, Map r) {<br>  ...<br>  if (e[0] == &#39;fn&#39;) {<br>    var f = [e[0]] + e[1];<br>    return (p) {<br>      Map n = {&#39;&#39;: r};<br>      for (var i = 1; i &lt; f.length; i++)<br>        n[f[i]] = f[i] == &#39;&amp;&#39; ? p.sublist(i) : p[i];<br>      return evalN(e.skip(2), n);<br>    };<br>  }<br>  e = e.map((e) =&gt; eval(e, r)).toList();<br>  return e[0](e);<br>}</pre><p>Instead of the for loop, I’d love to have used something like zip(f, p) but Dart has no such function — probably because Dart has no statically typed tuple type. This makes me sad…</p><p>Let’s break it down:</p><ul><li>e[0] is the symbol fn.</li><li>e[1] must be a list of formal parameters which must be symbols (not checked).</li><li>f is the list of formal parameters with a dummy first element so that it matches the arguments. I use e[0] instead of something shorter because Dart’s <em>type inference</em> otherwise is too clever and mistypes my list.</li><li>e[2],... are the function’s body.</li><li>r is the defining environment.</li><li>n is the new environment that is freshly created each time the defined function is called.</li><li>p contains the arguments for such a call. Note, that p[0] is the function value itself, that is, the first argument is p[1].</li><li>The for loop binds all <em>actuals</em> to <em>formals</em>.</li><li>The &amp; is special cased and expected to be the last formal parameter.</li><li>I also expect to get at least as many arguments as there are formals. We could use i &lt; p.length ? p[i] : [] but I think, it’s better to throw an error if expected arguments are missing.</li></ul><p>Note, I could access the formals only inside the loop (saving some bytes) but then I don’t get an error if I mess up the fn declaration before I actually call the function. Therefore I define f outside of the Dart function literal.</p><p>I wrote a lot of tests to make sure functions work as expected:</p><pre>  group(&#39;fn&#39;, () {<br>    test(&#39;is a function&#39;, () {<br>      expect(eval([&#39;fn&#39;, []], R), TypeMatcher&lt;Function&gt;());<br>    });<br>    test(&#39;empty&#39;, () {<br>      expect(eval([[&#39;fn&#39;, []]], R), equals([]));<br>    });<br>    test(&#39;with body&#39;, () {<br>      expect(eval([[&#39;fn&#39;, [], 3]], R), equals(3));<br>      expect(eval([[&#39;fn&#39;, [], 3, 4]], R), equals(4));<br>    });<br>    test(&#39;single param&#39;, () {<br>      var r = {&#39;&#39;: R, &#39;a&#39;: 1};<br>      expect(eval([[&#39;fn&#39;, [&#39;a&#39;], &#39;a&#39;], 2], r), equals(2));<br>    });<br>    test(&#39;two params&#39;, () {<br>      var r = {&#39;&#39;: R, &#39;a&#39;: 1};<br>      expect(eval([[&#39;fn&#39;, [&#39;a&#39;, &#39;b&#39;], <br>        [&#39;cons&#39;, &#39;b&#39;, [&#39;cons&#39;, &#39;a&#39;, []]]], 3, 4], r), equals([4, 3]));<br>    });<br>    test(&#39;rest param&#39;, () {<br>      expect(eval([[&#39;fn&#39;, [&#39;a&#39;, &#39;&amp;&#39;], &#39;&amp;&#39;], 1], R), equals([]));<br>      expect(eval([[&#39;fn&#39;, [&#39;a&#39;, &#39;&amp;&#39;], &#39;&amp;&#39;], 1, 2], R), equals([2]));<br>      expect(eval([[&#39;fn&#39;, [&#39;a&#39;, &#39;&amp;&#39;], &#39;&amp;&#39;], 1, 2, 3], R), equals([2, 3]));<br>    });<br>    test(&#39;closure &#39;, () {<br>      var r = {&#39;&#39;: R, &#39;a&#39;: 1};<br>      R[&#39;f&#39;] = eval([&#39;fn&#39;, [], &#39;a&#39;], r);<br>      expect(eval([&#39;f&#39;], r), equals(1));<br>      r[&#39;a&#39;] = 2;<br>      expect(eval([&#39;f&#39;], r), equals(2));<br>      r = {&#39;&#39;: R, &#39;a&#39;: 3};<br>      expect(eval([&#39;f&#39;], r), equals(2));<br>    });<br>    test(&#39;needs formals&#39;, () {<br>      expect(() =&gt; eval([&#39;fn&#39;], R), throwsError);<br>      expect(() =&gt; eval([&#39;fn&#39;, 1], R), throwsError);<br>    });<br>    test(&#39;needs enough arguments&#39;, () {<br>      expect(() =&gt; eval([[&#39;fn&#39;, [&#39;a&#39;]]], R), throwsError);<br>    });<br>  });</pre><h3>Binding Values</h3><p>The last missing piece is df to define a global variable (that is, create a new binding or overwrite an existing one in the global environment R):</p><pre>evalList(List e, Map r) {<br>  ...<br>  if (e[0] == &#39;df&#39;) return R[e[1]] = evalN(e.skip(2), r);<br>  e = e.map((e) =&gt; eval(e, r)).toList();<br>  return e[0](e);<br>}</pre><p>It’s a one-liner. I’m actually using evalN instead of eval because I can. I’m not sure whether it is useful to allow multiple expressions for defining something, but as a neat side effect, [&#39;df&#39;, &#39;x&#39;] sets x to nil.</p><p>By changing R to r I could change the semantics to define local variables, but I think, this is not the way define is supposed to work in Scheme.</p><p>Here are the unit tests:</p><pre>test(&#39;df&#39;, () {<br>    eval([&#39;df&#39;, &#39;a&#39;, 1], R);<br>    expect(R[&#39;a&#39;], equals(1));<br>    eval([&#39;df&#39;, &#39;b&#39;], R);<br>    expect(R[&#39;b&#39;], equals([]));<br>    expect(() =&gt; eval([&#39;df&#39;], R), throwsError);<br>  });</pre><p>And … we’re done.</p><p>This is the complete interpreter for minimal a Scheme-like programming language implemented with 1132 characters in Dart:</p><pre>Map R = {<br>  &#39;car&#39;: (p) =&gt; p[1][0],<br>  &#39;cdr&#39;: (p) =&gt; p[1].sublist(1),<br>  &#39;cons&#39;: (p) =&gt; [p[1]] + p[2],<br>  &#39;=&#39;: (p) =&gt; isEqual(p[1], p[2]),<br>  &#39;list?&#39;: (p) =&gt; isList(p[1]),<br>};</pre><pre>evalN(Iterable e, Map r) {<br>  return e.fold([], (_, e) =&gt; eval(e, r));<br>}</pre><pre>eval(e, Map r) {<br>  if (e is String) return lookup(e, r);<br>  if (isList(e)) return evalList(e, r);<br>  return e;<br>}</pre><pre>evalList(List e, Map r) {<br>  if (e[0] == &#39;!&#39;) return e[1];<br>  if (e[0] == &#39;?&#39;) {<br>    for (e in e.skip(1)) <br>      if (eval(e[0], r)) return evalN(e.skip(1), r);<br>    return [];<br>  }<br>  if (e[0] == &#39;fn&#39;) {<br>    var f = [e[0]] + e[1];<br>    return (p) {<br>      Map n = {&#39;&#39;: r};<br>      for (var i = 1; i &lt; f.length; i++) <br>        n[f[i]] = f[i] == &#39;&amp;&#39; ? p.sublist(i) : p[i];<br>      return evalN(e.skip(2), n);<br>    };<br>  }<br>  if (e[0] == &#39;df&#39;) return R[e[1]] = evalN(e.skip(2), r);<br>  e = e.map((e) =&gt; eval(e, r)).toList();<br>  return e[0](e);<br>}</pre><pre>lookup(String s, Map r) {<br>  return r[s] ?? lookup(s, r[&#39;&#39;]);<br>}</pre><pre>bool isNil(Object e) {<br>  return e is List &amp;&amp; e.isEmpty;<br>}</pre><pre>bool isEqual(Object e1, Object e2) {<br>  return e1 == e2 || isNil(e1) &amp;&amp; isNil(e2);<br>}</pre><pre>bool isList(Object e) {<br>  return e is List &amp;&amp; !isNil(e);<br>}</pre><h3>Factorial Example</h3><p>We can run the factorial example if we define * and -:</p><pre>void main() {<br>  eval([&#39;df&#39;, &#39;*&#39;, (p) =&gt; p[1] * p[2]], R);<br>  eval([&#39;df&#39;, &#39;-&#39;, (p) =&gt; p[1] - p[2]], R);<br>  eval([&#39;df&#39;, &#39;fac&#39;, [&#39;fn&#39;, [&#39;n&#39;],<br>    [&#39;?&#39;, <br>      [[&#39;=&#39;, &#39;n&#39;, 0], 1],<br>      [true, [&#39;*&#39;, &#39;n&#39;, [&#39;fac&#39;, [&#39;-&#39;, &#39;n&#39;, 1]]]]]]], R);<br>  print(eval([&#39;fac&#39;, 10], R));<br>}</pre><p>This should print 3628800.</p><h3>No Special Forms</h3><p>As you saw, adding new primitive functions like + is very easy. But what if I want to add new special forms, let’s say a let statement that makes it easier to define temporary variables?</p><p>Therefore, I make evaluation more uniform and add special forms to the global environment, too. To distinguish them from normal function, I wrap them in Set literals. This way I can use is Set to detect them. Creating my own class would require more characters. Using a Set literal requires Dart 2.2 but I think, this is no problem at all.</p><p>Here is the extended environment:</p><pre>Map R = {<br>  &#39;car&#39;: (p) =&gt; p[0][0],<br>  &#39;cdr&#39;: (p) =&gt; p[0].sublist(1),<br>  &#39;cons&#39;: (p) =&gt; [p[0]] + p[1],<br>  &#39;=&#39;: (p) =&gt; isEqual(p[0], p[1]),<br>  &#39;list?&#39;: (p) =&gt; isList(p[0]),<br>  &#39;!&#39;: {(e, r) =&gt; e[1]},<br>  &#39;?&#39;: {q},<br>  &#39;fn&#39;: {f},<br>  &#39;df&#39;: {(e, r) =&gt; R[e[1]] = evalN(e.skip(2), r)},<br>};</pre><pre>q(List e, Map r) {<br>  for (e in e.skip(1)) if (eval(e[0], r)) return evalN(e.skip(1), r);<br>  return [];<br>}</pre><pre>f(List e, Map r) {<br>  List f = e[1];<br>  return (p) {<br>    Map x = {&#39;&#39;: r};<br>    for (var i = 0; i &lt; f.length; i++) x[f[i]] = f[i] == &#39;&amp;&#39; ? p.sublist(i) : p[i];<br>    return evalN(e.skip(2), x);<br>  };<br>}</pre><p>Note, that I’m now using 0-based parameter lists, not 1-based as before. Because of this, I have to change my factorial example which used this implementation detail for * and -. And I had to change the unit tests for ! which didn’t use the global environment. Perhaps ! should be a special case of the special case and built-in? I don’t know.</p><p>Here is the new evalList implementation:</p><pre>evalList(List e, Map r) {<br>  var f = eval(e[0], r);<br>  return f is Set <br>    ? f.first(e, r) <br>    : f(e.skip(1).map((e) =&gt; eval(e, r)).toList());<br>}</pre><p>I’m now counting 1160 characters for the whole interpreter. I noticed that I’m using `isEqual` only once. This can be inlined and the interpreter uses only 1098 characters now.</p><h3>Shrinking the Code</h3><p>Let’s take it to the next level.</p><p>I can remove all type annotation and relay only on implicit dynamic types. I’m down to 1019 characters and code looks now like this:</p><pre>...</pre><pre>evalN(e, r) {<br>  return e.fold([], (_, e) =&gt; eval(e, r));<br>}</pre><pre>eval(e, r) {<br>  if (e is String) return lookup(e, r);<br>  if (isList(e)) return evalList(e, r);<br>  return e;<br>}</pre><pre>...</pre><p>Most Dart function are one liners and I can use <em>expression bodies</em> instead of <em>block bodies</em>. Now, only 947 characters are required to implement by interpreter.</p><p>Can we also remove the var declaration from this 125 characters function so that we can remove the <em>block body</em>?</p><pre>evalList(e, r) {<br>  var f = eval(e[0], r);<br>  return f is Set ? f.first(e, r) : f(e.skip(1).map((e) =&gt; eval(e, r)).toList());<br>}</pre><p>Sure. I introduce an anonymous function. This one-liner (only formatted here for readability) needs only 114 characters (saving 11 precious characters):</p><pre>evalList(e, r) =&gt; ((f) =&gt; f is Set <br>  ? f.first(e, r) <br>  : f(e.skip(1).map((e) =&gt; eval(e, r)).toList()))<br>    (eval(e[0], r));</pre><p>And I will use the same trick in this 185 characters function:</p><pre>f(e, r) {<br>  List f = e[1];<br>  return (p) {<br>    Map n = {&#39;&#39;: r};<br>    for (var i = 0; i &lt; f.length; i++) <br>      n[f[i]] = f[i] == &#39;&amp;&#39; ? p.sublist(i) : p[i];<br>    return evalN(e.skip(2), n);<br>  };<br>}</pre><p>Unfortunately, this will add one character because of the indentation, but once I’ve stripped all whitespace, it should be more compact:</p><pre>f(e, r) =&gt; ((List f) =&gt; (p) {<br>      Map n = {&#39;&#39;: r};<br>      for (var i = 0; i &lt; f.length; i++)<br>        n[f[i]] = f[i] == &#39;&amp;&#39; ? p.sublist(i) : p[i];<br>      return evalN(e.skip(2), n);<br>    })(e[1]);</pre><p>I’m now down to 937 characters. Let’s rename isNil to n and isList to il and lookup to l. I keep only eval and evalN because that’s my API. This saves 43 additional characters.</p><p>Because evalList is used only once, I can inline it and save 26 more characters. Including whitespace, the code needs 867 characters and the unit tests are still running.</p><h4>Stripping Whitespace</h4><p>Until now, I’ve always used the Dart formatter to get a canonical representation of my code. Let’s change that and strip every whitespace that isn’t required for the final step to make this as small as possible.</p><p>I’m arriving at 666 characters (broken down into multiple lines just to display it here):</p><pre>Map R={&#39;car&#39;:(p)=&gt;p[0][0],&#39;cdr&#39;:(p)=&gt;p[0].sublist(1),&#39;cons&#39;:(p)=&gt;<br>[p[0]]+p[1],&#39;=&#39;:(p)=&gt;p[0]==p[1]||n(p[0])&amp;&amp;n(p[1]),&#39;list?&#39;:(p)=&gt;il<br>(p[0]),&#39;!&#39;:{(e,r)=&gt;e[1]},&#39;?&#39;:{q},&#39;fn&#39;:{f},&#39;df&#39;:{(e,r)=&gt;R[e[1]]=ev<br>alN(e.skip(2),r)},};q(e,r){for(e in e.skip(1))if(eval(e[0],r))ret<br>urn evalN(e.skip(1),r);return[];}f(e,r)=&gt;((List f)=&gt;(p){Map n={&#39;&#39;<br>:r};for(var i=0;i&lt;f.length;i++)n[f[i]]=f[i]==&#39;&amp;&#39;?p.sublist(i):p[i<br>];return evalN(e.skip(2),n);})(e[1]);evalN(e,r)=&gt;e.fold([],(_,e)=<br>&gt;eval(e,r));eval(e,r)=&gt;e is String?l(e,r):il(e)?((f)=&gt;f is Set?f.<br>first(e,r):f(e.skip(1).map((e)=&gt;eval(e,r)).toList()))(eval(e[0],r<br>)):e;l(s,r)=&gt;r[s]??l(s,r[&#39;&#39;]);n(e)=&gt;e is List&amp;&amp;e.isEmpty;il(e)=&gt;e<br> is List&amp;&amp;!n(e);</pre><p>What a beauty :-)</p><p>And the unit tests still run for this blob of code. I feel I’m done. This was a fun experiment, even if I eventually decided against using a Scheme-like interpreter for my project.</p><p><strong>PS:</strong> I tried to prove the metacircularity (if that’s a word?) of my interpreter by implementing it again in itself but it was too tedious to make it work because it seems, McCarthy’s original relays on the fact, that everything but nil is true and that calling car with not a list is no error but nil, that is, false.</p><p>If you want to experiment yourself, here’s my read function to convert a string into a list of S-expressions in 427 characters, still with wordy error messages included.</p><pre>read(s){var i=RegExp(r&quot;[&#39;()]|[^\s&#39;()]+&quot;).allMatches(s).map((m)=&gt;m<br>[0]).iterator;c()=&gt;i.current;n()=&gt;i.moveNext();e(){if(c()==&quot;&#39;&quot;){n<br>();return[&#39;!&#39;,e()];}if(c()==&#39;(&#39;){n();var l=[];while(c()!=&#39;)&#39;){if(<br>c()==null)throw &#39;missing )&#39;;l.add(e());}n();return l;}if(c()==&#39;)&#39;<br>)throw &#39;unbalanced )&#39;;if(c()==null)throw &#39;missing expr&#39;;var atom=<br>c();n();return double.tryParse(atom)??atom;}n();var l=[];while(c(<br>)!=null)l.add(e());return l;}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950f92725aef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/a-lisp-in-less-than-2k-of-dart-code-950f92725aef">A Lisp in less than 2K of Dart Code</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Cloud Functions In Dart]]></title>
            <link>https://medium.com/icnh/writing-cloud-functions-in-dart-b7e62192b3bc?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/b7e62192b3bc</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Mon, 11 May 2020 15:28:30 GMT</pubDate>
            <atom:updated>2020-06-01T09:35:05.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2SLmWfLsmaKxevXB" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Can you write <a href="https://firebase.google.com/docs/functions">Firebase Cloud Functions</a> in <a href="https://dart.dev/">Dart</a>?</p><p>Yes you can and here is how.</p><blockquote>The article has been updated to Firebase CLI version 8.4.</blockquote><h3>Firebase Setup</h3><p>Install <a href="https://nodejs.org/en/">Node.js</a> and the <a href="https://firebase.google.com/docs/cli?#setup_update_cli">Firebase CLI</a> if you haven’t done so already:</p><pre>npm install -g firebase-tools</pre><p>Then, log into the <a href="https://console.firebase.google.com/">Firebase Console</a> and create a new project (or pick one you want to use). Because later in this tutorial, we will demonstrate a function that accesses the <a href="https://firebase.google.com/docs/firestore">Cloud Firestore</a>, create such a database in your prefered region and remember that region. You must deploy your functions in the same region as your database if you don’t want to pay for the data traffic between different regions!</p><p>Back on the terminal, also log into Firebase here:</p><pre>firebase login</pre><p>Then, last but not least, setup the functions project in your current directory:</p><pre>firebase init functions</pre><p>Choose the Firebase project you created earlier and pick “JavaScript” as language and deselect “ESLint” (which we don’t need as we don’t write JavaScript on our own). Then allow firebase to download all dependencies via npm and wait while it downloads half of the internet.</p><p>This process created an empty firebase.json file and a directory called functions which contains a typical node project with a package.json file, a node_modules directory and an index.js file which contains a “hello world” example.</p><p>Open index.js and uncomment the example code. Then test the created function to make sure, your setup was successful, running:</p><pre>npm run serve</pre><p>The Firebase emulator should print the URL to access the cloud function. On my machine this is <a href="http://localhost:5001/brettspielspielbrett/us-central1/helloWorld">http://localhost:5001/&lt;projectname&gt;/us-central1/helloWorld</a>. It also starts a fancy web UI for its emulator on <a href="http://localhost:4000/">http://localhost:4000/</a>. It will even automatically pick up changes to index.js while running which is quite nice. Eventually, stop the server.</p><h3>Switch to Dart</h3><p>Next, setup the Dart project.</p><p><a href="https://dart.dev/tutorials/server/get-started#2-install-dart">Install the Dart SDK</a> if you haven’t done so already.</p><p>Create a new pubspec.yaml file in the functions directory with the following content:</p><pre>name: functions<br>version: 1.0.0</pre><pre>environment:<br>  sdk: ‘&gt;=2.8.0 &lt;3.0.0’</pre><pre>dependencies:<br>  firebase_functions_interop: ^1.0.2</pre><pre>dev_dependencies:<br>  build_runner: ^1.9.0<br>  build_node_compilers: ^0.2.4</pre><p>Run pub get to download all dependencies.</p><p>Create a directory called node and create a file called index.dart inside that folder that looks like this:</p><pre>import &#39;package:firebase_functions_interop/firebase_functions_interop.dart&#39;;</pre><pre>void main() {<br>  functions[‘moin’] = functions<br>    .region(&#39;europe-west3&#39;)<br>    .https.onRequest(greet);<br>}</pre><pre>void greet(ExpressHttpRequest request) {<br>  request.response<br>    ..writeln(&#39;Moin, moin!&#39;)<br>    ..close();<br>}</pre><p><strong>Note:</strong> You must replace europe-west3 with your region or omit that line.</p><p>Create another file called build.yaml with this content:</p><pre>targets:<br>  $default:<br>    sources:<br>      — node/**<br>      — lib/**<br>    builders:<br>      build_node_compilers|entrypoint:<br>        options:<br>          compiler: dart2js</pre><p>Add these lines to .gitignore:</p><pre>ui-debug.log<br>build/<br>.dart_tool/<br>.packages</pre><p>Now run</p><pre>pub run build_runner build -o node:build</pre><p>This converts node/index.dart to build/index.dart.js. The convention, to use a node directory instead of the usual bin directory has been built into the NodeJS wrapper package that is used internally. It does the heavy-lifting of translating Dart to JavaScript. You can add more Dart files to lib if you like.</p><p>Then change package.json and add:</p><pre>  &quot;main&quot;: &quot;build/index.dart.js&quot;</pre><p>You can remove index.js. The JavaScript reign is about to end.</p><p>Next, run npm run serve again. When accessing the shown URL, the text “Moin, moin!” should be displayed. We successfully created a cloud function in Dart! Eventually, stop the server.</p><h3>Deploying the Function</h3><p>Replace the content of firebase.json with this content:</p><pre>{<br>  &quot;functions&quot;: {<br>    &quot;ignore&quot;: [<br>      &quot;.dart_tool&quot;,<br>      &quot;.packages&quot;,<br>      &quot;**/build/*.map&quot;,<br>      &quot;**/build/packages&quot;,<br>      &quot;build.yaml&quot;,<br>      &quot;node&quot;,<br>      &quot;node_modules&quot;,<br>      &quot;pubspec.*&quot;<br>    ]<br>  }<br>}</pre><p>Let’s now deploy the cloud function to Firebase:</p><pre>npm run deploy</pre><p>Your function should be live now.</p><p>Please notice that by default, the package.json is configured to use Node.js version 8. This version will soon be disabled by Google. You must switch to version 10. However, you will have then to pay for using this version.</p><h3>Development Workflow</h3><p>To develop locally, use watch instead of build like so:</p><pre>pub run build_runner watch -o node:build</pre><p>and — in a second terminal — run:</p><pre>npm run serve</pre><p>Then change the Dart source and observe the build_runner to recompile the Dart source and the Firebase development server to reload the JavaScript function. Now, you’re ready to leave the JavaScript world behind and only use Dart for both your client and server development. Happy times!</p><h3>Firestore Integration</h3><p>Let’s define a Firestore trigger which will automatically be called every time a new document is add to the foo collection. It creates a similar document in the bar collection that has the same name property as the document in foo.</p><p>First, initialize, download and run the Firestore emulator:</p><pre>firebase init emulators<br>firebase emulators:start</pre><p>A fancy UI is available on <a href="http://localhost:4000/">http://localhost:4000/</a>.</p><p>Now replace index.dart with the following code and make sure that the Dart build_runner is still watching you.</p><pre>import &#39;package:firebase_functions_interop/firebase_functions_interop.dart&#39;;</pre><pre>void main() {<br>  functions[&#39;foo&#39;] = functions<br>    .region(&#39;europe-west3&#39;)<br>    .firestore.document(&#39;/foo/{id}&#39;).onCreate(createHook);<br>}</pre><pre>Future&lt;void&gt; createHook(DocumentSnapshot snapshot, EventContext context) async {<br>  final name = snapshot.data.getString(&#39;name&#39;);<br>  final data = DocumentData.fromMap({&#39;name&#39;: name});<br>  await snapshot.firestore.collection(&#39;/bar&#39;).add(data);<br>}</pre><p><strong>Note:</strong> Make sure that the function runs in the same region as your datastore! Also notice that the store region name and the function region name might not be identical.</p><p>As both the Firebase emulator and the build watcher are running, saving the Dart file should automatically (re)reploy your function and and you’re good to go and test it buy manually creating a new document in foo, adding at least a name property to that document. Then switch to bar and observe that our function has successfully created a document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O-6mmbppPqMLC40--USXg.png" /></figure><p>For the last time, deploy:</p><pre>npm run deploy</pre><p>Now go to Firebase console, open your Firestore database and test the trigger by creating a foo/&lt;id&gt; document with a name property and observe the creation of a new bar/&lt;id&gt; docment with a similar name property. &lt;id&gt; stands for the automatically created document identifier.</p><h3>Conculsion</h3><p>At ICNH, we’re building <a href="https://flutter.dev/">Flutter</a> apps for fun and profit and we love to use Firebase as a simple to use backend. It is very well integrated with Flutter because Google provides ready to use packages most aspects of Firebase. For most mobile application, we also have to customize the server part. Using the same programming language for server development as for client development really helps to make this process much nicer.</p><p>We successfully created a custom backend for a Flutter app using only Dart.</p><h3>Source code</h3><p><a href="https://github.com/icnh/dart_cloud_functions_example">icnh/dart_cloud_functions_example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7e62192b3bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/writing-cloud-functions-in-dart-b7e62192b3bc">Writing Cloud Functions In Dart</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Errors Messages for Flutter]]></title>
            <link>https://medium.com/icnh/better-errors-messages-for-flutter-a21c53982a99?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/a21c53982a99</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Fri, 08 May 2020 09:28:01 GMT</pubDate>
            <atom:updated>2020-05-08T09:40:40.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fyjMIeuWBEbrp7OjaoM3Q.png" /><figcaption>Imagine that it’s blinking…</figcaption></figure><p>… is probably an article I should have published on April 1st. Still, here it is. The <a href="https://en.wikipedia.org/wiki/Amiga">Amiga</a> had an iconic way to display fatal errors: The <a href="https://en.wikipedia.org/wiki/Guru_Meditation">guru meditation</a> alert. Let’s recreate this for Flutter.</p><p>Here is how I want to display the alert:</p><pre>showAlert(context, 42);</pre><p>Instead of complicated and talkative text messages, I will display succient hexadecimal error codes which need no translation or localization. I’m utterly convinced that this is the future.</p><pre>import &#39;package:flutter/widgets.dart&#39;;</pre><pre>void showAlert(BuildContext context, int code) {<br>  final hex = code.toRadixString(16).toUpperCase().padLeft(8, &#39;0&#39;);</pre><pre>  ...</pre><pre>}</pre><p>Notice, how I not try to include a library for left-padding my string for improved stability and protection against rage-quitting developers.</p><p>To display anything above the normal UI, an OverlayEntry which is then added to the current Overlay can be used. The such an Overlay is automatically created as part of a WidgetsApp or MaterialApp widget. The overlay entry must be explicitly removed again. I’m using a GestureDetector so that the user has to tap the overlay to make it go away.</p><pre>void showAlert(BuildContext context, int code) {<br>  final hex = code.toRadixString(16).toUpperCase().padLeft(8, &#39;0&#39;);<br>  final black = Color(0xFF000000);<br>  final red = Color(0xFFFF0000);<br>  OverlayEntry overlay;<br>  overlay = OverlayEntry(builder: (context) {<br>    return Positioned(<br>      left: 0,<br>      right: 0,<br>      child: GestureDetector(<br>        onTap: () =&gt; overlay.remove(),<br>        child: Container(<br>          color: black,<br>          height: 128,<br>        ),<br>      ),<br>    );<br>  });<br>  Overlay.of(context).insert(overlay);<br>}</pre><p>Because I don’t want to depend on material.dart I create my own Color objects. And because I need to refer to the overlay variable inside of the onTap handler of the builder function I cannot use the usual final variable definition that declares and initializes a variable in one step. Overlays are a bit special.</p><p>The Overlay widget is basically a Stack so I can use a Positioned widget to position my alert (currently just a black Container wrapped inside a GestureDetector) at the top edge of the screen.</p><p>At this point, I can display a black overlay which is removed if I tap it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*w1SXil0aU6fMW-oKQBVXQA.png" /></figure><p>Because an OverlayEntry isn’t automatically wrapped with a DefaultTextStyle, Text widgets without style or with a TextStyle that does not explicitly prohibits inheritance are displayed with a very ugly default text style (large redish text that has yellow double-underlining). Therefore, it is important to add an inherit: false property like so:</p><pre>          Container(<br>            alignment: Alignment.center,<br>            color: black,<br>            height: 128,<br>            child: Text(<br>              &#39;Software Failure.  Tap to continue.\n\n&#39;<br>              &#39;Guru Meditation #48454C50.$hex&#39;,<br>              textAlign: TextAlign.center,<br>              style: TextStyle(<br>                color: red,<br>                fontFamily: &#39;Courier&#39;,<br>                fontSize: 16,<br>                fontWeight: FontWeight.bold,<br>                inherit: false,<br>              ),<br>            ),<br>          )</pre><p>It starts to look like the real deal (please ignore the notch for now):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*Erc7tfzV4tVm39aSQqWt-A.png" /></figure><p>Let’s add the iconic red border next. There’s one problem, though. I don’t want the text to wrap (which would happen on smaller devices). Furthermore, if you compare the Courier font I used with the original Amiga font, it runs too wide. So let’s transform the Text widget by scaling it horizontally to 75%. To keep it at the same width, I have to enlarge the width by 133% at the same time. The text should now always fit the screen.</p><pre>          Container(<br>            alignment: Alignment.center,<br>            decoration: BoxDecoration(<br>              color: black,<br>              border: Border.all(color: red, width: 8),<br>            ),<br>            padding: EdgeInsets.symmetric(<br>              horizontal: 8,<br>              vertical: 16,<br>            ),<br>            child: FractionallySizedBox(<br>              widthFactor: 4 / 3,<br>              child: Transform(<br>                alignment: Alignment.center,<br>                transform: Matrix4.identity().scaled(3 / 4, 1),<br>                child: Text(<br>                  ...<br>                ),<br>              ),<br>            ),<br>          ),</pre><p>We’re almost there…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*f0INcWhdYykz55DWFvYonA.png" /></figure><p>As you probably see on my screen shots, if the device has a notch, the alert doesn’t look right. I’d like to move the box below the notch but cover everything above in black. The Amiga also displays a small black border around the red border, so let’s add this, too. A SafeArea widget inside another Container can do both. I need to disable its bottom margin, though.</p><pre>    return Positioned(<br>      left: 0,<br>      right: 0,<br>      child: Container(<br>        color: black,<br>        child: SafeArea(<br>          minimum: EdgeInsets.all(8),<br>          bottom: false,<br>          child: GestureDetector(<br>            ...<br>          ),<br>        ),<br>      ),<br>    );</pre><p>And there, it is, perfectly aligned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*n2PEJjl2HSAhxWHhEb-85w.png" /></figure><p>For the final and most important step, I will add blinking.</p><p>The following might be a bit hacky, I don’t know, but it works and I don’t have to create a custom StatefulWidget. I’m using a StatefulBuilder instead. Each time, that widget asks its builder function to recreate the UI, I setup a timer to toggle the border color from red to black and back again after 700ms. Then, I’m using an AnimatedContainer to implicitly animate this color change within 300ms. Some things are just too easy in Flutter.</p><pre>          GestureDetector(<br>            onTap: () {<br>              blink = null;<br>              overlay.remove();<br>            },<br>            child: StatefulBuilder(<br>              builder: (context, setState) {<br>                Future.delayed(Duration(milliseconds: 700))<br>                .then((_) {<br>                  if (blink != null) setState(() =&gt; blink = !blink);<br>                });<br>                return AnimatedContainer(<br>                  duration: Duration(milliseconds: 300),<br>                  curve: Curves.easeInOut,<br>                  alignment: Alignment.center,<br>                  decoration: BoxDecoration(<br>                    color: black,<br>                    border: Border.all(<br>                      color: blink ? red : black, width: 8),<br>                  ),<br>                  ...<br>                );<br>              },<br>            ),<br>          ),</pre><p>Here is the hacky part: Because Flutter throws an exception if I tap the alert and setState is then called on a disposed widget, I need to protect myself against this case by setting blink to null and explicitly checking for it. Perhaps, I should have used a Timer instead of a Future because that timer could be cancelled, I think. The future is inevitable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*no1rJFjbWreZkHQUjphPIQ.gif" /><figcaption>Back to the future…</figcaption></figure><p>And there you have it, an alert box that looks much better than the usual modal dialog. And at least with old folk like myself, people will have a positive nostalgic feeling instead of cold-blooded anger because your app didn’t work for them as expected.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Feibaan%2Fembed%2Fpreview%2FwvKmrMg%3Fheight%3D600%26slug-hash%3DwvKmrMg%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Feibaan%2Fpen%2FwvKmrMg&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f52d8f12dc98951a94c88e0435191f/href">https://medium.com/media/52f52d8f12dc98951a94c88e0435191f/href</a></iframe><p>Here is the <a href="https://gist.github.com/sma/3dc39562fbd927e8b9519b690862dfea">source code</a>, by the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21c53982a99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/better-errors-messages-for-flutter-a21c53982a99">Better Errors Messages for Flutter</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Without Flutter]]></title>
            <link>https://medium.com/icnh/flutter-without-flutter-15177c91d066?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/15177c91d066</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Thu, 07 May 2020 17:10:10 GMT</pubDate>
            <atom:updated>2020-05-02T09:57:21.930Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an experiment. Let’s create the minimal code required to display something on a mobile device without using the Flutter framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HxAY1iTzcOaUnSz0aNZ0A.png" /><figcaption>not pretty, but self-made</figcaption></figure><p><a href="https://flutter.dev/">Flutter</a> is a high level GUI framework that uses dart:ui (an abstraction of the <a href="https://skia.org/">Skia engine</a>) to actually display something and to interact with the platform that something is displayed on. Of course, we’re free to directly use this low-level dart:ui library our selves.</p><h3>Setup</h3><p>Let’s create a new Flutter project:</p><pre>$ flutter create flutter_without_flutter</pre><p>then replace `lib/main.dart` with this code:</p><pre>import ‘dart:ui’;</pre><pre>void main() {<br> window.onBeginFrame = beginFrame;<br> window.scheduleFrame();<br>}</pre><pre>void beginFrame(Duration duration) {<br>}</pre><p>Explanation: We register a global function called beginFrame with the window singleton and then ask the graphics engine to schedule a callback to this function. It is supposed to prepare and eventually draw a frame, that is, display something on the device screen.</p><h3>Drawing Something</h3><p>Because I’m used to work with <em>logical units</em> instead of <em>physical pixels,</em> the first step in beginFrame is to convert the physical screen size of the device to more familiar values:</p><pre>void beginFame(Duration duration) {<br> final pixelRatio = window.devicePixelRatio;<br> final size = window.physicalSize / pixelRatio;<br> final physicalBounds = Offset.zero &amp; size * pixelRatio;<br> …</pre><p>The next step is to setup a Canvas that uses logical units:</p><pre> …<br> final recorder = PictureRecorder();<br> final canvas = Canvas(recorder, physicalBounds);<br> canvas.scale(pixelRatio, pixelRatio);<br> …</pre><p>Let’s then draw a circle filled with red-ish paint:</p><pre> …<br> final paint = Paint()..color = Color(0xFFF44336);<br> final center = size.center(Offset.zero);<br> canvas.drawCircle(center, size.shortestSide / 4, paint);<br> …</pre><p>The last step is to take the recording created by calling Canvas methods and use it to build a so called scene that is then rendered by the window singleton:</p><pre> …<br> final picture = recorder.endRecording();<br> final sceneBuilder = SceneBuilder()<br> ..pushClipRect(physicalBounds)<br> ..addPicture(Offset.zero, picture)<br> ..pop();<br> window.render(sceneBuilder.build());<br>}</pre><p>By the way, the usual <em>instant hot code reloading</em> of Flutter projects still works and this is why it might be useful to use this setup to create low level graphics applications like for example 2D games.</p><h3>Moving Something</h3><p>To move the circle and bounce it around the screen, we will store its center point in a global variable (called center) and its velocity in another globale variable (called velocity), modify these variables each time beginFrame is called and then ask for another draw operation using scheduleFrame at the end of the beginFrame function.</p><p>Here is the relevant change:</p><pre>Offset center;<br>Offset velocity;</pre><pre>void beginFrame(Duration duration) {<br> …<br> canvas.scale(pixelRatio, pixelRatio);</pre><pre>final radius = size.shortestSide / 4;<br> if (center == null) {<br> center = size.center(Offset.zero);<br> velocity = Offset(3, 5);<br> } else {<br> if (center.dx &lt; radius || center.dx &gt; size.width — radius)<br> velocity = velocity.scale(-1, 1);<br> if (center.dy &lt; radius || center.dy &gt; size.height — radius)<br> velocity = velocity.scale(1, -1);<br> center += velocity;<br> }</pre><pre>final paint = Paint()..color = Color(0xFFF44336);<br> canvas.drawCircle(center, radius, paint);</pre><pre>…</pre><pre>window.scheduleFrame();<br>}</pre><p>Because we don’t have control over how often the beginFrame function is scheduled, we should probably make use of the passed duration and bind the circle’s velocity to the passed time. To compute the time that passed between calls, we introduce another global variable called lastDuration.</p><pre>Duration lastDuration;</pre><pre>void beginFrame(Duration duration) {<br> …<br> if (center == null) {<br> …<br> } else {<br> …<br> final delta = (duration — lastDuration).inMilliseconds / 1000;<br> center += velocity * delta;<br> }<br> lastDuration = duration;</pre><pre>…</pre><p>If you kept the application running and just changed the soure code, the circle should have started moving just like magic.</p><h3>Reacting to Touches</h3><p>Last but not least, let’s change the velocity each time we tap the screen. To detect touches, we need to add another callback called onPointerDataPacket. This function receives a list of PointerData objects which describe <em>touch down</em>, <em>touch move</em>, and <em>touch up</em> events. We’re only interested in events of type PointerChange.up, though.</p><p>Here is the new main function:</p><pre>void main() {<br> window.onBeginFrame = beginFrame;<br> window.onPointerDataPacket = pointerDataPacket;<br> window.scheduleFrame();<br>}</pre><p>And here is the new callback function:</p><pre>void pointerDataPacket(PointerDataPacket packet) {<br> for (final data in packet.data) {<br> if (data.change == PointerChange.up) {<br> velocity = Offset.fromDirection(<br> _random.nextDouble() * pi * 2,<br> _random.nextDouble() * 800–400,<br> );<br> }<br> }<br>}</pre><pre>final _random = Random();</pre><p>Using this foundation, it should be possible for you to create your own Flutter-like GUI framework from scratch.</p><p>I leave this as an exercise to the reader :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15177c91d066" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/flutter-without-flutter-15177c91d066">Flutter Without Flutter</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Hammurabi in Dart]]></title>
            <link>https://medium.com/icnh/running-hammurabi-in-dart-e96cd85f9e61?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/e96cd85f9e61</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hammurabi]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Thu, 07 May 2020 17:09:28 GMT</pubDate>
            <atom:updated>2020-05-03T09:38:42.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVOzZqB4RoGBw3qUzWCfug.png" /></figure><p>One of the first computer games I played (back in the 80’s) was <a href="https://en.wikipedia.org/wiki/Hamurabi_(video_game)">Hammurabi</a>, after I found David Ahl’s <a href="https://www.atariarchives.org/basicgames/showpage.php?page=cover-german">classic book</a> about BASIC computer games in my local public library. Line by line, I typed the source code into my home computer and had hours of fun. At least, this is how I remember it.</p><p>Some time ago, I wanted to experience <a href="https://www.atariarchives.org/basicgames/showpage.php?page=78">the game</a> again. It would have been easy to translate its <a href="https://www.atariarchives.org/basicgames/showpage.php?page=79">source code</a> into some modern programming language, like for example <a href="https://www.dartlang.org/">Dart</a>, but I figured, it would be more fun to create a BASIC interpreter in Dart and let <em>it</em> run the original program.</p><p>This is my story of doing exactly this.</p><h3>Analysing BASIC</h3><p>The game consists of 120 lines of <a href="https://www.atariarchives.org/basicgames/showpage.php?page=i12">BASIC</a> for the Altair 8800 and this is a very typical example for its time with line numbers, simple instructions, no other control structures than FOR and GOTO and with only global variables.</p><p>Here is an except from the start of the program:</p><pre>10 PRINT TAB(32);&quot;HAMURABI&quot;<br>20 PRINT TAB(15);&quot;CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY&quot;<br>30 PRINT:PRINT:PRINT<br>80 PRINT &quot;TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA&quot;<br>90 PRINT &quot;FOR A TEN-YEAR TERM OF OFFICE.&quot;:PRINT<br>95 D1=0: P1=0<br>100 Z=0: P=95:S=2800: H=3000: E=H-S<br>110 Y=3: A=H/Y: I=5: Q=1<br>210 D=0<br>215 PRINT:PRINT:PRINT &quot;HAMURABI:  I BEG TO REPORT TO YOU,&quot;: Z=Z+1<br>217 PRINT &quot;IN YEAR&quot;;Z;&quot;,&quot;;D;&quot;PEOPLE STARVED,&quot;;I;&quot;CAME TO THE CITY,&quot;<br>218 P=P+I<br>227 IF Q&gt;0 THEN 230<br>228 P=INT(P/2)</pre><p>You might want to follow <a href="https://www.atariarchives.org/basicgames/showpage.php?page=i12">the link</a> to the original source code, since I refer to it by mentioning line numbers in the rest of this article.</p><p>Basically, I will create an interpreter which reads in the source, splits it into tokens (like <em>numbers</em>, <em>operators</em>, <em>names</em>, …) to make further processing easier and then parse and evaluate instructions until I see the END instruction. Each instruction (with the exception of LET for assignments) starts with a <em>keyword</em> and is terminated by either : or the <em>end of line</em>.</p><p>For evaluating expressions (stuff like H/Y or INT(P/2)) I will probably need to create a recursive descent parser for a very typical <a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">EBNF</a> grammar like this:</p><pre>expression = term {(&quot;+&quot;|&quot;-&quot;) term}<br>term = factor {(&quot;*&quot;|&quot;/&quot; factor)}<br>factor = &quot;-&quot; factor | primary<br>primary = &quot;(&quot; expression &quot;)&quot; | number | string | variable | function<br>variable = name<br>function = name (&quot; expression &quot;)&quot;</pre><p>As seen in line 227, there are also conditionals which follow this grammar:</p><pre>conditional = expression (&quot;&lt;&quot;|&quot;&lt;=&quot;|&quot;&gt;&quot;|&quot;&gt;=&quot;|&quot;=&quot;|&quot;&lt;&gt;&quot;) expression</pre><p>To implement jumping to lines I will simply do a linear search on the list of tokens instead of implementing some internal representation which might be more efficient. Each line starts with a line number and (with the exception of the first line) each line number is preceded by an <em>end of line</em> token from the previous line.</p><h3>Divide and Conquer</h3><p>Let’s start simple.</p><p>I set up a new Dart project where I put by BASIC source code (see above) and then create a file called hammurabi.dart which will contain all source code shown in this article.</p><p>I’ll try to show the relevant parts so that you can read along.</p><p>The following Dart code reads the BASIC source code and prints it. It’s to make sure the project setup works and we can run it (I’m using Visual Studio Code plus its Dart plugin) from within the IDE.</p><pre>import &#39;dart:io&#39;;</pre><pre>void main() {<br>  run(File(&quot;hammurabi.bas&quot;).readAsStringSync());<br>}</pre><pre>void run(String source) {<br>  print(source);<br>}</pre><p>By the way, because of an 8-letter restriction on the length of the filename, the original misses an “m” in the <a href="https://en.wikipedia.org/wiki/Hammurabi">king’s name</a>. I added it back.</p><p>My standard approach when creating LL(1) parsers is to create a stream of tokens using a tokenize function that uses a more or less complex <em>regular expression</em> to detect tokens and do some minimal post processing.</p><p>Eyeballing the source code, I need to detect</p><ul><li>numbers: \d+</li><li>strings: &quot;.*?&quot;</li><li>names (variables and keywords of instructions): \w+</li><li>arithmetic operators (see grammar above): [-+*/]</li><li>comparison operators (see grammar above): &lt;(&gt;=)?|&gt;=?|=</li><li>syntax like parentheses or the : to separate instructions</li><li>the <em>end of line</em></li></ul><p>I also want to skip whitespace. Therefore, I group everything I want to detect, append an alternative to skip whitespace, and return the first <em>capture group</em> and not the whole expression.</p><pre>Iterable&lt;String&gt; tokenize(String source) {<br>  return RegExp(r&#39;(...)|\s+&#39;)<br>    .allMatches(source)<br>    .map((m) =&gt; m[1])<br>    .where((m) =&gt; m != null);<br>}</pre><p>This (instead of ...) is my regular expression:</p><pre>(\d+|&quot;.*?&quot;|\w+|[-+*/:;()]|[&lt;&gt;=]+|\n)</pre><p>Let’s test it by replacing the old run with this new code:</p><pre>void run(String source) {<br>  print(List.of(tokenize(source)));<br>}</pre><p>This prints something like this which doesn’t look too bad:</p><pre>[10, PRINT, TAB, (, 32, ), ;, &quot;HAMURABI&quot;, <br>, 20, PRINT, TAB, (, 15, ), ;, &quot;CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY&quot;, <br>, 30, PRINT, :, PRINT, :, PRINT, <br>, 80, PRINT, &quot;TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA&quot;, <br>, 90, PRINT, &quot;FOR A TEN-YEAR TERM OF OFFICE.&quot;, :, PRINT, <br>, 95, D1, =, 0, :, P1, =, 0, <br>, 100, Z, =, 0, :, P, =, 95, :, S, =, 2800, :, H, =, 3000, :, E, =, H, -, S, <br>, 110, Y, =, 3, :, A, =, H, /, Y, :, I, =, 5, :, Q, =, 1, <br>, 210, D, =, 0, ...</pre><p>This was almost too easy. To make sure, that I didn’t miss anything (spoiler: I did) I add another alternate group to the regular expression (.) that matches anything not matched before and prints it:</p><pre>Iterable&lt;String&gt; tokenize(String source) {<br>  return RegExp(r&#39;(\d+|&quot;.*?&quot;|\w+|[-+*/:;()]|[&lt;&gt;=]+|\n)|\s+|(.)&#39;)<br>      .allMatches(source)<br>      .map((m) {<br>        if (m[2] != null) print(m[2]);<br>        return m;<br>      })<br>      .map((m) =&gt; m[1])<br>      .where((m) =&gt; m != null);<br>}</pre><p>Looks like I’m missing these characters: ?!&#39;,%. While , and . (as part of floating point numbers) are obvious mistakes and I have to modify my regular expression accordingly, I don’t think that BASIC ever had those other operators. Looking at the source, I notice that the REM statement for <em>remarks</em> is somewhat irregular.</p><pre>418 REM *** TRYING TO USE MORE GRAIN THAN IS IN SILOS?<br>532 REM *** LET&#39;S HAVE SOME BABIES<br>541 REM *** HORROR, A 15% CHANCE OF PLAGUE</pre><p>So I have to filter it, too. My first instinct was to make it whitespace but then I thought that empty lines might later irritate my interpreter. I decided to make it a normal instruction, just ignoring everything following the keyword up to the end of the line. Because Dart — like JavaScript — has no lookbehind operator, I have to add a bit of post processing using an additional <em>capture group</em>. Order matters here.</p><pre>Iterable&lt;String&gt; tokenize(String source) {<br>  return RegExp(r&#39;(\d+(?:\.\d*)?|\.\d+|&quot;.*?&quot;|(REM).*|\w+|&#39;<br>                r&#39;[-+*/:;()]|[&lt;&gt;=]+|\n)|\s+&#39;)<br>      .allMatches(source)<br>      .map((m) =&gt; m[2] ?? m[1])<br>      .where((m) =&gt; m != null);<br>}</pre><p>This correctly tokenizes the complete source code.</p><h3>Parsing for Fun and Profit</h3><p>Over the years, I learned how a create a tiny framework for writing LL(1) parsers by hand.</p><ul><li>The token function returns the current token. Normally, I’d use some kind of stream (a.k.a. Iterable), but thinking about how to implement GOTO I knew I had to keep all tokens as the representation of the program around, so this implementation will use a List and an int index. Later, I will call this index the <em>instruction pointer</em>.</li><li>The advance function will consume the current token and advances the index to the next one to make it the new current token.</li></ul><p>Both functions are the basic building block for all other functions:</p><ul><li>at(t) tests whether token is t and automatically consumes it if this is the case. This is very useful for testing for keywords and other syntax.</li><li>expect(t) works like at but throws an error if at would return false.</li><li>Throwing the error is done by theexpected function which tries to give some context. In this implementation I’m printing the current token and the BASIC line number, which is nearest to the instruction pointer.</li></ul><pre>String get token =&gt; _tokens[_index];</pre><pre>void advance() =&gt; _index++;</pre><pre>bool at(String t) {<br>  if (token == t) {<br>    advance();<br>    return true;<br>  }<br>  return false;<br>}</pre><pre>void expect(String t) {<br>  if (!at(t)) expected(&#39;$t&#39;);<br>}</pre><pre>void expected(String message) {<br>  var i = _index;<br>  while (i &gt;= 0 &amp;&amp; _tokens[i] != &#39;\n&#39;) --i;<br>  var line = _tokens[i + 1];<br>  throw &#39;expected $message but found $token in $line&#39;;<br>}</pre><pre>List&lt;String&gt; _tokens;</pre><pre>int _index;</pre><p>Because it will be handy, the next two functions detect the end of an instruction and unify the two cases that there’s either a : or the <em>end of line</em>. In the latter case I also skip the next line number which must follow (this would crash if the program end with : which it doesn’t).</p><pre>bool atEnd() {<br>  if (at(&#39;\n&#39;)) {<br>    advance();<br>    return true;<br>  }<br>  return at(&#39;:&#39;);<br>}</pre><pre>void expectEnd() {<br>  if (!atEnd()) expected(&#39;end of instruction&#39;);<br>}</pre><p>Let’s test this “framework” by printing all BASIC instructions like so:</p><pre>void run(String source) {<br>  _tokens = List.of(tokenize(source));<br>  _index = 1;<br>  while (!at(&#39;END&#39;)) {<br>    print(token);<br>    while (!atEnd()) advance();<br>  }<br>}</pre><p>I can pipe this output to sort -u and removing the obvious variable names, I get an overview of all instructions I have to implement:</p><pre>GOSUB<br>GOTO<br>IF<br>INPUT<br>PRINT<br>REM<br>RETURN</pre><p>Fortunately, this is a very short list. Adding another function for processing assignments (because theLET keyword is optional) I shall be able to parse everything using this main loop:</p><pre>void run(String source) {<br>  _tokens = List.of(tokenize(source));<br>  _index = 1;<br>  while (!at(&#39;END&#39;)) {<br>    if (at(&#39;GOSUB&#39;))<br>      doGosub();<br>    else if (at(&#39;GOTO&#39;))<br>      doGoto();<br>    else if (at(&#39;IF&#39;))<br>      doIf();<br>    else if (at(&#39;INPUT&#39;))<br>      doInput();<br>    else if (at(&#39;PRINT&#39;))<br>      doPrint();<br>    else if (at(&#39;REM&#39;))<br>      doRem();<br>    else if (at(&#39;RETURN&#39;))<br>      doReturn();<br>    else<br>      doLet();<br>  }<br>}</pre><pre>void doGosub() { expectEnd(); }<br>void doGoto() { expectEnd(); }<br>void doIf() { expectEnd(); }<br>void doInput() { expectEnd(); }<br>void doPrint() { expectEnd(); }<br>void doRem() { expectEnd(); }<br>void doReturn() { expectEnd(); }<br>void doLet() { expectEnd(); }</pre><p>Running this obviously doesn’t work, but the error that occurs will help in implementing the needed functionality as we slowing proceed through the source:</p><pre>&quot;expected end of instruction but found TAB in 10&quot;</pre><p>This refers to the very first line:</p><pre>10 PRINT TAB(32);&quot;HAMURABI&quot;</pre><p>So let’s implement PRINT (which unfortunately is also the most complex instruction) and for this, let’s implement expression parsing first.</p><h3>Express Yourself</h3><p>Instead of incrementally developing those parsing functions, I’ll create a standard expression parser according to the EBNF grammar shown above because that’s straight forward (at least to me). You can translate EBNF grammars nearly directly into recursive function calls. There is just one minor problem: The above grammar cannot distinguish <em>variable</em> and <em>function</em> rules as written. But that’s easy to fix.</p><p>You will also notice that I have to use <em>regular expressions</em> again to detect numbers and names. I could omit this by introducing a Token class that holds this information which is more easily available in tokenize. That function would be the right place to create such tokens. I leave this as an exercise to the reader and keep using strings.</p><pre>// expression = term {(&quot;+&quot;|&quot;-&quot;) expression}<br>expression() {<br>  var v = term();<br>  while (true) {<br>    if (at(&#39;+&#39;))<br>      v += term();<br>    else if (at(&#39;-&#39;))<br>      v -= term();<br>    else<br>      return v;<br>  }<br>}</pre><pre>// term = factor {(&quot;*&quot;|&quot;/&quot;) factor}<br>term() {<br>  var v = factor();<br>  while (true) {<br>    if (at(&#39;*&#39;))<br>      v *= factor();<br>    else if (at(&#39;/&#39;))<br>      v /= factor();<br>    else<br>      return v;<br>  }<br>}</pre><pre>// factor = &quot;-&quot; factor | primary<br>// primary = &quot;(&quot; expression &quot;)&quot;<br>//         | number | string | variable | function<br>// variable = name<br>// function = name (&quot; expression &quot;)&quot;<br>factor() {<br>  if (at(&#39;-&#39;)) return -factor();<br>  if (at(&#39;(&#39;)) {<br>    var v = expression();<br>    expect(&#39;)&#39;);<br>    return v;<br>  }<br>  var t = token;<br>  if (t[0] == &#39;&quot;&#39;) {<br>    advance();<br>    return t.substring(1, t.length - 1);<br>  }<br>  if (RegExp(r&#39;\.?\d&#39;).matchAsPrefix(t) != null) {<br>    advance();<br>    return num.parse(t);<br>  }<br>  var n = name();<br>  if (at(&#39;(&#39;)) {<br>    var arg = expression();<br>    expect(&#39;)&#39;);<br>    if (n == &#39;TAB&#39;) return &#39; &#39; * arg;<br>    expected(&#39;unknown function $n&#39;);<br>  }<br>  return _variables[n] ?? 0;<br>}</pre><pre>String name() {<br>  var t = token;<br>  if (RegExp(r&#39;[a-zA-Z]&#39;).matchAsPrefix(t) != null) {<br>    advance();<br>    return t;<br>  }<br>  throw expected(&#39;name&#39;);<br>}</pre><pre>Map&lt;String, num&gt; _variables = {};</pre><p>Because Dart <a href="https://github.com/dart-lang/language/issues/83">cannot express union types</a> like num | String which is what these functions will return, I don’t specify a return type at all (so it is dynamic). This could be omitted by creating a hierarchy of custom values types but I consider it overkill for this project.</p><h3>PRINT</h3><p>Now, the doPrint function looks like this:</p><pre>void doPrint() {<br>  var s = &quot;&quot;;<br>  if (!atEnd()) {<br>    s += &#39;${expression()}&#39;;<br>    while (at(&#39;;&#39;)) {<br>      s += &#39;${expression()}&#39;;<br>    }<br>    expectEnd();<br>  }<br>  stdout.writeln(s);<br>}</pre><p>Looking at line 30, PRINT could be empty. Therefore the first if. Otherwise, there’s at least one expression and probably more, which are then separated by ;. If you know BASIC, you’ll remember that there’s also a variant using , instead of ; but luckily, this isn’t used by this program. (And yes, the above implementation isn’t 100% correct. We’ll revisit it shortly.)</p><h4>Let there be print!</h4><p>We’re now making real progress. Running the interpreter prints something:</p><pre>                                HAMURABI<br>               CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY<br>TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA<br>FOR A TEN-YEAR TERM OF OFFICE.</pre><h4>Apropos LET</h4><p>The next error is in line 95 which is the first assignment.</p><pre>&quot;expected end of instruction but found D1 in 95&quot;</pre><p>Let’s implement LET. With everything we already written, it’s almost too easy. We expect a name and a = token followed by an expression. Then we create or update a global variable.</p><pre>void doLet() {<br>  var n = name();<br>  expect(&#39;=&#39;);<br>  _variables[n] = expression();<br>  expectEnd();<br>}</pre><p>Let’s run the programm again.</p><h3>Conditions</h3><p>The next error is in line 227 which is the first IF statement:</p><pre>227 IF Q&gt;0 THEN 230</pre><p>Evaluating the conditional expression should be easy and will be achieved by a new function called condition.</p><pre>bool condition() {<br>  var e = expression();<br>  if (at(&#39;=&#39;)) return e == expression();<br>  if (at(&#39;&lt;&gt;&#39;)) return e != expression();<br>  if (at(&#39;&lt;&#39;)) return e &lt; expression();<br>  if (at(&#39;&lt;=&#39;)) return e &lt;= expression();<br>  if (at(&#39;&gt;&#39;)) return e &gt; expression();<br>  if (at(&#39;&gt;=&#39;)) return e &gt;= expression();<br>  expected(&#39;comparison operator&#39;);<br>}</pre><p>(BTW, does anybody know how to tell the Dart compiler that expected is a function that never returns? In Swift, it’s the type Never. I thought, I have to use Null in Dart, but I still get a warning that condition might not return a Boolean value.)</p><h4>With a Jump to the Left…</h4><p>So let’s next have a look at how to implement the jump. First of all, I want to make sure, there is a valid number, which is checked by a function line which works like name shown before. The goto function then implements searching for right line number and moving the instruction pointer index right behind that number in the token stream.</p><pre>String line() {<br>  var t = token;<br>  if (RegExp(r&#39;\d+&#39;).matchAsPrefix(t) != null) {<br>    advance();<br>    return t;<br>  }<br>  throw expected(&#39;line number&#39;);<br>}</pre><pre>...</pre><pre>void goto(String line) {<br>  for (var i = 0; i &lt; _tokens.length;) {<br>    if (_tokens[i++] == line) {<br>      _index = i;<br>      return;<br>    }<br>    for (; i &lt; _tokens.length &amp;&amp; _tokens[i] != &#39;\n&#39;; i++);<br>    i++;<br>  }<br>  throw &#39;missing line $line&#39;;<br>}</pre><p>The last throw should never occur in a program but better be safe than sorrow. I’m using a string as a cheap runtime exception. Don’t follow my example.</p><h4>IF THEN</h4><p>This instruction is again straight forward to implement. I just have to remember that I have to parse the whole instruction before jumping or otherwise not jumping would result in a parsing error (which of course happened when I wrote this initially).</p><pre>void doIf() {<br>  var c = condition();<br>  expect(&#39;THEN&#39;);<br>  var l = line();<br>  expectEnd();<br>  if (c) goto(l);<br>}</pre><h3>More BASIC Functions</h3><p>The next problem is a missing RND function in line 310:</p><pre>310 C=INT(10*RND(1)): Y=C+17</pre><p>There’s also another function INT which I will implement simultaneously. For the random function, I have to import dart:math and initialize a random generator somewhere in my program. I will omit that code here and just show the implementation of the two BASIC functions by adding two lines to the existingfactor function:</p><pre>factor() {<br>  ...<br>  var n = name();<br>  if (at(&#39;(&#39;)) {<br>    var arg = expression();<br>    expect(&#39;)&#39;);<br>    if (n == &#39;TAB&#39;) return &#39; &#39; * arg;<br>    if (n == &#39;RND&#39;) return _random.nextDouble();<br>    if (n == &#39;INT&#39;) return arg.toInt();<br>    expected(&#39;unknown function $n&#39;);<br>  }<br>  ...<br>}</pre><h3>Revisiting PRINT</h3><p>The next error took me some time to understand.</p><pre>&quot;expected name but found \n in 321&quot;</pre><p>Is the INPUT statement the problem? But then the error is wrong…!?</p><pre>320 PRINT &quot;HOW MANY ACRES DO YOU WISH TO BUY&quot;;<br>321 INPUT Q: IF Q&lt;0 THEN 850<br>322 IF Y*Q&lt;=S THEN 330</pre><p>No, the problem is the ; in line 320 which instructs BASIC to not add a line feed and carriage return to the printed line, so that INPUT will prompt the user in the same line. But I overlooked it for minutes even if I originally knew about that variant of PRINT.</p><p>And while at it and in the case you’re following along with your own implementation, you might have noticed that the output looks wrong:</p><pre>POPULATION IS NOW100<br>THE CITY NOW OWNS 1000.0ACRES.<br>YOU HARVESTED3BUSHELS PER ACRE.<br>RATS ATE200BUSHELS.</pre><p>I think, we need to add spaces around the numbers where semicolons are used. The true semantics when to add space might be more sophisticated, but that should do the trick. And I should probably also omit to print decimal places for doubles that have none. To do all this argument processing, I introduce a local function str.</p><pre>void doPrint() {<br>  String str(v) {<br>    if (v is String) return v;<br>    if (v == v.toInt()) v = v.toInt();<br>    return &#39; $v &#39;;<br>  }</pre><pre>  var s = &quot;&quot;;<br>  if (!atEnd()) {<br>    s += str(expression());<br>    while (at(&#39;;&#39;)) {<br>      if (atEnd()) {<br>        stdout.write(s);<br>        return;<br>      }<br>      s += str(expression());<br>    }<br>    expectEnd();<br>  }<br>  stdout.writeln(s);<br>}</pre><p>This should fix the PRINT statement for good.</p><h3>INPUT</h3><p>Now the next missing instruction is INPUT. Its implementation would look like this, but because Visual Studio Code doesn’t support reading from <em>stdin</em> I couldn’t continue to run and debug my code using this IDE. How annoying…</p><pre>void doInput() {<br>  var n = name();<br>  expectEnd();<br>  stdout.write(&#39;? &#39;);<br>  var i = stdin.readLineSync();<br>  _variables[n] = num.tryParse(i) ?? 0;<br>}</pre><p>I need a better solution and for now, I will provide hard-coded values I read from a global variable called inputs. I feel clever that I came up with this trick ;-)</p><pre>var inputs = [&#39;0&#39;, &#39;1&#39;, &#39;1800&#39;, &#39;1000&#39;];</pre><pre>void doInput() {<br>  var n = name();<br>  expectEnd();<br>  stdout.write(&#39;? &#39;);<br>  var i;<br>  if (inputs != null &amp;&amp; inputs.isNotEmpty) {<br>    i = inputs.removeAt(0);<br>    stdout.writeln(i);<br>  } else {<br>    i = stdin.readLineSync();<br>  }<br>  _variables[n] = num.tryParse(i) ?? 0;<br>}</pre><p>We’re almost there. The output looks promising:</p><pre>                                HAMURABI<br>               CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY</pre><pre>TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA<br>FOR A TEN-YEAR TERM OF OFFICE.</pre><pre>HAMURABI:  I BEG TO REPORT TO YOU,<br>IN YEAR 1 , 0 PEOPLE STARVED, 5 CAME TO THE CITY,<br>POPULATION IS NOW 100 <br>THE CITY NOW OWNS  1000 ACRES.<br>YOU HARVESTED 3 BUSHELS PER ACRE.<br>RATS ATE 200 BUSHELS.<br>YOU NOW HAVE  2800 BUSHELS IN STORE.</pre><pre>LAND IS TRADING AT 24 BUSHELS PER ACRE.<br>HOW MANY ACRES DO YOU WISH TO BUY? 0<br>HOW MANY ACRES DO YOU WISH TO SELL? 1</pre><pre>HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? 1800</pre><pre>HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? 1000<br>HAMURABI:  THINK AGAIN.  YOU OWN ONLY 999 ACRES.  NOW THEN,</pre><h3>GOTO, GOSUB and RETURN</h3><p>These are the remaining instructions to implement.</p><p>The next error shown after NOW THEN is this:</p><pre>&quot;expected end of instruction but found 440 in 447&quot;</pre><p>Looking at that line, this is a GOTO instruction. Easy.</p><p>Here is this unconditional jump:</p><pre>void doGoto() {<br>  var l = line();<br>  expectEnd();<br>  goto(l);<br>}</pre><p>For jumping to (and returning from) subroutines, I need to setup a stack to save the current instruction pointer before changing it like so:</p><pre>void doGosub() {<br>  var l = line();<br>  expectEnd();<br>  _stack.add(_index);<br>  goto(l);<br>}</pre><pre>void doReturn() {<br>  expectEnd();<br>  _index = _stack.removeLast();<br>}</pre><pre>List&lt;int&gt; _stack = [];</pre><h3>The BASIC Has Landed</h3><p>I think, that was all.</p><p>I can now, after an hour or two needing to implement my interpreter and multiple hours writing everything down and refactoring the code and fixing my writeup, finally play this rather boring game.</p><pre>                                HAMURABI<br>               CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY</pre><pre>TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA<br>FOR A TEN-YEAR TERM OF OFFICE.</pre><pre>HAMURABI:  I BEG TO REPORT TO YOU,<br>IN YEAR 1 , 0 PEOPLE STARVED, 5 CAME TO THE CITY,<br>POPULATION IS NOW 100 <br>THE CITY NOW OWNS  1000 ACRES.<br>YOU HARVESTED 3 BUSHELS PER ACRE.<br>RATS ATE 200 BUSHELS.<br>YOU NOW HAVE  2800 BUSHELS IN STORE.</pre><pre>LAND IS TRADING AT 18 BUSHELS PER ACRE.<br>HOW MANY ACRES DO YOU WISH TO BUY? 0<br>HOW MANY ACRES DO YOU WISH TO SELL? 0</pre><pre>HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? 1800</pre><pre>HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? 990</pre><pre>HAMURABI:  I BEG TO REPORT TO YOU,<br>IN YEAR 2 , 10 PEOPLE STARVED, 13 CAME TO THE CITY,<br>POPULATION IS NOW 103 <br>THE CITY NOW OWNS  1000 ACRES.<br>YOU HARVESTED 5 BUSHELS PER ACRE.<br>RATS ATE 0 BUSHELS.<br>YOU NOW HAVE  5455 BUSHELS IN STORE.</pre><pre>LAND IS TRADING AT 17 BUSHELS PER ACRE.<br>HOW MANY ACRES DO YOU WISH TO BUY? _</pre><p>Back in the early eighties, I found it much more fascinating. But David Ahl’s book contains a lot of other games. The game <a href="https://www.atariarchives.org/basicgames/showpage.php?page=157">Super Star Trek</a>, sounds promising, doesn’t it? Let’s try it:</p><pre>                                     ,------*------,<br>                    ,-------------   &#39;---  ------&#39;<br>                     &#39;-------- --&#39;      / /<br>                         ,---&#39; &#39;-------/ /--,<br>                          &#39;----------------&#39;</pre><pre>                    THE USS ENTERPRISE --- NCC-1701</pre><p>Then, it crashes because I don’t support string variables or array variables… The bigger problem however is that the Star Trek source doesn’t use spaces to separate tokens so my tokenize function is too simplistic to split something like IFK9&gt;T9THENT9=K9+1. Too bad. Perhaps another time.</p><h3>Appendix</h3><p>The complete <a href="https://gist.github.com/sma/99424474a607430ab81f2e05336697bb">source code</a> for my interpreter.</p><p>I’m not sure whether I’m allowed to also include the BASIC source, but this guy thinks it’s okay to provide machine readable <a href="http://www.vintage-basic.net/games.html">versions</a> from the book.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96cd85f9e61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/running-hammurabi-in-dart-e96cd85f9e61">Running Hammurabi in Dart</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a Gap to Flutter]]></title>
            <link>https://medium.com/icnh/adding-a-gap-to-flutter-e4277715b6a5?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4277715b6a5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Thu, 07 May 2020 17:07:28 GMT</pubDate>
            <atom:updated>2020-05-03T09:10:44.390Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I wished that Row or Column widgets had a spacing property to configure gaps between child widgets.</p><p>Because I find it too cumbersome to add padding to those children — both because this further indents the widgets in the widget tree and because its difficult to decide whether one should add only a bottom padding, or only a top padding, or paddings to both the top and the bottom of child widgets — I most often use a SizedBox widget to introduce gaps. And there’s another inconvenience: I have to explicitly set the width or the height property dependent on whether the gap is added to a Row or Column and to use constants, I have to introduce both smallVerticalGap and smallHorizontalGap or something similar.</p><p>Can we create a Gap widget that automatically does the right thing?</p><p>Yes, we can!</p><h3>The Gap</h3><p>Here is my implementation.</p><p>Because its layout is depdent on the direction of the Flex widget it is a child of (the Spacer widget has the same problem) this cannot be achieved with widgets alone. I need a special <em>render object</em> that performs the special layout. Therefore, Gap shall be a subclass of SingleChildRenderObjectWidget:</p><pre>class Gap extends SingleChildRenderObjectWidget {<br>  const Gap({Key key, this.size = 16})<br>    : assert(size != null),<br>      super(key: key);</pre><pre>  final double size;</pre><pre>  …</pre><p>Gap is now required to implement a createRenderObject method which, well, creates a render object. I shall call this object RenderGap, following Flutter’s naming convention.</p><pre>  …</pre><pre>  @override<br>  RenderGap createRenderObject(BuildContext context) {<br>    return RenderGap(size);<br>  }</pre><pre>  …</pre><p>As Gap has one property which must be passed down, I also implement updateRenderObject to make sure that changes to that property also affect my render object:</p><pre>  …</pre><pre>  @override<br>  void updateRenderObject(BuildContext context, RenderGap renderObject) {<br>    renderObject.gapSize = size;<br>  }<br>}</pre><p>The RenderGap is implemented as a subclass of RenderBox which provides most of the functionallity needed. Because render objects — in constrast to widgets — are mutable, I make sure that changes to the gapSize property trigger a re-layout, but only if the size really changes.</p><pre>class RenderGap extends RenderBox {<br>  RenderGap(this._gapSize);</pre><pre>  double _gapSize;<br>  double get gapSize =&gt; _gapSize;<br>  set gapSize(double gapSize) {<br>    if (_gapSize != gapSize) {<br>      _gapSize = gapSize;<br>      markNeedsLayout();<br>    }<br>  }</pre><pre>  …</pre><p>We’re done with the <em>boiler plate</em> code.</p><p>To implement layout, we have to override the performLayout method which must set the object’s size property. The documentation says that it also should honor the object’s constraints, but for now, I ignore them because I’m a bit in a hurry. Hopefully, my assumption is correct that performLayout is only called once the object has been added to the render tree and therefore always has a parent.</p><p>I assign a size based on the layout direction of its parent like so:</p><pre>  …</pre><pre>  @override<br>  void performLayout() {<br>    final parent = this.parent;<br>    if (parent is RenderFlex) {<br>      if (parent.direction == Axis.horizontal) {<br>        size = Size(_gapSize, 0);<br>      } else {<br>        size = Size(0, _gapSize);<br>      }<br>    } else {<br>      throw FlutterError(‘Gap must be used inside a Flex widget’);<br>    }<br>  }<br>}</pre><p>Now, it is possible to add gaps to columns or rows:</p><pre>Column(<br>  children: [<br>    Text(‘Here is a message’),<br>    Gap.large,<br>    Row(<br>      children: [<br>        Spacer(),<br>        RaisedButton(<br>          onPressed: () =&gt; null,<br>          child: Text(‘Cancel’),<br>        ),<br>        Gap.small,<br>        RaisedButton(<br>          onPressed: () =&gt; null,<br>          child: Text(‘OK’),<br>        ),<br>      ],<br>    ),<br>  ]<br>);</pre><p>For a complete implementation one must also override the four compute{Min,Max}Intrinsic{Width,Height} methods. Instead of 0, they should return gapSize if there is a parent of class RenderFlex with the right `direction`.</p><p>Here is the complete <a href="https://dartpad.dev/a377435ab091d4b3b5b367f20907cd29">source code</a>.</p><h3>Alternatives to consider</h3><p>After implementing this, I’d love to hear other people’s opinion whether this is useful or not. Or should we define something like</p><pre>List&lt;Widget&gt; rowGap(double gap, Iterable&lt;Widget&gt; children) {<br>  return children.expand((child) sync* {<br>    yield SizedBox(width: gap);<br>    yield child;<br>  });<br>}</pre><pre>List&lt;Widget&gt; columnGap(double gap, Iterable&lt;Widget&gt; children) {<br>  return children.expand((child) sync* {<br>    yield SizedBox(height: gap);<br>    yield child;<br>  });<br>}</pre><p>and then use those method like this</p><pre>Column(<br>  children: columnGap(32, [<br>    Text(‘Here is a message’),<br>    Row(<br>      children: rowGap(8, [<br>        Spacer(),<br>        RaisedButton(<br>          onPressed: () =&gt; null,<br>          child: Text(‘Cancel’),<br>        ),<br>        RaisedButton(<br>          onPressed: () =&gt; null,<br>          child: Text(‘OK’),<br>        ),<br>      ]),<br>    ),<br>  ])<br>);</pre><p>instead?</p><p>At least, this articles demonstrates how to create a simple render object in case you need one. At lease <em>leaf render object</em> are simple to create and sometimes useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4277715b6a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/adding-a-gap-to-flutter-e4277715b6a5">Adding a Gap to Flutter</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Flutter App from Sketch]]></title>
            <link>https://medium.com/icnh/creating-a-flutter-app-from-sketch-89ceec716ca2?source=rss----c4bdd4301276---4</link>
            <guid isPermaLink="false">https://medium.com/p/89ceec716ca2</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[sketch]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Stefan Matthias Aust]]></dc:creator>
            <pubDate>Mon, 13 May 2019 14:19:57 GMT</pubDate>
            <atom:updated>2019-05-13T14:19:34.356Z</atom:updated>
            <content:encoded><![CDATA[<p>Wouldn’t it be cool, if you could create a working <a href="https://flutter.dev/">Flutter</a> app directly from a design created in <a href="https://www.sketch.com/">Sketch</a>? Let’s do a proof of concept implementation.</p><p>Here’s the plan: Sketch saves its design documents as zip archives. Those archives contain multiple JSON files which describe (so it seems) some meta data, the editor’s state, the pages and artboards, and all the graphical elements that comprise the design. I will navigate the zip’s file structure to find an artboard, extract the relevant data, and draw each graphical element on a Flutter canvas. The linking between artboards can then be used to navigate in Flutter. And voilá – instant app.</p><p>Because I didn’t find a format description after a few minutes of googling, this will also be an exercise of reverse engineering the Sketch file format.</p><h3>Analyzing the File Format</h3><p>I create the following example in Sketch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-o7r3ZJzT05md2N04UYrw.png" /><figcaption>It is quite obvious that I’m not a designer</figcaption></figure><p>I save my design as example.sketch. There is one <em>page</em> that has two <em>artboards</em> that have a status bar and title bar you typically find on iOS and which contain some <em>text</em> and some <em>rectangles</em>. To draw the back button, I used a <em>vector</em>.</p><p>As previously mentioned, a .sketch file is a zip archive:</p><pre>$ file example.sketch <br>example.sketch: Zip archive data, at least v2.0 to extract</pre><p>It contains the following files:</p><pre>$ unzip -l example.sketch <br>Archive:  example.sketch<br>  Length    Name<br>---------   ----<br>      664   document.json<br>    32797   pages/E025DB91-38B6-4AE4-BACB-647DF4A40CBA.json<br>      137   user.json<br>      696   meta.json<br>    28858   previews/preview.png<br>---------   -------<br>    63152   5 files</pre><p>Let’s ignore the preview image. The user.json file seems to the editor’s state. I will ignore it. The document.json file also doesn’t contain useful information — but because it contains an empty assets collection, it might be important for “real world” sketch files that include bitmap images, symbols, or other elements besides simple rectangles and text. But I will ignore it for now.</p><p>The meta.json file is much more interesting. It contains information about the Sketch application used to create the .sketch file (which I will ignore) and the following table of contents:</p><pre>{<br>    &quot;commit&quot;: &quot;399b83655ed261b257875cf8e762efa1a649509e&quot;,<br>    &quot;pagesAndArtboards&quot;: {<br>        &quot;E025DB91-38B6-4AE4-BACB-647DF4A40CBA&quot;: {<br>            &quot;name&quot;: &quot;Page 1&quot;,<br>            &quot;artboards&quot;: {<br>                &quot;8C823950-BF56-42E2-ACAE-3762BBC8A570&quot;: {<br>                    &quot;name&quot;: &quot;First&quot;<br>                },<br>                &quot;49F995AB-4992-42AB-B708-86C5C42B3CDB&quot;: {<br>                    &quot;name&quot;: &quot;Second&quot;<br>                }<br>            }<br>        }<br>    },<br>    ...<br>}</pre><p>I will use this information to load the page file(s) that contains specific artboards. I could even make loading those files on-demand.</p><p>Looking at the JSON file for the page object, I can guess the classes used to represent the data before their instances where serialized to JSON. Most JSON objects contain a _class property with the class name and a do_objectID property which seems to be a UUID identifing the instance. Objects without identifiers are probably structs instead of classes.</p><pre>{<br>    &quot;_class&quot;: &quot;page&quot;,<br>    &quot;do_objectID&quot;: &quot;E025DB91-38B6-4AE4-BACB-647DF4A40CBA&quot;,<br>    ...<br>    &quot;frame&quot;: {<br>        &quot;_class&quot;: &quot;rect&quot;,<br>        &quot;constrainProportions&quot;: false,<br>        &quot;height&quot;: 0,<br>        &quot;width&quot;: 0,<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 0<br>    },<br>    ...<br>    &quot;name&quot;: &quot;Page 1&quot;,<br>    ...<br>    &quot;style&quot;: {<br>        &quot;_class&quot;: &quot;style&quot;,<br>        ...<br>    },<br>    &quot;layers&quot;: [<br>        {<br>            &quot;_class&quot;: &quot;artboard&quot;,<br>            &quot;do_objectID&quot;: &quot;49F995AB-4992-42AB-B708-86C5C42B3CDB&quot;,<br>            ...<br>        },<br>        ...<br>    ],<br>    ...<br>}</pre><p>Luckily, the whole structure seems to be quite uniform. Each element has a name, a frame, some style, and layers which is a list of child elements. Other properties look less important to me.</p><h3>Decoding the Sketch File in Dart</h3><p>Armed with this knowledge about the file structure, I shall create classes to represent those elements in Dart. This should then help to draw the elements into a Flutter canvas, creating a SketchWidget do display such canvas and eventually implement navigation between those widgets.</p><p>Reading the zip archive is easy thank to the <a href="https://pub.dev/packages/archive">archive</a> package.</p><h4>Reading the Table of Contents</h4><p>Let’s test this using the following Dart program:</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:archive/archive.dart&#39;;</pre><pre>void main() {<br>  final file = File(&#39;example.sketch&#39;);<br>  final bytes = file.readAsBytesSync();<br>  final archive = ZipDecoder().decodeBytes(bytes);<br>  for (final file in archive) {<br>    print(file.name);<br>  }<br>}</pre><p>This should print the file names shown above.</p><p>The next step is to use findFile to extract the meta.json file from the archive and to decode it as JSON document, then printing it, to make sure this works, too:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;package:archive/archive.dart&#39;;</pre><pre>void main() {<br>  final file = File(&#39;example.sketch&#39;);<br>  final bytes = file.readAsBytesSync();<br>  final archive = ZipDecoder().decodeBytes(bytes);<br>  final content = archive.findFile(&#39;meta.json&#39;).content;<br>  final data = json.decode(utf8.decode(content));<br>  print(JsonEncoder.withIndent(&#39;  &#39;).convert(data));<br>}</pre><p>This should emit the data struture shown above.</p><p>If you follow along with your own Sketch file, expect the UUID to be different. Still, there should be a pagesAndArtboards property that lists at lease one page with zero or more artboards.</p><h4>Extracting Artboards</h4><p>To extract artboards, I create an abstract Element class of which Artboard (as well as Page and later all other graphical elements) is a subclass. I decide to use computed fields (a.k.a. getter methods) to access all information instead of storing everything in instance variables. This might be less efficient, but it is also less code to write:</p><pre>abstract class Element {<br>  Element(this.data);</pre><pre>  final Map data;</pre><pre>  String get name =&gt; data[&#39;name&#39;];</pre><pre>  String get clazz =&gt; data[&#39;_class&#39;];</pre><pre>  String get id =&gt; data[&#39;do_objectID&#39;];</pre><pre>  Iterable&lt;Element&gt; get layers =&gt; <br>    (data[&#39;layers&#39;] as List).map((child) =&gt; Element.create(child));</pre><pre>  ...</pre><p>To create concrete element subclasses, I use a static Element.create method. It needs to know about every mapping from a Sketch class name to a Dart class (I use clazz because class is a reserved keyword in Dart):</p><pre>  ...</pre><pre>  static Element create(Map data) {<br>    final clazz = data[&#39;_class&#39;];<br>    switch (clazz) {<br>      case &#39;artboard&#39;:<br>        return Artboard(data);<br>      case &#39;page&#39;:<br>        return Page(data);<br>      default:<br>        throw &#39;Unknown element class $clazz&#39;;<br>    }<br>  }<br>}</pre><p>Here are the first two element subclasses:</p><pre>class Artboard extends Element {<br>  Artboard(Map data) : super(data);<br>}</pre><pre>class Page extends Element {<br>  Page(Map data) : super(data);</pre><pre>  Iterable&lt;Artboard&gt; get artboards =&gt; layers.whereType&lt;Artboard&gt;();<br>}</pre><p>For convenience, I also added an artboards getter to Page.</p><p>The task of reading a .sketch file and of providing access to all artboards is performed by this File class. To omit name clashes, I put all my classes into a new sketch.dart package which I will import with the name prefix sk.</p><pre>class File {<br>  final Map&lt;String, Artboard&gt; artboards = {};</pre><pre>  File(List&lt;int&gt; bytes) {<br>    final archive = ZipDecoder().decodeBytes(bytes);<br>    final content = archive.findFile(&#39;meta.json&#39;).content;<br>    final data = json.decode(utf8.decode(content));<br>    Map paa = data[&#39;pagesAndArtboards&#39;];<br>    for (final k1 in paa.keys) {<br>      final content = archive.findFile(&#39;pages/$k1.json&#39;).content;<br>      final data = json.decode(utf8.decode(content));<br>      final page = Page(data);<br>      for (final artboard in page.artboards) {<br>        artboards[artboard.name] = artboard;<br>      }<br>    }<br>  }</pre><pre>  static Future&lt;File&gt; named(String name) async {<br>    return File(await io.File(name).readAsBytes());<br>  }<br>}</pre><p>Here is the new main function:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:sketch_flutter/sketch.dart&#39; as sk;</pre><pre>void main() async {<br>  final file = await sk.File.named(&#39;example.sketch&#39;);<br>  final a = file.artboards[&#39;First&#39;];<br>  print(JsonEncoder.withIndent(&#39;  &#39;).convert(a.data));<br>}</pre><p>It should print the same data structure as before.</p><p>But now everything is nicely encapulated.</p><h3>Drawing Elements</h3><p>I could and probably should make my code indenpendent of Flutter. However, then, I have to create my own classes for common concepts like Rect, Color or the attributed strings used by Sketch and then define helper methods to convert them to Flutter (resp. dart:ui) equivalents. Because this is a proof of concept, I will make it dependent on Flutter because then I don’t have to create an ElementVisitor and other abstractions to separate the concerns.</p><h4>Missing Elements</h4><p>Looking at the JSON output, my artboards contain rectangle, text, group, and shapPath classes. Let’s define subclasses (not shown here) and add them to Element.create:</p><pre>static Element create(Map data) {<br>    final clazz = data[&#39;_class&#39;];<br>    switch (clazz) {<br>      case &#39;artboard&#39;:<br>        return Artboard(data);<br>        case &#39;group&#39;:<br>        return Group(data);<br>      case &#39;rectangle&#39;:<br>        return Rectangle(data);<br>      case &#39;page&#39;:<br>        return Page(data);<br>      case &#39;shapePath&#39;:<br>        return ShapePath(data);<br>      case &#39;text&#39;:<br>        return Text(data);<br>      default:<br>        throw &#39;Unknown element class $clazz&#39;;<br>    }<br>  }<br>}</pre><p>Because all elements have a frame let’s use that to draw rectangles on a canvas to learn more about the coordinate of Sketch.</p><h4>Sketching the Design</h4><p>Here is the usual boiler-plate code to setup a Flutter app:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;sketch.dart&#39; as sk;</pre><pre>void main() =&gt; runApp(MyApp());</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: SketchPage(),<br>    );<br>  }<br>}</pre><p>The SketchPage widget loads my example (which shouldn’t be hard-coded) from the application’s assets and uses a CustomPaint widget to draw the first artboard.</p><pre>class SketchPage extends StatelessWidget {<br>  Future&lt;sk.Artboard&gt; _loadArtboard(BuildContext context) {<br>    final bundle = DefaultAssetBundle.of(context);<br>    return bundle.load(&#39;example.sketch&#39;).then((asset) {<br>      final bytes = asset.buffer.asUint8List();<br>      return sk.File(bytes).artboards[&#39;First&#39;];<br>    });<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: FutureBuilder&lt;sk.Artboard&gt;(<br>        future: _loadArtboard(context),<br>        builder: (context, snapshot) {<br>          if (snapshot.hasError) return Text(&#39;${snapshot.error}&#39;);<br>          if (!snapshot.hasData) return CircularProgressIndicator();<br>          final artboard = snapshot.data;<br>          return CustomPaint(<br>            size: artboard.frame.size,<br>            painter: ArtboardPainter(artboard),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>The most important class is of course the ArtboardPainter. It will stroke rectangles for each and every element, descending recursively:</p><pre>class ArtboardPainter extends CustomPainter {<br>  final sk.Artboard artboard;</pre><pre>  ArtboardPainter(this.artboard);</pre><pre>  @override<br>  void paint(Canvas canvas, Size size) {<br>    _draw(artboard, canvas);<br>  }</pre><pre>  void _draw(sk.Element e, Canvas canvas) {<br>    final p = Paint()<br>      ..color = Colors.black<br>      ..style = PaintingStyle.stroke;<br>    canvas.drawRect(e.frame, p);<br>    for (final c in e.layers) _draw(c, canvas);<br>  }</pre><pre>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return true;<br>  }<br>}</pre><p>Of course, I have to implement frame in Element. I also noticed that I layers can be null, so I had to change that accessor slightly:</p><pre>abstract class Element {<br>  ...</pre><pre>  ui.Rect get frame {<br>    final frame = data[&#39;frame&#39;];<br>    assert(frame[&#39;_class&#39;] == &#39;rect&#39;);<br>    return ui.Rect.fromLTWH(<br>      frame[&#39;x&#39;].toDouble(),<br>      frame[&#39;y&#39;].toDouble(),<br>      frame[&#39;width&#39;].toDouble(),<br>      frame[&#39;height&#39;].toDouble(),<br>    );<br>  }</pre><pre>  Iterable&lt;Element&gt; get layers =&gt; (data[&#39;layers&#39;] as List)?<br>      .map((child) =&gt; Element.create(child)) ?? [];</pre><pre>  ...</pre><p>The result isn’t too bad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*Hk010eOweTFKixq_XDeYmA.png" /></figure><p>It looks like that child elements have a relative coordinate system (which is a sensible design decision). I also noticed that the artboard’s frame denotes the position on the page which is something, I don’t want, so I will override the frame getter for Artboard like so:</p><pre>class Artboard extends Element {<br>  ...</pre><pre>  @override<br>  ui.Rect get frame =&gt; ui.Offset.zero &amp; super.frame.size;<br>}</pre><p>Then, let’s translate the coordinate system before applying the recursion:</p><pre>class ArtboardPainter extends CustomPainter {<br>  ...</pre><pre>  void _draw(sk.Element e, Canvas canvas) {<br>    final p = Paint()<br>      ..color = Colors.black<br>      ..style = PaintingStyle.stroke;<br>    canvas.drawRect(e.frame, p);<br>    canvas.save();<br>    canvas.translate(e.frame.left, e.frame.top);<br>    for (final c in e.layers) _draw(c, canvas);<br>    canvas.restore();<br>  }</pre><pre>  ...</pre><p>Now, it looks right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*sA-PZki5P7WLxNtBv7rYgg.png" /></figure><p>By the way, I picked a simulator with the same size as the artboards to minimize the problems. I actually used the resize hints supported by Sketch but for this proof of concept, I will not try to implement them. I assume Sketch uses the same <em>autoresizing</em> algorithms as implemented by macOS resp. iOS.</p><h4>Adding Color</h4><p>Black strokes are boring. Let’s add color. Digging into the JSON, it seems that the style property has borders and fills properties, which are lists of <em>border</em> or <em>fill</em> objects which have a color property which is an RGBA value.</p><p>Here’s the code to represent those styles:</p><pre>class Border {<br>  final Map data;</pre><pre>  Border(this.data) : assert(data[&#39;_class&#39;] == &#39;border&#39;);</pre><pre>  bool get isEnabled =&gt; data[&#39;isEnabled&#39;];</pre><pre>  ui.Color get color =&gt; Style._createColor(data[&#39;color&#39;]);</pre><pre>  double get thickness =&gt; data[&#39;thickness&#39;].toDouble();<br>}</pre><pre>class Fill {<br>  final Map data;</pre><pre>  Fill(this.data) : assert(data[&#39;_class&#39;] == &#39;fill&#39;);</pre><pre>  bool get isEnabled =&gt; data[&#39;isEnabled&#39;];</pre><pre>  ui.Color get color =&gt; Style._createColor(data[&#39;color&#39;]);<br>}</pre><pre>class Style {<br>  final Map data;</pre><pre>  Style(this.data) : assert(data[&#39;_class&#39;] == &#39;style&#39;);</pre><pre>  List&lt;Border&gt; get borders =&gt; (data[&#39;borders&#39;] as List)?<br>    .map((b) =&gt; Border(b))?.where((b) =&gt; b.isEnabled) ?? [];</pre><pre>  Iterable&lt;Fill&gt; get fills =&gt; (data[&#39;fills&#39;] as List)?<br>    .map((f) =&gt; Fill(f))?.where((f) =&gt; f.isEnabled) ?? [];</pre><pre>  static ui.Color _createColor(Map data) {<br>    assert(data[&#39;_class&#39;] == &#39;color&#39;);<br>    return ui.Color.fromARGB(<br>      (255 * data[&#39;alpha&#39;].toDouble()).round(),<br>      (255 * data[&#39;red&#39;].toDouble()).round(),<br>      (255 * data[&#39;green&#39;].toDouble()).round(),<br>      (255 * data[&#39;blue&#39;].toDouble()).round(),<br>    );<br>  }<br>}</pre><p>Then I add a style getter method to Element:</p><pre>abstract class Element {<br>  ...</pre><pre>  Style get style =&gt; Style(data[&#39;style&#39;]);</pre><p>Next, I refactor the way the elements are rendered by the ArtboardPainter. Instead of doing everything in that class, I delegate this to the Element by adding a render method like so:</p><pre>  ...</pre><pre>  void render(ui.Canvas canvas) {<br>    final p = ui.Paint()<br>      ..color = ui.Color(0xFF000000)<br>      ..style = ui.PaintingStyle.stroke;<br>    canvas.drawRect(frame, p);<br>    renderChildren(canvas);<br>  }</pre><pre>  void renderChildren(ui.Canvas canvas) {<br>    canvas.save();<br>    canvas.translate(frame.left, frame.top);<br>    for (final c in layers) c.render(canvas);<br>    canvas.restore();<br>  }</pre><p>This greatly simplifies the ArtboardPainter class:</p><pre>class ArtboardPainter extends CustomPainter {<br>  final sk.Artboard artboard;</pre><pre>  ArtboardPainter(this.artboard);</pre><pre>  @override<br>  void paint(Canvas canvas, Size size) {<br>    artboard.render(canvas);<br>  }</pre><pre>  @override<br>  bool shouldRepaint(ArtboardPainter oldDelegate) {<br>    return oldDelegate.artboard != artboard;<br>  }<br>}</pre><p>Then, I override render for Rectangle to finally add color:</p><pre>class Rectangle extends Element {<br>  Rectangle(Map data) : super(data);</pre><pre>  @override<br>  void render(ui.Canvas canvas) {<br>    if (style.fills.isNotEmpty) {<br>      final color = style.fills.first.color;<br>      canvas.drawRect(frame, ui.Paint()..color = color);<br>    }<br>  }<br>}</pre><p>Now, the artboards should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*ktylUJ8ONFlvJGNMU_Y3fA.png" /></figure><h4>Displaying Text</h4><p>Let’s display text next. Again, I’m guessing the structure by looking at the JSON. A Text element has a style with a textStyle property, which I could encapsulate as a Flutter TextStyle class. However, I don’t think, I need to use it. Instead, I’m looking at the attributedString property which I need to convert into a Flutter TextSpan. The atttributed string holds string attributes which describe the font family, the font size and the color (besides other attributes I will ignore). Instead, I will always center the text.</p><p>The following code is a bit hacky, I tried to implement the minimum to get some text on the screen, taking a few shortcuts. Unfortunately, I had to add a dependency not only to dart:ui but also to flutter/widgets.dart because I need TextSpan and TextStyle.</p><pre>class Text extends Element {<br>  Text(Map data) : super(data);</pre><pre>  TextSpan get text {<br>    final str = data[&#39;attributedString&#39;];<br>    assert(str[&#39;_class&#39;] == &#39;attributedString&#39;);<br>    final string = str[&#39;string&#39;] as String;<br>    final spans = &lt;TextSpan&gt;[];<br>    for (Map a in str[&#39;attributes&#39;]) {<br>      assert(a[&#39;_class&#39;] == &#39;stringAttribute&#39;);</pre><pre>      int location = a[&#39;location&#39;].toInt();<br>      int length = a[&#39;length&#39;].toInt();<br>      final text = string.substring(location, location + length);</pre><pre>      final aa = a[&#39;attributes&#39;];<br>      final fa = aa[&#39;MSAttributedStringFontAttribute&#39;];<br>      final fn = fa != null <br>        ? fa[&#39;attributes&#39;][&#39;name&#39;].toString() : null;<br>      final fs = fa != null <br>        ? fa[&#39;attributes&#39;][&#39;size&#39;].toDouble() : null;<br>      final ca = aa[&#39;MSAttributedStringColorAttribute&#39;];<br>      final style = TextStyle(<br>        fontFamily: fn != null <br>          ? _fontFamilyMapping[fn] ?? fn : null,<br>        fontWeight: _fontWeightMapping[fn],<br>        fontSize: fs,<br>        color: ca != null ? Style._createColor(ca) : null,<br>      );<br>      spans.add(TextSpan(<br>        text: text,<br>        style: style,<br>      ));<br>    }<br>    if (spans.isEmpty) return TextSpan(text: &#39;&#39;);<br>    if (spans.length == 1) return spans.first;<br>    return TextSpan(children: spans);<br>  }</pre><pre>  @override<br>  void render(ui.Canvas canvas) {<br>    final p = TextPainter(<br>      text: text,<br>      textDirection: TextDirection.ltr,<br>      textAlign: TextAlign.center,<br>    );<br>    final f = frame;<br>    p.layout(maxWidth: f.width);<br>    p.paint(<br>      canvas,<br>      Offset(<br>        f.left + (f.width - p.size.width) / 2,<br>        f.top + (f.height - p.size.height) / 2,<br>      ),<br>    );<br>  }</pre><pre>  static const _fontFamilyMapping = {<br>    &#39;AmericanTypewriter&#39;: &#39;American Typewriter&#39;,<br>    &#39;AmericanTypewriter-Bold&#39;: &#39;American Typewriter&#39;,<br>  };</pre><pre>  static const _fontWeightMapping = {<br>     &#39;AmericanTypewriter-Bold&#39;: FontWeight.bold,<br>  };<br>}</pre><p>It took me some trial and error to learn that Flutter needs a space in the font family name. Therefore, I created some simply mapping table one could extend with more entries. Sketch also encodes the font weight only in the font name, so I had to map this, too.</p><p>But the screens are displayed nearly correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*zK2xkbkCi2W9044SS6_6QA.png" /></figure><h4>Drawing Shapes</h4><p>To draw the back button shape on the second screen, I need to decode the points property of the ShapePath class. For this proof of concept, I don’t bother with splines or bézier curves, just simple vectors.</p><p>Looking at the JSON, I find it quite strange that points are actually represented by strings which also contains curly braces. Whatever, here’s some code to render the lines:</p><pre>class ShapePath extends Element {<br>  ShapePath(Map data) : super(data);</pre><pre>  bool get isClosed =&gt; data[&#39;isClosed&#39;];</pre><pre>  Iterable&lt;CurvePoint&gt; get points =&gt; <br>    (data[&#39;points&#39;] as List)?.map((p) =&gt; CurvePoint(p)) ?? [];</pre><pre>  @override<br>  void render(ui.Canvas canvas) {<br>    final f = frame;<br>    var path = Path();<br>    var first = true;<br>    for (final c in points) {<br>      final pt = c.point;<br>      final x = f.left + pt.dx * f.width;<br>      final y = f.top + pt.dy * f.height;<br>      if (first) {<br>        first = false;<br>        path.moveTo(x, y);<br>      } else {<br>        path.lineTo(x, y);<br>      }<br>    }<br>    if (isClosed) path.close();</pre><pre>    final b = style.borders.first;<br>    canvas.drawPath(<br>        path,<br>        Paint()<br>          ..color = b.color<br>          ..strokeWidth = b.thickness<br>          ..style = PaintingStyle.stroke);<br>  }<br>}</pre><pre>class CurvePoint {<br>  final Map data;</pre><pre>  CurvePoint(this.data) : assert(data[&#39;_class&#39;] == &#39;curvePoint&#39;);</pre><pre>  ui.Offset get point =&gt; _decode(data[&#39;point&#39;]);</pre><pre>  static ui.Offset _decode(String s) {<br>    final parts = s.substring(1, s.length - 1).split(&#39;,&#39;);<br>    return ui.Offset(<br>      double.parse(parts[0]), <br>      double.parse(parts[1]),<br>    );<br>  }<br>}</pre><p>After making the Group no longer display its rectangle, I’m done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ROywFV5jXUnemYAlWdQHiw.png" /></figure><h3>Navigation</h3><p>The last thing that remains it implementing the navigation. Searching the JSON reveals these data structures:</p><pre>&quot;flow&quot;: {<br>  &quot;_class&quot;: &quot;MSImmutableFlowConnection&quot;,<br>  &quot;do_objectID&quot;: &quot;45E1A3D8-591A-4D01-B04B-36B58CA4CE51&quot;,<br>  &quot;animationType&quot;: 0,<br>  &quot;destinationArtboardID&quot;: &quot;49F995AB-4992-42AB-B708-86C5C42B3CDB&quot;<br>},</pre><pre>...</pre><pre>&quot;flow&quot;: {<br>  &quot;_class&quot;: &quot;MSImmutableFlowConnection&quot;,<br>  &quot;do_objectID&quot;: &quot;84BEAFDE-FFCE-42E5-8614-1AFC1FED8A19&quot;,<br>  &quot;animationType&quot;: 0,<br>  &quot;destinationArtboardID&quot;: &quot;back&quot;<br>},</pre><p>An Element has an optional Flow object that defines the destination by referencing the artboard object identifier or the “magic” string back. Sketch supports multiple animations (I use the default, which is called “from the right”).</p><h4>Dart Part</h4><p>Here is my Dart implementation:</p><pre>class Flow {<br>  final Map data;</pre><pre>  Flow(this.data) <br>    : assert(data[&#39;_class&#39;] == &#39;MSImmutableFlowConnection&#39;);</pre><pre>  String get destination =&gt; data[&#39;destinationArtboardID&#39;];</pre><pre>  bool get isBack =&gt; destination == &#39;back&#39;;<br>}</pre><p>Then, I add a getter method to Element:</p><pre>abstract class Element {<br>  ...</pre><pre>  Flow get flow =&gt; data[&#39;flow&#39;] != null ? Flow(data[&#39;flow&#39;]) : null;<br>}</pre><p>In Sketch, I marked my first artboard as the initial screen. So I searched for an indicator in the JSON and eventually found a isFlowHome property. Let’s use this property to find the initial artboard to display instead of hardcoding its name:</p><pre>class Artboard extends Element {<br>  ...</pre><pre>  bool get isFlowHome =&gt; data[&#39;isFlowHome&#39;];<br>}</pre><pre>class File {<br>  ...</pre><pre>  Artboard get initialArtboard =&gt; <br>    artboards.values.firstWhere((a) =&gt; a.isFlowHome);</pre><pre>  Artboard artboardById(String id) =&gt; <br>   artboards.values.firstWhere((a) =&gt; a.id == id);</pre><pre>  ...<br>}</pre><h4>Flutter Part</h4><p>To implement the navigation, I use a GestureDetector to detect a tap, then use the context’s render box to compute the offset relative to the widget and then search the current artboard’s hierarchy for the element that was hit. If there is such an element and if it has a Flow object, I change the scene.</p><p>I refactor MyApp to load the Sketch file once:</p><pre>class MyApp extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: FutureBuilder&lt;sk.File&gt;(<br>        future: _load(context),<br>        builder: (context, snapshot) {<br>          if (!snapshot.hasData) return LoadingPage();<br>          final file = snapshot.data;<br>          return SketchPage(file, file.initialArtboard);<br>        },<br>      ),<br>    );<br>  }</pre><pre>  Future&lt;sk.File&gt; _load(BuildContext context) {<br>    final bundle = DefaultAssetBundle.of(context);<br>    return bundle.load(&#39;example.sketch&#39;).then((asset) {<br>      return sk.File(asset.buffer.asUint8List());<br>    });<br>  }<br>}</pre><p>This LoadingPage can be as fancy as you like:</p><pre>class LoadingPage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(child: CircularProgressIndicator()),<br>    );<br>  }<br>}</pre><p>The new SketchPage deals with navigation and delegates everything else to a SketchArtboard widget.</p><pre>class SketchPage extends StatelessWidget {<br>  SketchPage(this.file, this.artboard);</pre><pre>  final sk.File file;<br>  final sk.Artboard artboard;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Artboard(<br>        onPressed: (flow) =&gt; _navigate(context, flow),<br>        artboard: artboard,<br>      ),<br>    );<br>  }</pre><pre>  void _navigate(BuildContext context, sk.Flow flow) {<br>    if (flow.isBack) {<br>      Navigator.pop(context);<br>    } else {<br>      Navigator.push(<br>        context,<br>        MaterialPageRoute(<br>          builder: (_) =&gt; SketchPage(<br>                file,<br>                file.artboardById(flow.destination),<br>              ),<br>        ),<br>      );<br>    }<br>  }<br>}</pre><p>Here’s the new Artboard widget that detects gestures and uses a hit test algorithm in Element to find the element that was tapped and returns its flow object, if there is one.</p><pre>class Artboard extends StatelessWidget {<br>  const Artboard({<br>    Key key,<br>    @required this.onPressed,<br>    @required this.artboard,<br>  }) : super(key: key);</pre><pre>  final ValueChanged&lt;sk.Flow&gt; onPressed;<br>  final sk.Artboard artboard;</pre><pre>  @override<br>  build(BuildContext context) {<br>    return GestureDetector(<br>      onTapUp: (details) {<br>        RenderBox box = context.findRenderObject();<br>        final offset = box.globalToLocal(details.globalPosition);<br>        final flow = artboard.hit(offset);<br>        if (flow != null) onPressed(flow);<br>      },<br>      child: CustomPaint(<br>        size: artboard.frame.size,<br>        painter: ArtboardPainter(artboard),<br>      ),<br>    );<br>  }<br>}</pre><p>Here is the hit method of Element:</p><pre>abstract class Element {<br>  ...</pre><pre>  Flow hit(ui.Offset offset) {<br>    if (!frame.contains(offset)) return null;<br>    final localOffset = offset - frame.topLeft;<br>    for (final child in layers) {<br>      final flow = child.hit(localOffset);<br>      if (flow != null) return flow;<br>    }<br>    return flow;<br>  }<br>}</pre><p>This was the last piece of the puzzle. I can navigate between multiple SketchPage widgets created from (simple) Sketch artboards. I proudly present an animation of the final app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*kA3xKKe3XqKu8JKEqRlqCA.gif" /></figure><h3>Bottom Line</h3><p>There’s of course a lot of stuff missing. Sketch has more basic elements, they can be transformed, they can be grouped and reused as symbols, there are complex paths, gradients, shadows and much more. Then, there’s the challenge to scale the UI to other screen sizes. But that’s — hopefully — just more of the same.</p><p>It would be also very interesting to convert a Sketch design into true Flutter widgets like buttons and input fields. However, this would require a very different layout than the way Flutter normally works and therefore, I didn’t follow that path.</p><p>If you’re interested in the source code or what to help to add more features, please leave a comment below, we’re happy to open souce it.</p><p>Thanks for reading this article and please check out my other articles, too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ceec716ca2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/icnh/creating-a-flutter-app-from-sketch-89ceec716ca2">Creating a Flutter App from Sketch</a> was originally published in <a href="https://medium.com/icnh">ICNH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>