Skip to content

Instantly share code, notes, and snippets.

@jtlapp
Last active February 12, 2021 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jtlapp/f81438723e46d1c6258fce68d3d6766c to your computer and use it in GitHub Desktop.
Save jtlapp/f81438723e46d1c6258fce68d3d6766c to your computer and use it in GitHub Desktop.
Counter app implemented with InheritedWidget
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