'How to use setState in FutureBuilder?
I have a function that accepts data via API:
//fetch data from API
Future<List<CurrencyModel>?> _fetchCurrency() async {
currencyList = [];
final response = await http.get(
Uri.parse(
'https:...'),
);
if (response.statusCode == 200) {
List<dynamic> values = [];
values = json.decode(response.body);
if (values.isNotEmpty) {
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
Map<String, dynamic> map = values[i];
currencyList.add(
CurrencyModel.fromJson(map),
);
}
}
setState(() {
currencyList;
});
}
return currencyList;
} else {
throw Exception('Failed to load currencies');
}
}
I moved the logic of working with the API into a separate file, created a regular class with the Future function. How now to be with setState which was in Future? Because setState cannot be added to a regular class. How to add it to FutureBuilder? My code:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Currencies'),
centerTitle: true,
),
body: FutureBuilder(
future: client.fetchCurrency(),
builder: (BuildContext context,
AsyncSnapshot<List<CurrencyModel>?> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: currencyList.length,
itemBuilder: (context, index) => CurrencyCard(
currencyList[index],
),
);
} else if (snapshot.hasError) {
return Text(
'${snapshot.error}',
);
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: startTimer,
child: const Icon(Icons.update_sharp),
),
);
}
Solution 1:[1]
It is easy:
1 Declare a function to process your list
List<CurrencyModel>? _processOnEnd(List<CurrencyModel>? value){
//write what you need inside this function
return value;
}
2 Call it inside then method of your Future
FutureBuilder(
future: client.fetchCurrency().then(_processOnEnd),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kerim |
