Last active
January 2, 2023 02:22
-
-
Save mnvr/1f5d3d35986a1f925e088dd5cd0ae03d to your computer and use it in GitHub Desktop.
Minimal example demonstrating Flutter InheritedWidgets with mutable state
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/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MyWidget(), | |
); | |
} | |
} | |
class MyWidget extends StatefulWidget { | |
const MyWidget({super.key}); | |
@override | |
State<MyWidget> createState() => _MyWidgetState(); | |
} | |
class _MyWidgetState extends State<MyWidget> { | |
int c = 0; | |
void increment() { | |
setState(() { | |
c++; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Count(c: c, increment: increment, child: const NestedWidget()); | |
} | |
} | |
class Count extends InheritedWidget { | |
const Count({ | |
super.key, | |
required this.c, | |
required this.increment, | |
required super.child, | |
}); | |
final int c; | |
final void Function() increment; | |
static Count of(BuildContext context) => | |
context.dependOnInheritedWidgetOfExactType<Count>()!; | |
@override | |
bool updateShouldNotify(Count old) => c != old.c; | |
} | |
class NestedWidget extends StatelessWidget { | |
const NestedWidget({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
final c = Count.of(context).c; | |
return TextButton( | |
onPressed: Count.of(context).increment, | |
child: Text('$c', textScaleFactor: 3), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment