Skip to content

Instantly share code, notes, and snippets.

@jscarl
Created May 31, 2019 14:50
Show Gist options
  • Save jscarl/8e0456b9272d374605f3758995e8aab2 to your computer and use it in GitHub Desktop.
Save jscarl/8e0456b9272d374605f3758995e8aab2 to your computer and use it in GitHub Desktop.
Simple counter to implement provider approach for flutter.
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 Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home:
ChangeNotifierProvider<MyCounter>(
builder: (_) => MyCounter(),
child: MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final counterModel = Provider.of<MyCounter>(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${counterModel.getCounter()}',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counterModel.incrementCounter(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class MyCounter with ChangeNotifier {
int _counter = 0;
getCounter() => _counter;
setCounter(int counter) => _counter = counter;
void incrementCounter() {
_counter++;
notifyListeners();
}
void decrementCounter() {
_counter--;
notifyListeners();
}
}
@CagriKIRT
Copy link

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment