Skip to content

Instantly share code, notes, and snippets.

@isacjunior
Last active January 27, 2020 15:51
Show Gist options
  • Save isacjunior/dd71abaa0175318abe80672e6df999ea to your computer and use it in GitHub Desktop.
Save isacjunior/dd71abaa0175318abe80672e6df999ea to your computer and use it in GitHub Desktop.
import 'package:flutter/widgets.dart';
void main() => runApp(TopWidget());
class CounterInherited extends InheritedWidget {
CounterInherited({
Key key,
@required this.state,
@required Widget child,
}) : super(key: key, child: child);
final _TopWidgetState state;
@override
bool updateShouldNotify(CounterInherited old) => true;
static CounterInherited of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<CounterInherited>();
}
class TopWidget extends StatefulWidget {
@override
_TopWidgetState createState() => _TopWidgetState();
}
class _TopWidgetState extends State<TopWidget> {
int counter = 0;
void increment() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterInherited(
state: this,
child: MiddleWidget(),
),
);
}
}
class MiddleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: BottomWidget(),
);
}
}
class BottomWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final int counter = CounterInherited.of(context).state.counter;
return Container(
child: Text(counter.toString()),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment