Last active
July 19, 2024 13:31
-
-
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`)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}'), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It might still be convenient to use a macro
@Stateful
to generatecreateState
and add the superclass: