gpt4 book ai didi

flutter - ChangeNotifier 被处理后被使用

转载 作者:行者123 更新时间:2023-12-03 08:16:14 32 4
gpt4 key购买 nike

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

第一次工作正常,但当我第二次进入页面并再次按“返回”按钮时,它返回错误

Unhandled Exception: A GoogleMapsNotifier was used after beingdisposed. E/flutter (13173): Once you have called dispose() on aGoogleMapsNotifier, it can no longer be used.

我该如何解决这个问题?

最佳答案

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: (_) => ...,
),
);

关于flutter - ChangeNotifier 被处理后被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69292237/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com