Created
August 3, 2019 08:56
-
-
Save extJo/e4f48ce7069edeaba4d27457afd7e80e to your computer and use it in GitHub Desktop.
Flutter count App with Provider
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'; | |
import 'package:provider/provider.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 CounterModel with ChangeNotifier { | |
int _count = 0; | |
int get count => _count; | |
void increment() { | |
_count++; | |
notifyListeners(); | |
} | |
void decrement() { | |
_count--; | |
notifyListeners(); | |
} | |
} | |
class Counter extends StatelessWidget { | |
Counter({Key key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return ChangeNotifierProvider( | |
builder: (context) => CounterModel(), | |
child: CounterUI() | |
); | |
} | |
} | |
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:', | |
), | |
Consumer<CounterModel>( | |
builder: (context, counter, child) => Text( | |
'${counter.count}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: Column( | |
mainAxisAlignment: MainAxisAlignment.end, | |
children: <Widget>[ | |
_fab(Icon(Icons.exposure_plus_1), | |
Provider.of<CounterModel>(context).increment), | |
_fab(Icon(Icons.exposure_neg_1), | |
Provider.of<CounterModel>(context).decrement), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment