Skip to content

Instantly share code, notes, and snippets.

@eernstg
Last active July 19, 2024 13:31
Show Gist options
  • Save eernstg/deadb7ff8237799cf2b1d8ddfa85caa4 to your computer and use it in GitHub Desktop.
Save eernstg/deadb7ff8237799cf2b1d8ddfa85caa4 to your computer and use it in GitHub Desktop.
Example from 'Cutting the stateful boilerplate' using likely Dart features (primary constructors, inferred `required`, `override`)
import 'package:flutter/material.dart';
// Assumptions:
// * Dart has primary constructors.
// * Dart supports `override`, and override inference
// is considered appropriate.
// * The named parameter `String name` can omit `required`
// because it is inferred.
void main() {
runApp(const App(name: 'Dash'));
}
class const App(String name) {
override build(context) {
return MaterialApp(
home: Counter(
name: name,
startValue: 10,
),
);
}
}
class const Counter({
super.key,
String name,
int startValue = 0,
}): assert(startValue >= 0) extends StatefulWidget {
override State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
override build(context) {
return Scaffold(
appBar: AppBar(title: Text('Hello ${widget.name}')),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_count += 1;
});
},
),
body: Center(
child: Text('Count: ${widget.startValue + _count}'),
),
);
}
}
@eernstg
Copy link
Author

eernstg commented Jul 19, 2024

It might still be convenient to use a macro @Stateful to generate createState and add the superclass:

@Stateful(_CounterState)
class const Counter({
  super.key,
  String name,
  int startValue = 0,
}): assert(startValue >= 0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment