Skip to content

Instantly share code, notes, and snippets.

@felangel felangel/main.dart
Created Mar 30, 2019

Embed
What would you like to do?
setState behavior
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
@immutable
abstract class MyState {}
class Uninitialized extends MyState {}
class Loading extends MyState {}
class Loaded extends MyState {
final String data;
Loaded(this.data);
}
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
MyState state = Uninitialized();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Sample'),
),
body: _getBody(state),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: FloatingActionButton(
child: Icon(Icons.get_app),
onPressed: () {
setState(() {
state = Loading();
});
setState(() {
state = Loaded('some data');
});
},
),
),
],
),
),
);
}
Widget _getBody(MyState state) {
print(state);
if (state is Loading) {
return Center(child: CircularProgressIndicator());
}
if (state is Loaded) {
return Center(child: Text(state.data));
}
return Container();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.