Created
June 25, 2023 23:45
-
-
Save christopherfujino/e30cc1ff36b60118de79168de7f0d68e to your computer and use it in GitHub Desktop.
Minimal implementation of InheritedWidget
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'; | |
void main() => runApp( | |
StateWrapper( | |
MaterialApp( | |
home: Scaffold( | |
body: App(), | |
), | |
), | |
), | |
); | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext ctx) { | |
final state = InheritedState.of(ctx); | |
return Column(children: <Widget>[ | |
Text('You pressed the button ${state.x} times.'), | |
TextButton( | |
onPressed: () { | |
state.updateX(state.x + 1); | |
}, | |
child: const Icon(Icons.add), | |
), | |
]); | |
} | |
} | |
class StateWrapper extends StatefulWidget { | |
const StateWrapper(this.child, {super.key}); | |
@override | |
State<StateWrapper> createState() => _WrapperState(); | |
final Widget child; | |
} | |
class _WrapperState extends State<StateWrapper> { | |
int x = 0; | |
@override | |
Widget build(BuildContext _) => InheritedState( | |
x, | |
(int nextX) => setState(() => x = nextX), | |
child: widget.child, | |
); | |
} | |
class InheritedState extends InheritedWidget { | |
const InheritedState(this.x, this.updateX, {super.key, required super.child}); | |
final int x; | |
final void Function(int) updateX; | |
@override | |
bool updateShouldNotify(InheritedState old) => x != old.x; | |
static InheritedState of(BuildContext ctx) { | |
return ctx.dependOnInheritedWidgetOfExactType<InheritedState>()!; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment