Skip to content

Instantly share code, notes, and snippets.

@MCarlomagno
Created January 12, 2022 20:34
Show Gist options
  • Save MCarlomagno/10df375f1affa578631691d860bdaae1 to your computer and use it in GitHub Desktop.
Save MCarlomagno/10df375f1affa578631691d860bdaae1 to your computer and use it in GitHub Desktop.
class Info extends InheritedWidget {
// this udget uses the of(context)
//method to call the build method
// when updateShouldNotify function returns true
const Info({
Key key,
@required this.score,
@required Widget child,
}) : assert(score != null),
assert(child != null),
super(key: key, child: child);
final int score;
static Info of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Info>();
}
@override
bool updateShouldNotify(covariant Info oldWidget) {
return score != oldWidget.score;
}
}
// This is the widget that will call the build method
// each time the score variable updates its value
class CurrentScore extends StatelessWidget {
const CurrentScore();
@override
Widget build(BuildContext context) {
final Info info = Info.of(context);
return Container(
child: Text(info?.score.toString()),
);
}
}
// In this widget, we initialize the variable
// score and send it to the inherited widget to
// notify the child widget about the state update
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int _score = 0;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Info(
score: _score,
child: CurrentScore(),
),
ElevatedButton(
child: const Text('Change'),
onPressed: () {
setState(() {
_score++;
});
},
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment