Glutter for Flutter developers
The rules that turn Flutter's API into Go, with Dart and Go side by side, and the few things that are not the same.
Glutter has Flutter’s framework API on its own engine, so what you know carries over: the widget tree, BuildContext, setState, Theme.of, Navigator, animation controllers, CustomPaint. Dart and Go are different languages, though, so the API follows a few rules. Once you know them, you can guess the Go name of almost anything in Flutter.
The snippets use one import:
import m "github.com/rm4n0s/glutter/material"
Some of them also use context and strconv of the standard library.
The rules#
| In Flutter | In Glutter |
|---|---|
A constructor, Text('Hi') | A function, m.NewText("Hi") |
| Required parameters | Arguments, in Flutter’s order; child and children come last |
| Optional named parameters | Fields of an options struct XOpts, with Flutter’s names |
A nullable parameter whose null is not zero | m.Some(value) |
A named constructor, ListView.builder | m.NewListViewBuilder |
A static method, Theme.of(context) | m.ThemeOf(bc) |
maybeOf, which may return null | Returns (value, ok) |
A property, widget.title | A method, w.Title() |
State<Counter> | m.StateOf[*Counter] |
A Future<T> | A function that takes a context.Context and returns (T, error) |
A Stream<T> | A channel, <-chan T |
Every enum’s zero value is XUnspecified, which means “the widget’s default”.
A widget without state#
Flutter:
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Text('Hello, $name', style: Theme.of(context).textTheme.titleLarge),
);
}
}
Glutter:
type Greeting struct {
m.StatelessWidget
name string
}
func NewGreeting(name string, opts ...m.WidgetOpts) *Greeting {
return &Greeting{StatelessWidget: m.NewStatelessWidgetBase(opts...), name: name}
}
func (g *Greeting) Name() string { return g.name }
func (g *Greeting) Build(bc m.BuildContext) m.Widget {
return m.NewPadding(m.NewEdgeInsetsAll(16),
m.NewText("Hello, "+g.name, m.TextOpts{Style: m.ThemeOf(bc).TextTheme.TitleLarge}))
}
The widget embeds m.StatelessWidget, Flutter’s superclass. The key is the Key field of m.WidgetOpts, which the constructor passes on.
A widget with state#
Flutter:
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _count++),
child: Text('Pushed $_count times'),
);
}
}
Glutter:
type Counter struct{ m.StatefulWidget }
func NewCounter(opts ...m.WidgetOpts) *Counter {
return &Counter{StatefulWidget: m.NewStatefulWidgetBase(opts...)}
}
func (c *Counter) CreateState() m.State { return &counterState{} }
type counterState struct {
m.StateOf[*Counter]
count int
}
func (s *counterState) Build(bc m.BuildContext) m.Widget {
return m.NewTextButton(
func() { s.SetState(func() { s.count++ }) },
m.NewText("Pushed "+strconv.Itoa(s.count)+" times"))
}
m.StateOf[*Counter] gives s.Widget() (Flutter’s widget), s.Context(), s.SetState(...) and the lifecycle methods that you override: InitState, DidUpdateWidget and Dispose. onPressed is a required parameter, so it is an argument, and nil disables the button, as null does in Flutter.
Layout, with options#
Flutter:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Title'),
const SizedBox(height: 8),
Row(children: [
const Expanded(child: Text('Left')),
Container(width: 80, color: Colors.amber, child: const Text('Right')),
]),
],
)
Glutter:
func layout() m.Widget {
return m.NewColumn([]m.Widget{
m.NewText("Title"),
m.NewSizedBox(nil, m.SizedBoxOpts{Height: m.Some(8.0)}),
m.NewRow([]m.Widget{
m.NewExpanded(m.NewText("Left")),
m.NewContainer(m.NewText("Right"), m.ContainerOpts{
Width: m.Some(80.0),
Color: m.Some(m.Colors.Amber.Primary),
}),
}),
}, m.ColumnOpts{CrossAxisAlignment: m.CrossAxisAlignmentStart})
}
children is the first argument because Column has nothing required before it. The child of Expanded and Container is the first argument as well, and nil stands for “no child”. width: 80 is m.Some(80.0), since a null width means “not constrained” and 0 is a width.
Named constructors and builders#
Flutter:
ListView.builder(
itemCount: names.length,
itemBuilder: (context, i) => ListTile(
leading: const Icon(Icons.person),
title: Text(names[i]),
onTap: () => debugPrint('tapped $i'),
),
)
Glutter:
func nameList(names []string) m.Widget {
return m.NewListViewBuilder(func(bc m.BuildContext, i int) m.Widget {
return m.NewListTile(m.ListTileOpts{
Leading: m.NewIcon(m.Icons.Person()),
Title: m.NewText(names[i]),
OnTap: func() { println("tapped", i) },
})
}, m.ListViewOpts{ItemCount: m.Some(len(names))})
}
ListView.builder is NewListViewBuilder. The builder is a required parameter, so it is an argument. Icons.person is the method m.Icons.Person(): 8,800 icons as fields would make the Go compiler run out of memory.
Inherited data and of#
Flutter:
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final width = MediaQuery.sizeOf(context).width;
return Container(
color: width > 600 ? scheme.primaryContainer : scheme.surface,
child: TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
);
}
Glutter:
func buildResponsive(bc m.BuildContext) m.Widget {
scheme := m.ThemeOf(bc).ColorScheme
width := m.MediaQuerySizeOf(bc).Width
color := scheme.Surface()
if width > 600 {
color = scheme.PrimaryContainer()
}
return m.NewContainer(
m.NewTextButton(func() { m.NavigatorPop(bc) }, m.NewText("Close")),
m.ContainerOpts{Color: m.Some(color)})
}
Static methods are functions named after the class: ThemeOf, MediaQuerySizeOf, NavigatorPop. The colors of a ColorScheme are methods, such as scheme.Surface(), because the scheme computes the ones that were not set from the others.
Navigation and results#
In Dart, the result of a route is the Future of the push. In Glutter it is a channel.
Flutter:
Future<void> pick(BuildContext context) async {
final color = await Navigator.of(context).push<String>(
MaterialPageRoute(builder: (context) => const PickerPage()),
);
if (color != null) setState(() => picked = color);
}
Glutter:
type Picker struct{ m.StatefulWidget }
type pickerState struct {
m.StateOf[*Picker]
picked string
}
func (s *pickerState) pick() {
result := m.NavigatorPush(s.Context(), m.NewMaterialPageRoute(func(bc m.BuildContext) m.Widget {
return m.NewScaffold(m.ScaffoldOpts{
Body: m.NewTextButton(func() { m.NavigatorPop(bc, "blue") }, m.NewText("Blue")),
})
}))
s.Go(func(ctx context.Context) {
select {
case v := <-result:
if color, ok := v.(string); ok {
s.SetState(func() { s.picked = color })
}
case <-ctx.Done():
}
})
}
NavigatorPush returns a <-chan any that gets the value once and is closed. State.Go runs the goroutine for you: its ctx ends when the state is disposed, so nothing outlives the widget. Only the UI goroutine may touch the framework, so the goroutine hands its result over with SetState.
Asynchronous data#
Flutter:
FutureBuilder<String>(
future: fetchGreeting(),
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
if (!snapshot.hasData) return const CircularProgressIndicator();
return Text(snapshot.data!);
},
)
Glutter:
func greeting() m.Widget {
return m.NewFutureBuilder(func(ctx context.Context) (string, error) {
return fetchGreeting(ctx)
}, func(bc m.BuildContext, snapshot m.AsyncSnapshot[string]) m.Widget {
if snapshot.HasError() {
return m.NewText("Error: " + snapshot.Error().Error())
}
if !snapshot.HasData() {
return m.NewCircularProgressIndicator()
}
return m.NewText(snapshot.Data())
})
}
The widget runs the function on its own goroutine, cancels the context when it is disposed, and builds with the snapshot on the UI thread. Everything that does I/O takes a ctx first, as in the rest of Go.
What is not the same#
- No
constwidgets. Go has no const constructors. Build a widget once and reuse it, as a package-level value or a field of the state. - Threads. The framework runs on one goroutine, the UI thread. There is no
asyncandawait: blocking is fine on your own goroutines, and they hand their work over withSetState.State.Gostarts a goroutine that is cancelled with the state. - Errors. A failure that can happen at run time is an
errorvalue. Panics are only for programmer errors. - Build modes.
flutter runmakes a debug build.go run,go buildandgo installmake a release build, the same asflutter build. Add-tags debug_modefor a debug build with Flutter’s asserts. - Hot reload is not possible in Go.
go runis fast. - Platform code. In place of
dart:io, plugins and platform channels there are the packages of Go’s standard library, and Glutter’sdesktoppackage: file dialogs, notifications, the tray, opening a URL.
Where to go next#
- Write your first Glutter app, if you have not yet.
- Glutter’s own guide goes on with animation, text input and forms, custom painting, fonts, SVG, the GPU, gamepads, audio and the Cupertino look, and has a section for the developers of each platform.
- The source of every app in the Playground shows these rules in a whole program.