我正在使用三个Flutter软件包来实现一项功能,用户可以通过该软件包进行刷新,使用BLoC逻辑检索地理坐标并将其传递回Flutter。
问题是,当我在拉动刷新中调度呼叫时,我无法获得BLoC来产生返回结果。
geolocation_bloc.dart
class GeolocationBloc extends Bloc<GeolocationEvent, GeolocationState> {
@override
GeolocationState get initialState => GeolocationUninitialized();
@override
Stream<GeolocationState> mapEventToState(GeolocationEvent event) async* {
if (event is RequestLocation) {
yield* _mapGeolocationRequestLocation();
}
}
Stream<GeolocationState> _mapGeolocationRequestLocation() async* {
Position position;
position = await Geolocator().getCurrentPosition();
print("RETRIEVED LOCATION"); // I CAN REACH HERE EVERYTIME.
if (position == null) {
yield LocationLoaded(0, 0);
} else {
yield LocationLoaded(position.latitude, position.longitude);
}
}
检索地理坐标。如果传感器已关闭/损坏,请改为返回(0,0)。
feed_page.dart
@override
void initState() {
super.initState();
_geolocationBloc.dispatch(RequestLocation());
}
void _onRefresh() {
_geolocationBloc.dispatch(RequestLocation());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Username')),
body: BlocProviderTree(
blocProviders: [
BlocProvider<PostBloc>(bloc: _postBloc),
BlocProvider<GeolocationBloc>(bloc: _geolocationBloc),
],
child: BlocListenerTree(
blocListeners: [
BlocListener<GeolocationEvent, GeolocationState>(
bloc: _geolocationBloc,
listener: (BuildContext context, GeolocationState state) {
if (state is LocationLoaded) {
print('LOADED'); // THIS NEVER GETS PRINTED WHEN PULLED TO REFRESH.
lat = state.latitude;
long = state.longitude;
}
..
驱动程序类在RequestLocation()
中分配一次请求initState()
,每次调用onRefresh()
时都会分配请求。
但是,在第一次调用RequestLocation()
时,它已成功通过,即在initState()
中,随后的调用使用了 pull-to-refresh onRefresh()
方法似乎不会产生LocationLoaded()
状态。
日志
Restarted application in 2,849ms.
I/flutter ( 6125): AppStarted
I/flutter ( 6125): RequestLocation
I/flutter ( 6125): RETRIEVED LOCATION
I/flutter ( 6125): Transition { currentState: GeolocationUninitialized, event: RequestLocation, nextState: LocationLoaded { latitude: 37.4219983, longitude: -122.084} }
I/flutter ( 6125): LOCATION LOADED
I/flutter ( 6125): RequestLocation
I/flutter ( 6125): RETRIEVED LOCATION
根据日志,第一个调用会同时打印已获取位置和已加载位置,但是在第二个已获取位置之后,则不会再显示其他任何内容。
如何解决此问题,以便刷新刷新将成功调用BLoC逻辑,该逻辑又将返回具有适当坐标的LocationLoaded()
对象。
答案 0 :(得分:0)
我设法通过删除Equatable
继承来解决此问题,该继承与等式比较混淆。
我设法通过从我的Equatable
和State
BLoC类中删除Event
继承来解决此问题。 Equatable
实现相等性检查导致BlocListener没有短路到相应的if / else块:
i.e. if (state is LocationLoaded)..
在Equatable
中,相等性检查可能会更加严格,或者由于我在状态(纬度/经度)下传递两个坐标,因此会导致相等性检查失败。
州级:
@immutable
abstract class GeolocationState extends Equatable { // Remove inheritance.
}
class LocationLoaded extends GeolocationState {
}
class GeolocationUninitialized extends GeolocationState {
}