我想用它的 api 從 coin gecko 獲取資料。用于FutureProvider執行此操作。FutureProvider 只獲取一次資料。所以資料來了,UI 構建成功。但是,我想聽每個加密貨幣的所有更改,并重建小部件。我正在使用riverpod的 FutureProvider。如果我能夠向服務發送請求,每 15 秒獲取一次資料,然后重建 UI,這將解決我的問題。但我做不到。此外,我想了解最有效的方法是什么,我走的是正確的道路嗎?任何幫助表示贊賞。:)
final marketProvider = FutureProvider<List<Coin>>(
(ref) async => await DataService().fetch_coin_data(),
);
class CoinListPage extends ConsumerWidget {
const CoinListPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
AsyncValue<List<Coin>> coinList = ref.watch(marketProvider);
return Scaffold(
appBar: AppBar(
title: const Text("T I T L E"),
),
body: Center(
child: coinList.when(
data: (data) => CoinList(coinList: data),
error: (e, stack) => Text('Error: $e'),
loading: () => const CircularProgressIndicator(),
),
),
);
}
}
Future<List<Coin>> fetch_coin_data() async {
List<Coin> _coinList = <Coin>[];
final resp = await http.get(Uri.parse(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h"));
if (resp.statusCode == 200) {
// If the call to the server was successful, parse the JSON
List<dynamic> decoded = json.decode(resp.body);
for (dynamic coin in decoded) {
_coinList.add(Coin.fromJson(coin));
}
return _coinList;
} else {
// If that call was not successful, throw an error.
throw Exception('Request Error!');
}
}
為此,我不知道應該使用哪個提供商。任何幫助表示贊賞!
uj5u.com熱心網友回復:
FutureProvider旨在解決簡單的用例。對于更高級的場景,請考慮使用StateNotifierProvider.
FutureProvider回傳一個AsyncValue,因此我們可以創建一個StateNotifierProvider狀態型別AsyncValue,它將每 15 秒更新一次獲取資料和更新狀態。
final marketProvider = StateNotifierProvider<MarketNotifier, AsyncValue>((ref) {
return MarketNotifier();
});
class MarketNotifier extends StateNotifier<AsyncValue> {
MarketNotifier() : super(const AsyncValue.loading()) {
fetchLoopWithDelay(const Duration(seconds: 15));
}
Future<void> fetchLoopWithDelay(Duration delay) async {
while (true) {
try {
final data = await DataService().fetch_coin_data();
state = AsyncValue.data(data);
} catch (e) {
state = AsyncValue.error(e, StackTrace.current);
}
await Future.delayed(delay);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537201.html
