Fair 2.0 Layout DSL Generation Principles
This article explains how the Fair 2.0 framework parses Dart source code into an AST, transforms the AST into a domain‑specific layout DSL, and handles variables, expressions, and method caching to enable dynamic UI updates in Flutter applications.
The Fair 2.0 project provides a dynamic framework for Flutter, allowing widgets to be updated at runtime by delivering compiled layout products. Because Flutter runs in AOT mode on release builds, Fair uses two separate strategies: layout dynamicization via a generated DSL and logic dynamicization by converting Dart code to JavaScript.
The overall workflow consists of two main steps. First, the fair_ast_gen tool parses Dart source files with the Dart analyzer, producing an AstMap . Second, fair_dsl_gen traverses the AST map and generates a JSON‑based DSL that describes the widget tree.
Key concepts include the Abstract Syntax Tree (AST) and Domain Specific Language (DSL). The AST provides a language‑agnostic representation of the source code, while the DSL encodes only the information needed for layout reconstruction.
During AST parsing, the analyzer’s parseFile function returns a CompilationUnit . A custom visitor, typically extending SimpleAstVisitor , walks the node tree and extracts relevant information such as class names, method signatures, and widget constructions.
DSL generation iterates over the AST nodes, focusing on the build method’s return expression. The resulting DSL is emitted as JSON for debugging and as FlatBuffers for production to reduce size and improve parsing speed.
Method caching (methodMap) is introduced to support nested widget‑building methods without altering the original code structure. Instead of restricting developers, Fair records auxiliary widget‑construction methods in methodMap so they can be invoked at runtime.
Variables and expressions are encoded with special prefixes to distinguish them from plain strings. For example:
Text('$_counter') => #($_counter) onPressed: _incrementCounter => @(incrementCounter)During DSL parsing, regular expressions detect these prefixes and bind the appropriate data or invoke the corresponding method.
In summary, Fair 2.0 leverages the Dart analyzer to extract an AST, refines the AST into a lightweight layout DSL, and uses method caching and prefixed placeholders to preserve dynamic behavior, enabling seamless hot‑updates of Flutter UI components.
58 Tech
Official tech channel of 58, a platform for tech innovation, sharing, and communication.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.