feat: 修复了插件需要外部Provider的问题;加上了一个简易的车控状态返回
This commit is contained in:
78
lib/bloc/easy_bloc.dart
Normal file
78
lib/bloc/easy_bloc.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
// 简易的Bloc, 简易的状态管理
|
||||
|
||||
abstract class EasyBlocBase<State> {
|
||||
|
||||
EasyBlocBase(this.state): assert(state != null);
|
||||
|
||||
final StreamController<State> _stateController = StreamController<State>.broadcast();
|
||||
|
||||
Stream<State> get stream => _stateController.stream;
|
||||
State state;
|
||||
|
||||
bool _emitted = false;
|
||||
|
||||
// 添加监听器方法
|
||||
StreamSubscription<State> listen(
|
||||
void Function(State state) onData, {
|
||||
Function? onError,
|
||||
void Function()? onDone,
|
||||
bool? cancelOnError,
|
||||
}) {
|
||||
return stream.listen(
|
||||
onData,
|
||||
onError: onError,
|
||||
onDone: onDone,
|
||||
cancelOnError: cancelOnError,
|
||||
);
|
||||
}
|
||||
|
||||
// 新状态
|
||||
void emit(State newState) {
|
||||
if (_stateController.isClosed) return;
|
||||
if (newState == state && _emitted) return;
|
||||
this.state = newState;
|
||||
_stateController.add(state);
|
||||
_emitted = true;
|
||||
}
|
||||
|
||||
@mustCallSuper
|
||||
Future<void> close() async {
|
||||
await _stateController.close();
|
||||
}
|
||||
}
|
||||
|
||||
class EasyBloc<Event, State> extends EasyBlocBase<State> {
|
||||
EasyBloc(State initialState) : super(initialState) {
|
||||
_eventController.stream.listen(_mapEventToState);
|
||||
}
|
||||
|
||||
final StreamController<Event> _eventController = StreamController<Event>();
|
||||
|
||||
// 子类需要实现这个方法来处理事件
|
||||
@mustBeOverridden
|
||||
void _mapEventToState(Event event) {
|
||||
// 默认不做任何处理,如果不实现会抛出异常
|
||||
throw UnimplementedError('_mapEventToState must be implemented by subclasses');
|
||||
}
|
||||
|
||||
// 添加事件
|
||||
void add(Event event) {
|
||||
if (_eventController.isClosed) return;
|
||||
_eventController.add(event);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
await _eventController.close();
|
||||
await super.close();
|
||||
}
|
||||
}
|
||||
|
||||
class EasyCubit<State> extends EasyBlocBase<State> {
|
||||
EasyCubit(State initialState) : super(initialState);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user