我有一个简单的服务,它正在跟踪当前用户的位置。
class LocationService {
LatLng _lastLocation;
Location location = Location();
StreamController<LatLng> _locationController = StreamController<LatLng>();
Stream<LatLng> get locationStream => _locationController.stream;
LocationService() {
location.onLocationChanged().listen((locationData) {
LatLng location = LatLng(locationData.latitude, locationData.longitude);
if(_lastLocation == null || _lastLocation != location) {
_lastLocation = location;
_locationController.add(location);
}
});
}
}
然后,我使用这个服务来创建一个地图(多亏了 扑腾图),它是跟随当前用户位置的。
class SelfUpdatingMap extends StatelessWidget {
final Icon currentPositionIcon;
final MapController _controller = MapController();
SelfUpdatingMap({
this.currentPositionIcon,
});
@override
Widget build(BuildContext context) => StreamBuilder<LatLng>(
stream: LocationService().locationStream,
builder: (context, asyncSnapshot) {
if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
return Text('Loading...');
}
try {
_controller?.move(asyncSnapshot.data, 18);
} catch (ignored) {}
return _createMapWidget(context, asyncSnapshot.data);
},
);
Widget _createMapWidget(BuildContext context, LatLng location) => FlutterMap(
options: MapOptions(
center: location,
zoom: 18,
),
layers: [
TileLayerOptions(
urlTemplate: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png', // https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png is good too.
subdomains: ['a', 'b', 'c'],
),
MarkerLayerOptions(
markers: [
Marker(
width: 40,
height: 40,
point: location,
builder: (contact) => currentPositionIcon,
),
]
),
],
mapController: _controller,
);
}
然后,我使用 SelfUpdating
小部件在两个地方。
所以这里的情况是 。
SelfUpdatingMap
.Navigator.pushNamed(context, '/page-2')
.Navigator.pushNamed(context, '/page-3')
. 我还有一个 SelfUpdatingMap
.Navigator.pop(context)
,我得到的是 第1页 但是 的 SelfUpdatingMap
不更新自己了。建造者甚至不再被调用。所以请问,这段代码有什么问题?
谢谢你!我有一个简单的服务,它可以跟踪当前用户的位置:类LocationService { LatLng _lastLocation
当你推送和弹出一个页面后,构建metod并没有重新启动.我发现FlutterBluetoothSerial.instance.onStateChanged()流也有同样的问题,我找到的解决方案是将该流添加到本地静态最终变量中并使用它,而不是每次调用原来的方法(只有当该流是广播流时,你才能做到这一点,我认为)。
解决方案的例子。
class ExampleClass {
static final Stream<LatLng> locationStream = LocationService().locationStream;
}
class SelfUpdatingMap extends StatelessWidget {
...
@override
Widget build(BuildContext context) => StreamBuilder<LatLng>(
stream: ExampleClass.locationStream,
builder: (context, asyncSnapshot) {
if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
return Text('Loading...');
}
try {
_controller?.move(asyncSnapshot.data, 18);
} catch (ignored) {}
return _createMapWidget(context, asyncSnapshot.data);
},
);
...
}
class Page3Widget extends StatelessWidget {
...
@override
Widget build(BuildContext context) => StreamBuilder<LatLng>(
stream: ExampleClass.locationStream,
builder: (context, asyncSnapshot) {
//do something
},
);
...
}