我真的被这部分代码所困扰(我是Flutter的初学者)。我想显示秒表计时器和距geolocator的总距离,但是秒表只是在“ geolocation”移动时更新。
按下按钮时,我将其称为:
void _toggleListening() {
if (_positionStreamSubscription == null) {
const LocationOptions locationOptions =
LocationOptions(accuracy: LocationAccuracy.best);
final Stream<Position> positionStream =
Geolocator().getPositionStream(locationOptions);
_positionStreamSubscription = positionStream.listen((Position position) {
setState(() {
_positions.add(position);
_allPositions = _positions;
_positionRealTime = position;
updatePinOnMap();
print('all lenght ${_allPositions.length}');
totalDistanceAux = 0.0;
for (var i = 0; i < _allPositions.length - 1; i++) {
totalDistanceAux = totalDistanceAux +
distance.as(
LengthUnit.Meter,
LatLng(_allPositions[i].latitude, _allPositions[i].longitude),
LatLng(_allPositions[i + 1].latitude,
_allPositions[i + 1].longitude),
);
}
totalDistance = totalDistanceAux;
print('total distance $totalDistance');
});
});
_positionStreamSubscription.pause();
_stopwatch.stop();
} else {
setState(() {
if (_positionStreamSubscription.isPaused == true) {
_positionStreamSubscription.resume();
_stopwatch.start();
}
});
}
}
我正在与FutureBuilder一起显示:
FutureBuilder<GeolocationStatus>(
future: Geolocator().checkGeolocationPermissionStatus(),
builder: (BuildContext context,
AsyncSnapshot<GeolocationStatus> snapshot) {
距离和计时器工作正常,唯一的问题是计时器仅在发生一些移动时才更新。 这是我在StackOverflow上遇到的第一个问题,对不起,如果我做错了什么。谢谢!
答案 0 :(得分:0)
如果要定期重建窗口小部件,请添加timer_builder软件包并像这样使用它:
TimerBuilder.periodic(Duration(seconds: 1),
builder: (context) {
return YourWidget();
}
)