Skip to content

Instantly share code, notes, and snippets.

@Ticore
Created July 14, 2018 15:21
Show Gist options
  • Select an option

  • Save Ticore/9e7ae0f6d7b33bacbc0eee33a363afe7 to your computer and use it in GitHub Desktop.

Select an option

Save Ticore/9e7ae0f6d7b33bacbc0eee33a363afe7 to your computer and use it in GitHub Desktop.
try to remove ui implementation from state, and put in StatefulWidget
///
/// [pure state flutter app]
/// try to remove ui implementation from state, and put in StatefulWidget
///
import 'package:flutter/material.dart';
void main() => runApp(new MainApp());
//
// MainApp
//
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
title: "Flutter App",
theme: ThemeData(primaryColor: Colors.deepPurple),
home: HomePage(title: 'Home Page'),
);
}
//
// StatefulWidget with ui impementation
//
class HomePage extends StatefulWidget {
// static state map
static final _stateMap = <HomePage, _HomeState>{};
get state => _stateMap[this];
set state(v) => _stateMap[this] = v;
stateDispose() => _stateMap.remove(this);
@override
State<StatefulWidget> createState() => state = _HomeState();
final String title;
HomePage({Key key, this.title}) : super(key: key);
// State build child widget
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RaisedButton(
onPressed: state._decrementCounter,
child: Icon(Icons.remove),
),
Text(
'${state._counter}',
style: Theme.of(context).textTheme.display1,
),
RaisedButton(
onPressed: state._incrementCounter,
child: Icon(Icons.add),
),
],
),
),
);
}
//
// State without ui implementation
//
class _HomeState extends State<HomePage> {
int _counter = 0;
_incrementCounter() {
setState(() => _counter++);
}
_decrementCounter() {
setState(() => _counter--);
}
@override
dispose() {
super.dispose();
widget.stateDispose();
}
@override
didUpdateWidget(oldWidget) {
super.didUpdateWidget(oldWidget);
widget.state = this;
}
// call widget to build child widget
Widget build(BuildContext context) {
return widget.build(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment