Skip to content

Instantly share code, notes, and snippets.

@extJo
Created August 3, 2019 07:21
Show Gist options
  • Save extJo/31a5e1c3d1252d4b85f105c3fc6fca97 to your computer and use it in GitHub Desktop.
Save extJo/31a5e1c3d1252d4b85f105c3fc6fca97 to your computer and use it in GitHub Desktop.
Flutter count App with InheritedWidget
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter State Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Counter(),
);
}
}
class _InheritedCounter extends InheritedWidget {
_InheritedCounter({Key key, @required this.counterState, @required this.child})
: assert(counterState != null),
super(key: key, child: child);
final _CounterState counterState;
final Widget child;
@override
bool updateShouldNotify(_InheritedCounter old) => counterState.count != old.counterState.count;
}
class Counter extends StatefulWidget {
Counter({Key key}) : super(key: key);
@override
_CounterState createState() => _CounterState();
static _CounterState of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(_InheritedCounter)
as _InheritedCounter).counterState;
}
}
class _CounterState extends State<Counter> {
int count = 0;
void increment() {
setState(() {
count++;
});
}
void decrement() {
setState(() {
count--;
});
}
@override
Widget build(BuildContext context) {
return _InheritedCounter(
child: CounterUI(),
counterState: this,
);
}
}
class CounterUI extends StatelessWidget {
Widget _fab(Icon icon, Function action) {
return FloatingActionButton(
child: icon,
onPressed: action,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Count Sample State Management'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${Counter.of(context).count}',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
_fab(Icon(Icons.exposure_plus_1), Counter.of(context).increment),
_fab(Icon(Icons.exposure_neg_1), Counter.of(context).decrement),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment