For doing async code there are so many options but the below one will be the simplest for getting work done.
Example:
String _deckString = "This is a Deck"; /// This variable should be used in a text widget, so until the network fetch the real data, till then default text can be shown
@override
void initState() {
// TODO: implement initState
super.initState();
client().then((value) { /// This code will run only when async operation done inside method client(), so value is its response which need to be shown
setState(() {
_deckString = value;
});
});
}
Full Code:
class _HomeScreenState extends State<HomeScreen> {
String _deckString = "This is a Deck";
@override
void initState() {
// TODO: implement initState
super.initState();
client().then((value) {
setState(() {
_deckString = value;
});
});
}
Future<String> client() async {
return await HttpRequest.getString('localhost:8000');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Example'),),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ElevatedButton(
onPressed: () {},
child: Text(_deckString),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () {},
tooltip: 'Add a Card',
),
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
tooltip: 'See All Cards',
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () {},
tooltip: 'Delete this Deck',
)
],
),
),
);
}
}
CLICK HERE to find out more related problems solutions.