Last active
February 12, 2021 13:31
-
-
Save jtlapp/f81438723e46d1c6258fce68d3d6766c to your computer and use it in GitHub Desktop.
Counter app implemented with InheritedWidget
This file contains 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(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
// Counter app with InheritedWidget | |
class MyHomePage extends StatelessWidget { | |
Widget build(BuildContext context) { | |
return CounterWidget( | |
child: Scaffold( | |
appBar: AppBar( | |
title: Text("Page Title"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Builder(builder: (context) { | |
final inherited = | |
context.inheritFromWidgetOfExactType(_InheritedCount) | |
as _InheritedCount; | |
return Text( | |
'${inherited.state.count}', | |
style: Theme.of(context).textTheme.display1, | |
); | |
}), | |
Builder(builder: (context) { | |
final ancestor = | |
context.ancestorWidgetOfExactType(_InheritedCount) | |
as _InheritedCount; | |
return RaisedButton( | |
onPressed: () => ancestor.state.incrementCount(), | |
child: Text("Increment"), | |
); | |
}), | |
], | |
), | |
), | |
), | |
); | |
} | |
} | |
class CounterWidget extends StatefulWidget { | |
CounterWidget({Key key, @required this.child}) : super(key: key); | |
final Widget child; | |
@override | |
_CounterState createState() => _CounterState(); | |
} | |
class _CounterState extends State<CounterWidget> { | |
int count; | |
void incrementCount() { | |
setState(() { | |
++count; | |
}); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
count = 0; | |
} | |
@override | |
Widget build(BuildContext context) { | |
return _InheritedCount( | |
state: this, | |
child: widget.child, | |
); | |
} | |
} | |
class _InheritedCount extends InheritedWidget { | |
_InheritedCount({Key key, @required this.state, @required Widget child}) | |
: super(key: key, child: child); | |
final _CounterState state; | |
@override | |
bool updateShouldNotify(_InheritedCount old) => true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment