import 'package:flutter/material.dart'; import '../data/models/coin.dart'; import '../data/services/market_service.dart'; /// 行情狀態管理 class MarketProvider extends ChangeNotifier { final MarketService _marketService; List _allCoins = []; List _platformCoins = []; List _nonPlatformCoins = []; bool _isLoading = false; String? _error; bool _coinsLoaded = false; MarketProvider(this._marketService); // Getters List get allCoins => _allCoins; bool get isLoading => _isLoading; String? get error => _error; List get platformCoins => _platformCoins; List get nonPlatformCoins => _nonPlatformCoins; /// 加載幣種列表 Future loadCoins({bool force = false}) async { if (_coinsLoaded && !force && _allCoins.isNotEmpty) { return; } final isFirstLoad = !_coinsLoaded || _allCoins.isEmpty; if (isFirstLoad) { _isLoading = true; _error = null; notifyListeners(); } try { final response = await _marketService.getCoinList(); if (response.success) { _allCoins = response.data ?? []; _platformCoins = _allCoins.where((c) => c.isPlatform == 1 && c.status == 1).toList(); _nonPlatformCoins = _allCoins.where((c) => c.isPlatform != 1 && c.code != 'USDT').toList(); _coinsLoaded = true; _error = null; } else { // 非首次加载时保留旧数据,仅记录错误 if (!isFirstLoad && _allCoins.isNotEmpty) { _error = null; } else { _error = response.message; } } } catch (e) { // 非首次加载且有缓存数据时,不覆盖为错误状态 if (!isFirstLoad && _allCoins.isNotEmpty) { _error = null; } else { _error = '加載失敗: $e'; } } _isLoading = false; notifyListeners(); } /// 根據代碼獲取幣種 Coin? getCoinByCode(String code) { try { return _allCoins.firstWhere((c) => c.code == code); } catch (_) { return null; } } /// 刷新 Future refresh() async { await loadCoins(force: true); } /// 重置加載狀態(用於退出登錄時) void resetLoadState() { _coinsLoaded = false; _allCoins = []; _error = null; notifyListeners(); } }