Skip to content

Instantly share code, notes, and snippets.

@HansMuller
Created December 14, 2018 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HansMuller/4c4da1e1e801edf6ddbb506989d546a4 to your computer and use it in GitHub Desktop.
Save HansMuller/4c4da1e1e801edf6ddbb506989d546a4 to your computer and use it in GitHub Desktop.
/*
An example of managing a tiny Flutter app's state with a StatefulWidget.
The ViewController widget's persistent state is defined by an instance
of Model and its build method creates a widget that provides an
interactive visualization of that model.
To keep things simple, the model is immutable. The ViewController updates
its model by replacing it.
*/
import 'package:flutter/material.dart';
class Model {
const Model({ this.value = 0 });
final int value;
@override
bool operator ==(Object other) {
if (identical(this, other))
return true;
if (other.runtimeType != runtimeType)
return false;
final Model otherModel = other;
return otherModel.value == value;
}
@override
int get hashCode => value.hashCode;
}
class ViewController extends StatefulWidget {
_ViewControllerState createState() => _ViewControllerState();
}
class _ViewControllerState extends State<ViewController> {
Model currentModel = Model();
void updateModel(Model newModel) {
if (newModel != currentModel) {
setState(() {
currentModel = newModel;
});
}
}
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
updateModel(Model(value: currentModel.value + 1));
},
child: Text('Hello World ${currentModel.value}'),
);
}
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(child: ViewController()),
),
);
}
}
void main() {
runApp(App());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment