Last active
August 8, 2021 18:34
-
-
Save Emex4gman/97b8ac6d6b5690c02fd14e22ad1e1c5c to your computer and use it in GitHub Desktop.
ui state app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
enum AppState { LOADING, COMPLETED, ERROR, IDEL } | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHome(), | |
); | |
} | |
} | |
class MyHome extends StatefulWidget { | |
const MyHome({Key? key}) : super(key: key); | |
@override | |
_MyHomeState createState() => _MyHomeState(); | |
} | |
class _MyHomeState extends State<MyHome> { | |
AppState uiState = AppState.LOADING; | |
Future<void> _callApi() async { | |
try { | |
uiState = AppState.LOADING; | |
setState(() {}); | |
await Future.delayed(Duration(seconds: 5)); // the api call and you can set the data from the api call | |
uiState = AppState.COMPLETED; | |
setState(() {}); | |
// to test the error state you can trow an error | |
} catch (e) { | |
uiState = AppState.ERROR; | |
setState(() {}); | |
} | |
} | |
Future<void> _retry() async { | |
/// you can add your retry stuff | |
} | |
@override | |
void initState() { | |
super.initState(); | |
_callApi(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: SafeArea( | |
child: Builder( | |
builder: (ctx) { | |
switch (uiState) { | |
case AppState.LOADING: | |
return Center(child: CircularProgressIndicator()); | |
case AppState.COMPLETED: | |
return Column( | |
children: [ | |
Text("APP IS READY"), | |
], | |
); | |
case AppState.ERROR: | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text("APP HAS ERROR"), | |
TextButton( | |
onPressed: _retry, | |
child: Text("RETRY"), | |
), | |
], | |
); | |
default: | |
return Container(); | |
} | |
}, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment