ChangeNotifier被处理后使用



我是新来的扑动和坚持这个我有一个页面,使用一个名为GoogleMapsNotifier与ChangeNotifier的类,当我弹出页面时,我想在这个类(最后一个函数)内处置流。

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);
},

第一次可以正常工作,但是当我第二次进入页面并再次按下Go Back按钮时,它返回一个错误

未处理异常:一个GoogleMapsNotifier被使用后处理。E/flutter(13173):一旦在a上调用dispose()

我该如何解决这个问题?

Provider应该在你推的Route里面。如果使用全局提供程序,GoogleMapsNotifier的实例将始终是相同的。因此,当您第二次进入页面时,它将无法工作(因为它是您第一次处理的同一个实例)

下面是一个具体的例子

// GOOD
runApp(MaterialApp(...));
...
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ChangeNotifierProvider<GoogleMapsNotifier>(
create: (_) => GoogleMapsNotifier(),
child: ...,
),
),
);

// BAD
runApp(
ChangeNotifierProvider<GoogleMapsNotifier>(
create: (_) => GoogleMapsNotifier(),
child: MaterialApp(
home: ...,
),
)
);
...
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ...,
),
);

最新更新