我正在尝试学习和使用flutter bloc来创建一个项目,该项目可以侦听用户的位置,还可以从服务中获取一些坐标,并将此坐标显示在地图中作为标记。这是myApp方法:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: MultiBlocProvider(providers: [
BlocProvider<FoursquareBloc>(create: (context) => sl<FoursquareBloc>()), //bloc page to get corrdinate
BlocProvider<LocationBloc>(create: (context) => sl<LocationBloc>()), // bloc page to listen to change user location
], child: HomeFoursquareScreen()),
);
}
}
HomeFoursquareScreen
页面显示地图:
Widget build(BuildContext context) {
return BlocBuilder<LocationBloc, LocationState>(builder: (context, state) {
if (state is LocationLoadingState) {
return Center(child: CircularProgressIndicator());
} else if (state is LocationLoadedState) {
print("LocationLoadedState");
intMapCoordinate =
LatLng(state.location.latitude, state.location.longitude);
} else if (state is UserLocationListeningState) {
_controller.move(
LatLng(state.location.latitude, state.location.longitude), 15.0);
}
return FlutterMap(
mapController: _controller,
options: MapOptions(
center: intMapCoordinate,
zoom: 13.0,
),
layers: [
TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
],
);
});
}
我很困惑,因为我不知道如何使用FoursquareBloc
来获取坐标以在地图上显示为标记?
这是LocationBloc
class LocationBloc extends Bloc<LocationEvent, LocationState> {
var location = Location();
StreamSubscription<LocationData> _locationSubscription;
LocationData currentLocation;
@override
LocationState get initialState => LocationLoadingState();
@override
Stream<LocationState> mapEventToState(
LocationEvent event,
) async* {
if (event is GetCurrentLocation) {
yield* _mapToGetCurrentLocationState();
} else if (event is StartListeningForLiveLocation) {
yield* _mapToStartListeningUserLocation();
}else if (event is AddLiveUserLocation) {
yield UserLocationListeningState(event.location);
}
}
这是FoursquareBloc
:
class FoursquareBloc extends Bloc<FoursquareEvent, FoursquareState> {
final FoursquareRepository repo;
FoursquareBloc(this.repo);
@override
FoursquareState get initialState => Empty();
@override
Stream<FoursquareState> mapEventToState(
FoursquareEvent event,
) async* {
if (event is GetVenuesByUserEvent) {
yield Loading();
try {
final result = await repo.getVenuesByUser(event.lat, event.lng);
yield Loaded(result);
} on Exception catch (e) {
yield Error(e.toString());
}
}
}
}
它是否再次在BlocBuilder<LocationBloc, LocationState>(builder: (context, state)
下调用BlocBuilder还是我必须使用LocationBloc构造函数在LocationBloc内部调用FoursquareBlo
?
答案 0 :(得分:1)
我遇到了同样的问题,直到现在Flutter Bloc库都不支持MultiBlocBuilder。您可以使用嵌套的bloc生成器或创建将其他两个状态组合在一起的新bloc。我进行issue in Github检查以获取更多信息。