在Flutter中,是否可以使用Provider创建监听函数

In Flutter, is it possible to use Provider to create a listener function

所以我有这个提供商

import 'package:flutter/material.dart';
import 'package:gotaxi_flutter/enums.dart';
import 'package:gotaxi_flutter/models/google_places_models/google_places_models.dart';

class PlaceInfo {
  GooglePlace place;
  bool isDestination;
  PlaceInfo(this.place, this.isDestination);
}

class RideInfoProvider with ChangeNotifier {
  CurrentRideScreen _currentRideScreen = CurrentRideScreen.none;
  PlaceInfo? _place;

  PlaceInfo? get place => _place;

  CurrentRideScreen get currentRideScreen => _currentRideScreen;

  void setCurrentRideScreen(CurrentRideScreen screen) {
    _currentRideScreen = screen;
    notifyListeners();
  }

  //set origin or destination locations
  void setPlace(GooglePlace place, bool isDestination) {
    _place = PlaceInfo(place, isDestination);
    notifyListeners();
  }
}

如何在我的小部件中创建类似于以下内容的内容:

@override
  void initState() {
    super.initState();

    _rideInfoProvider = RideInfoProvider();

    _rideInfoProvider.addListener(() {
      print("RideInfoProvider changed");
      if (_rideInfoProvider.place != null) {
        print(_rideInfoProvider.place);
        //run other functions or instances that exist in this widget and may utilize the place variable
      }
    });

}

否则,我必须将整个侦听器逻辑和变量移至提供程序。

您可以根据有状态的小部件生命周期添加和删除您的侦听器。 这意味着 myListenerFunction 将在每次从 RideInfoProvider 调用 notifyListeners() 时被调用,直到小部件被处置。 请务必将侦听器添加为单独的函数,以便稍后能够将其删除(传递给函数的相同引用)。

正如@josip-domazet 评论的那样,我不建议为此使用消费者,因为它会从小部件的构建方法内部调用 myListenerFunction,因此每次 flutter 重绘时都会调用它小部件,而不是仅在通知程序中进行新更改时。

@override
  void initState() {
    super.initState();

    _rideInfoProvider = context.read<RideInfoProvider>();

    _rideInfoProvider.addListener(myListenerFunction);

}


@override
  void dispose() {
    super.dispose();

    _rideInfoProvider.removeListener(myListenerFunction);

}