Last active
September 18, 2020 10:10
-
-
Save FantasyCheese/1c927d7724e4e8aa0c8895982b7f951d to your computer and use it in GitHub Desktop.
Simplest InheritedWidget with State Update Example
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 'dart:async'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(CounterUpdater( | |
child: MyApp(), | |
)); | |
} | |
class CounterUpdater extends StatefulWidget { | |
CounterUpdater({Key key, this.child}) : super(key: key); | |
final Widget child; | |
@override | |
_CounterUpdaterState createState() => _CounterUpdaterState(); | |
} | |
class _CounterUpdaterState extends State<CounterUpdater> { | |
int count = 42; | |
@override | |
void initState() { | |
super.initState(); | |
Timer.periodic(Duration(seconds: 1), (timer) { | |
setState(() { | |
count++; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return CountProvider( | |
count: count, | |
child: widget.child, | |
); | |
} | |
} | |
class CountProvider extends InheritedWidget { | |
final Widget child; | |
final int count; | |
CountProvider({Key key, this.child, this.count}) : super(key: key, child: child); | |
static CountProvider of(BuildContext context) => context.dependOnInheritedWidgetOfExactType(aspect: CountProvider); | |
@override | |
bool updateShouldNotify(CountProvider oldWidget) => true; | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Center( | |
child: RichText( | |
text: TextSpan(text: CountProvider.of(context).count.toString()), | |
textDirection: TextDirection.ltr, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment