【发布时间】:2021-11-16 09:26:57
【问题描述】:
我是 Flutter 的新手并坚持使用这个 我有一个页面,它使用一个名为 GoogleMapsNotifier 的类和 ChangeNotifier,当我弹出页面时,我想在这个类中处理 Stream(最后一个函数)。
class GoogleMapsNotifier with ChangeNotifier {
final geolocatorService = GeolocatorService();
final placesService = PlacesService();
final markerService = MarkerService();
Position? currentLocation;
List<PlaceSearch> searchResults = [];
StreamController<Place> selectedLocation = BehaviorSubject<Place>();
StreamController<LatLngBounds> bounds = BehaviorSubject<LatLngBounds>();
late Place selectedLocationStatic;
List<Marker> markers = <Marker>[];
GoogleMapsNotifier() {
setCurrentLocation();
}
setCurrentLocation() async {
currentLocation = await geolocatorService.determinePosition();
selectedLocationStatic = Place(
geometry: Geometry(
location: Location(
lat: currentLocation!.latitude, lng: currentLocation!.longitude),
),
name: '',
vicinity: '');
notifyListeners();
}
searchPlaces(String searchTerm) async {
searchResults = await placesService.getAutocomplete(searchTerm);
notifyListeners();
}
setSelectedLocation(String placeId) async {
var sLocation = await placesService.getPlace(placeId);
selectedLocation.add(sLocation);
selectedLocationStatic = sLocation;
searchResults = [];
markers = [];
var newMarker = markerService.createMarkerFromPlace(sLocation);
markers.add(newMarker);
var _bounds = markerService.bounds(Set<Marker>.of(markers));
bounds.add(_bounds as LatLngBounds);
notifyListeners();
}
@override
void dispose() {
selectedLocation.close();
super.dispose();
}
}
然后我有一个弹出页面的返回按钮,我之前用 Provider 调用了这个函数。
onTap: () async {
Provider.of<GoogleMapsNotifier>(context, listen: false)
.dispose();
Navigator.pop(context);
},
第一次可以正常使用,但是第二次进入页面并再次按下返回按钮时,它返回错误
未处理的异常:在被使用后使用了 GoogleMapsNotifier 处置。 E/flutter (13173):一旦你调用了 dispose() GoogleMapsNotifier,不能再使用了。
我该如何解决这个问题?
【问题讨论】:
标签: flutter flutter-provider flutter-change-notifier