Skip to content

Instantly share code, notes, and snippets.

@brianegan
Created February 9, 2019 12:22
Show Gist options
  • Save brianegan/42b7e2ef856ca8f82f84c62cba46b2d4 to your computer and use it in GitHub Desktop.
Save brianegan/42b7e2ef856ca8f82f84c62cba46b2d4 to your computer and use it in GitHub Desktop.
SetState example not rerendering after each statement
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
enum MyState { initial, loading, success, error }
class _MyHomePageState extends State<MyHomePage> {
MyState _currentState = MyState.initial;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(child: _buildBody()),
floatingActionButton: FloatingActionButton(
onPressed: _updateState,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _updateState() {
setState(() {
_currentState = MyState.initial;
});
setState(() {
_currentState = MyState.loading;
});
setState(() {
_currentState = MyState.success;
});
}
Widget _buildBody() {
switch (_currentState) {
case MyState.loading:
return CircularProgressIndicator();
case MyState.error:
return Text("error");
case MyState.success:
return Text("success");
case MyState.initial:
default:
return Text("Initial State");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment