Skip to content

Instantly share code, notes, and snippets.

@jediyeti
Created February 4, 2020 10:37
Show Gist options
  • Save jediyeti/ef41b68acfed34d4516e5fdc0cccad77 to your computer and use it in GitHub Desktop.
Save jediyeti/ef41b68acfed34d4516e5fdc0cccad77 to your computer and use it in GitHub Desktop.
Inherited Widget Example
import 'package:flutter/material.dart';
void main() {
runApp(
InitialCounterValueProvider(
value: 5,
child: MaterialApp(
title: 'Flutter Tutorial',
home: TutorialHome(),
),
),
);
}
class InitialCounterValueProvider extends InheritedWidget {
const InitialCounterValueProvider({
Key key,
@required this.value,
@required Widget child,
}) : assert(value != null),
assert(child != null),
super(child: child);
final int value;
static InitialCounterValueProvider of(BuildContext context) {
return context
.dependOnInheritedWidgetOfExactType<InitialCounterValueProvider>();
}
@override
bool updateShouldNotify(InitialCounterValueProvider old) =>
value != old.value;
}
class TutorialHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Counter()),
);
}
}
class Counter extends StatefulWidget {
// Creates State
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
@override
initState() {
super.initState();
}
@override
didChangeDependencies() {
super.didChangeDependencies();
final counterValueProvider = InitialCounterValueProvider.of(context);
_counter = counterValueProvider.value;
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: _increment,
child: Text('Increment'),
),
SizedBox(width: 16.0),
Text(
'Count: $_counter',
style: TextStyle(fontSize: 16.0),
),
],
);
}
void _increment() {
setState(() {
_counter++;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment