Created
November 30, 2018 00:46
-
-
Save filiph/2b97db29acaa345612f6c255a92d2d2d to your computer and use it in GitHub Desktop.
ScopedModel counter app
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 'dart:async'; | |
import 'package:flutter/material.dart'; | |
import 'package:scoped_model/scoped_model.dart'; | |
void main() { | |
// The app state. | |
final myModel = CounterModel(42); | |
// A timer, to simulate updates coming from outside the app. | |
Timer.periodic(const Duration(seconds: 2), (_) => myModel.increment()); | |
// Provide the model to the top-most widget. | |
runApp(MyApp(myModel)); | |
} | |
class CounterModel extends Model { | |
// The state variable. | |
int counter; | |
// The constructor, which takes the initial state. | |
CounterModel(this.counter); | |
// The method to mutate the state. | |
void increment() { | |
counter += 1; | |
notifyListeners(); | |
} | |
} | |
class MyApp extends StatelessWidget { | |
final CounterModel counterModel; | |
MyApp(this.counterModel, {Key key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return ScopedModel( | |
model: counterModel, | |
child: MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(title: 'Flutter Demo Home Page'), | |
), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
MyHomePage({Key key, this.title}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
final model = ScopedModel.of<CounterModel>(context, rebuildOnChange: true); | |
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( | |
'${model.counter}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () => model.increment(), | |
tooltip: 'Increment', | |
child: Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment