追加webdav重新登录的button,还在测试边界情况
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
// lib/base/base_state.dart
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 所有页面的基类,提供安全的 setState 封装
|
||||
///
|
||||
/// 使用方式:
|
||||
/// 1. 将页面的 State 类从 `State<YourPage>` 改为 `BaseState<YourPage>`
|
||||
/// 2. 将所有 `setState(() { ... })` 替换为 `safeSetState(() { ... })`
|
||||
abstract class BaseState<T extends StatefulWidget> extends State<T> {
|
||||
/// 安全的 setState,自动检查 mounted
|
||||
///
|
||||
/// 用法:
|
||||
/// ```dart
|
||||
/// safeSetState(() {
|
||||
/// _isLoading = false;
|
||||
/// });
|
||||
/// ```
|
||||
void safeSetState(VoidCallback fn) {
|
||||
if (mounted) {
|
||||
setState(fn);
|
||||
}
|
||||
}
|
||||
|
||||
/// 安全执行异步操作,完成后自动刷新
|
||||
///
|
||||
/// 用法:
|
||||
/// ```dart
|
||||
/// await safeAsync(
|
||||
/// () => _loadData(), // 异步操作
|
||||
/// () => _isLoading = false, // 完成后执行的 setState
|
||||
/// );
|
||||
/// ```
|
||||
Future<void> safeAsync(
|
||||
Future<void> Function() action,
|
||||
VoidCallback onComplete, {
|
||||
VoidCallback? onError,
|
||||
}) async {
|
||||
try {
|
||||
await action();
|
||||
if (mounted) {
|
||||
setState(onComplete);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('⚠️ [BaseState] safeAsync error: $e');
|
||||
if (mounted) {
|
||||
setState(onComplete);
|
||||
}
|
||||
onError?.call();
|
||||
}
|
||||
}
|
||||
|
||||
/// 显示 SnackBar(封装,确保 mounted)
|
||||
void showSafeSnackBar(String message, {Color? backgroundColor}) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(message),
|
||||
backgroundColor: backgroundColor ?? Colors.grey,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user