问题描述
最近我正在学习Flutter_bloc
,并引用了项目flutter_weather。
让我感到困惑的是,如果一个Bloc
类有很多事件,并且大多数Event
都将有State
返回的值,并且有很多{{1} }中的项目,如果我想让BlocBuilder
只响应某个BlocBuilder
怎么办?
我能想到的方法是将这个Event
分为多个Bloc
,或者将每个值都视为Bloc
的属性,Bloc
使用BlocBuilder
方法来确定是否重建。
但这两种方法都不适合我。有什么好的方法吗?最好在github上有项目以供参考。
例如: 这是事件:
buildwhen
这是状态:
abstract class WeatherEvent extends Equatable {
const WeatherEvent();
}
class WeatherRequested extends WeatherEvent {
final String city;
const WeatherRequested({@required this.city}) : assert(city != null);
@override
List<Object> get props => [city];
}
class WeatherRefreshRequested extends WeatherEvent {
final String city;
const WeatherRefreshRequested({@required this.city}) : assert(city != null);
@override
List<Object> get props => [city];
}
这是集团:
abstract class WeatherState extends Equatable {
const WeatherState();
@override
List<Object> get props => [];
}
class WeatherInitial extends WeatherState {}
class WeatherLoadInProgress extends WeatherState {}
class WeatherLoadSuccess extends WeatherState {
final Weather weather;
const WeatherLoadSuccess({@required this.weather}) : assert(weather != null);
@override
List<Object> get props => [weather];
}
class WeatherLoadFailure extends WeatherState {}
这是BlocConsumer:
class WeatherBloc extends Bloc<WeatherEvent,WeatherState> {
final WeatherRepository weatherRepository;
WeatherBloc({@required this.weatherRepository})
: assert(weatherRepository != null),super(WeatherInitial());
@override
Stream<WeatherState> mapEventToState(WeatherEvent event) async* {
if (event is WeatherRequested) {
yield* _mapWeatherRequestedToState(event);
} else if (event is WeatherRefreshRequested) {
yield* _mapWeatherRefreshRequestedToState(event);
}
}
Stream<WeatherState> _mapWeatherRequestedToState(
WeatherRequested event,) async* {
yield WeatherLoadInProgress();
try {
final Weather weather = await weatherRepository.getWeather(event.city);
yield WeatherLoadSuccess(weather: weather);
} catch (_) {
yield WeatherLoadFailure();
}
}
Stream<WeatherState> _mapWeatherRefreshRequestedToState(
WeatherRefreshRequested event,) async* {
try {
final Weather weather = await weatherRepository.getWeather(event.city);
yield WeatherLoadSuccess(weather: weather);
} catch (_) {}
}
}
问题是我希望BlocBuilder1仅在事件类型为WeatherRequested时才能工作,而BlocBuilder2仅在事件类型为WeatherRefreshRequested时才能工作。我的想法之一是,每个事件都有自己的状态,然后在构建时判断状态的类型。
有什么好的方法吗?
解决方法
如果要构建窗口小部件以响应某些状态,则应使用 BlocConsumer ,并在 buildWhen 中告诉该bloc告诉它应该在什么状态下构建/重建小部件。
BlocConsumer<QuizBloc,QuizState>(
buildWhen: (previous,current) {
if (current is QuizPoints)
return true;
else
return false;
},listener: (context,state) {},builder: (context,state) {
if (state is QuizPoints)
return Container(
child: Center(
child: Countup(
begin: 0,end: state.points,duration: Duration(seconds: 2),separator: ',',),);
else
return Container();
},);