import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:grpc/grpc.dart'; import 'ui.dart'; import '../common/utils/log.dart' as log_utils; export '../common/utils/base_utils.dart'; export 'ui.dart'; class BaseUIModel extends ChangeNotifier { String uiErrorMsg = ""; bool _isDisposed = false; bool get mounted => !_isDisposed; BuildContext? context; BaseUIModel() { initModel(); } @mustCallSuper void initModel() { dPrint("[base] <$runtimeType> Model Init"); loadData(); } @mustCallSuper @override void dispose() { _isDisposed = true; _childUIModels?.forEach((k, value) { (value as BaseUIModel).dispose(); _childUIModels?[k] = null; }); dPrint("[base] <$runtimeType> Model Disposed"); super.dispose(); } Future loadData() async {} Future reloadData() async { return loadData(); } Future onErrorReloadData() async { return loadData(); } @override void notifyListeners() { if (!mounted) return; super.notifyListeners(); } Future handleError(Future Function() requestFunc, {bool showFullScreenError = false, String? errorOverride, bool noAlert = false}) async { uiErrorMsg = ""; if (mounted) notifyListeners(); try { return await requestFunc(); } catch (e) { dPrint("$runtimeType.handleError Error:$e"); String errorMsg = "Unknown Error"; if (e is GrpcError) { errorMsg = "远程服务器消息: ${e.message ?? "Unknown Error"}"; } else { errorMsg = e.toString(); } if (showFullScreenError) { uiErrorMsg = errorMsg; notifyListeners(); return null; } if (!noAlert) { showToast(context!, errorOverride ?? errorMsg, constraints: BoxConstraints( maxWidth: MediaQuery.of(context!).size.width * .6, ), title: "出现错误!"); } } return null; } Map? _childUIModels; Map? _childUIProviders; BaseUIModel? onCreateChildUIModel(modelKey) => null; dynamic _getChildUIModel(modelKey) { _childUIModels ??= {}; final cachedModel = _childUIModels![modelKey]; if (cachedModel != null) { return (cachedModel); } final newModel = onCreateChildUIModel(modelKey); _childUIModels![modelKey] = newModel!; return newModel; } ChangeNotifierProvider getChildUIModelProviders( modelKey) { _childUIProviders ??= {}; if (_childUIProviders![modelKey] == null) { _childUIProviders![modelKey] = ChangeNotifierProvider((ref) { final c = (_getChildUIModel(modelKey) as M); return c..context = context; }); } return _childUIProviders![modelKey]!; } T? getCreatedChildUIModel(String modelKey, {bool create = false}) { if (create && _childUIModels?[modelKey] == null) { _getChildUIModel(modelKey); } return _childUIModels?[modelKey] as T?; } Future reloadAllChildModels() async { if (_childUIModels == null) return; final futureList = []; for (var value in _childUIModels!.entries) { futureList.add(value.value.reloadData()); } await Future.wait(futureList); notifyListeners(); } dismissKeyBoard() { FocusManager.instance.primaryFocus?.unfocus(); } dPrint(src) { log_utils.dPrint("<$runtimeType> $src"); } }