Last active
January 27, 2020 15:51
-
-
Save isacjunior/dd71abaa0175318abe80672e6df999ea to your computer and use it in GitHub Desktop.
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/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