Skip to content

Instantly share code, notes, and snippets.

@yjbanov
Created May 9, 2024 00:08
Show Gist options
  • Save yjbanov/eb1c59002f80a01f2eaed524cb733b56 to your computer and use it in GitHub Desktop.
Save yjbanov/eb1c59002f80a01f2eaed524cb733b56 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp(name: 'Dash'));
}
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Counter(
name: name,
startValue: 10,
),
);
}
}
// The stateful parts of the counter class
mixin CounterState on State<Counter> {
int count = 0;
}
class Counter extends GeneratedStatefulWidget<_GeneratedCounterState> {
const Counter({super.key, required this.name, required this.startValue});
final String name;
final int startValue;
@override
Widget build(CounterState state) {
final ThemeData theme = Theme.of(state.context);
return Scaffold(
appBar: AppBar(title: Text('Hello $name', style: theme.textTheme.bodyLarge)),
floatingActionButton: FloatingActionButton(
onPressed: () {
state.count += 1;
},
),
body: Center(
child: Text('Count: ${startValue + state.count}'),
),
);
}
//////////////// GENERATED ///////////////////////////
@override
State<StatefulWidget> createState() => _GeneratedCounterState();
}
abstract class GeneratedStatefulWidget<S extends State> extends StatefulWidget {
const GeneratedStatefulWidget({super.key});
Widget build(S state);
}
class _GeneratedCounterState extends State<Counter> with CounterState {
@override
set count(int value) {
// Since this is generated code, it can be optimized to not incur the cost
// of an extra closure. Instead, it could just directly call markNeedsBuild(),
// which is way cheaper.
setState(() {
super.count = value;
});
}
@override
Widget build(BuildContext context) {
return widget.build(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment