Skip to content

Instantly share code, notes, and snippets.

@szotp
Created February 17, 2019 13:55
Show Gist options
  • Save szotp/af3c8944f113c8656ed28664ebdcd506 to your computer and use it in GitHub Desktop.
Save szotp/af3c8944f113c8656ed28664ebdcd506 to your computer and use it in GitHub Desktop.
simple state management
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: BrowserPage(),
);
}
}
class BrowserController extends ChangeNotifier {
int _likeCounter = 0;
int get likeCounter => _likeCounter;
void incrementCounter() {
_likeCounter++;
notifyListeners();
}
}
class BrowserPage extends StatefulWidget {
@override
_BrowserPageState createState() => _BrowserPageState();
}
class _BrowserPageState extends State<BrowserPage> {
BrowserController _controller;
@override
void initState() {
_controller = BrowserController();
super.initState();
}
@override
void setState(fn) {
assert(false, 'calling setState should not be needed');
super.setState(fn);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
// Notice that we are not calling setState anywhere
// AnimatedBuilder will update itself when BrowserController notifies listeners
AnimatedBuilder(
animation: _controller,
builder: (context, _) {
return Text('${_controller.likeCounter}');
},
),
FlatButton(
child: Text('Increment'),
onPressed: _controller.incrementCounter,
)
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment