Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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;
bool operator ==(Object other) {
if (identical(this, other))
return true;
if (other.runtimeType != runtimeType)
return false;
final Model otherModel = other;
return otherModel.value == value;
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;
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
updateModel(Model(value: currentModel.value + 1));
child: Text('Hello World ${currentModel.value}'),
class App extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(child: ViewController()),
void main() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment