底部tab的灵活可控
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'dart:convert';
|
||||
import '../../domain/tab_config.dart';
|
||||
|
||||
abstract class TabConfigState {}
|
||||
|
||||
class TabConfigInitial extends TabConfigState {}
|
||||
|
||||
class TabConfigLoaded extends TabConfigState {
|
||||
final TabConfig config;
|
||||
|
||||
TabConfigLoaded(this.config);
|
||||
}
|
||||
|
||||
class TabConfigCubit extends Cubit<TabConfigState> {
|
||||
final SharedPreferences _prefs;
|
||||
static const String _configKey = 'tab_config';
|
||||
|
||||
TabConfigCubit(this._prefs) : super(TabConfigInitial()) {
|
||||
_loadConfig();
|
||||
}
|
||||
|
||||
void _loadConfig() {
|
||||
try {
|
||||
final configJson = _prefs.getString(_configKey);
|
||||
if (configJson != null) {
|
||||
final List<dynamic> decoded = jsonDecode(configJson);
|
||||
final items = decoded.map((e) {
|
||||
final map = Map<String, dynamic>.from(e);
|
||||
return TabConfigItem(
|
||||
id: map['id'] as String,
|
||||
name: map['name'] as String,
|
||||
nameEn: map['nameEn'] as String,
|
||||
icon: map['icon'] as String,
|
||||
isEnabled: map['isEnabled'] as bool,
|
||||
order: map['order'] as int,
|
||||
);
|
||||
}).toList();
|
||||
emit(TabConfigLoaded(TabConfig(items: items)));
|
||||
} else {
|
||||
final defaultConfig = TabConfig.defaultConfig();
|
||||
_saveConfig(defaultConfig);
|
||||
emit(TabConfigLoaded(defaultConfig));
|
||||
}
|
||||
} catch (e) {
|
||||
final defaultConfig = TabConfig.defaultConfig();
|
||||
emit(TabConfigLoaded(defaultConfig));
|
||||
}
|
||||
}
|
||||
|
||||
void _saveConfig(TabConfig config) {
|
||||
try {
|
||||
final configList = config.items.map((item) => {
|
||||
'id': item.id,
|
||||
'name': item.name,
|
||||
'nameEn': item.nameEn,
|
||||
'icon': item.icon,
|
||||
'isEnabled': item.isEnabled,
|
||||
'order': item.order,
|
||||
}).toList();
|
||||
_prefs.setString(_configKey, jsonEncode(configList));
|
||||
} catch (e) {
|
||||
print('保存 Tab 配置失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void toggleTab(String itemId) {
|
||||
if (state is TabConfigLoaded) {
|
||||
final currentState = state as TabConfigLoaded;
|
||||
final newConfig = currentState.config.toggleItem(itemId);
|
||||
|
||||
// 只有配置真正改变时才保存和 emit
|
||||
if (newConfig != currentState.config) {
|
||||
_saveConfig(newConfig);
|
||||
emit(TabConfigLoaded(newConfig));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TabConfig? getConfig() {
|
||||
if (state is TabConfigLoaded) {
|
||||
return (state as TabConfigLoaded).config;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user