Skip to content

Instantly share code, notes, and snippets.

@felangel
Last active June 19, 2020 00:05
Show Gist options
  • Save felangel/9fa7296f76d6aae41cf5c05a0710f664 to your computer and use it in GitHub Desktop.
Save felangel/9fa7296f76d6aae41cf5c05a0710f664 to your computer and use it in GitHub Desktop.
StatefulRebuilder
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: MyChild(),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() {}),
child: Icon(Icons.refresh),
),
);
}
}
class MyChild extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StatefulRebuilder<int>(
initState: (context) => 10,
builder: (context, state, setState) {
return Center(
child: RaisedButton(
child: Text('${state.value}'),
onPressed: () => setState(() => state.value++),
),
);
},
);
}
}
class StatefulRebuilder<T> extends StatefulWidget {
final T Function(BuildContext) initState;
final Widget Function(
BuildContext,
StateWrapper<T> state,
StateSetter setState,
) builder;
StatefulRebuilder({
Key key,
@required this.initState,
@required this.builder,
}) : super(key: key);
@override
State<StatefulRebuilder<T>> createState() => _StatefulBuilderState<T>();
}
class _StatefulBuilderState<T> extends State<StatefulRebuilder<T>> {
StateWrapper<T> _state;
@override
void initState() {
super.initState();
_state = StateWrapper(widget.initState(context));
}
@override
Widget build(BuildContext context) {
return widget.builder(context, _state, setState);
}
}
class StateWrapper<T> {
T value;
StateWrapper(this.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment