Skip to content

Instantly share code, notes, and snippets.

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