Files
monisuo/flutter_monisuo/lib/providers/market_provider.dart
2026-04-07 01:05:05 +08:00

79 lines
1.8 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:flutter/material.dart';
import '../data/models/coin.dart';
import '../data/services/market_service.dart';
/// 行情狀態管理
class MarketProvider extends ChangeNotifier {
final MarketService _marketService;
List<Coin> _allCoins = [];
bool _isLoading = false;
String? _error;
bool _coinsLoaded = false;
MarketProvider(this._marketService);
// Getters
List<Coin> get allCoins => _allCoins;
bool get isLoading => _isLoading;
String? get error => _error;
/// BTC 和 ETH上半區展示
List<Coin> get featuredCoins =>
_allCoins.where((c) => c.code == 'BTC' || c.code == 'ETH').toList();
/// 排除 BTC、ETH、USDT 的代幣列表(下半區展示)
List<Coin> get otherCoins => _allCoins
.where((c) => !{'BTC', 'ETH', 'USDT'}.contains(c.code))
.toList();
/// 加載幣種列表
Future<void> loadCoins({bool force = false}) async {
if (_coinsLoaded && !force && _allCoins.isNotEmpty) {
return;
}
_isLoading = true;
_error = null;
notifyListeners();
try {
final response = await _marketService.getCoinList();
if (response.success) {
_allCoins = response.data ?? [];
_coinsLoaded = true;
} else {
_error = response.message;
}
} catch (e) {
_error = '加載失敗: $e';
}
_isLoading = false;
notifyListeners();
}
/// 根據代碼獲取幣種
Coin? getCoinByCode(String code) {
try {
return _allCoins.firstWhere((c) => c.code == code);
} catch (_) {
return null;
}
}
/// 刷新
Future<void> refresh() async {
await loadCoins(force: true);
}
/// 重置加載狀態(用於退出登錄時)
void resetLoadState() {
_coinsLoaded = false;
_allCoins = [];
_error = null;
notifyListeners();
}
}