Flutter Provider - 小部件不订阅更新

Flutter Provider - Widget not subscribing to updates

我想让我的小部件收听对提供的 FormViewModelChangNotifier 的更新。在小部件中,使用以下方式访问和订阅通知程序:

FormViewModel model = Provider.of<FormViewModel>(context);

FormViewModel 使用以下方法创建:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Nothing New';
    return MultiProvider(
      providers: [
        Provider<FormViewModel>(
          create: (_) => FormViewModel(Loading(), FirebaseService(), ImageUploadService()),
        )
      ],
      child: MaterialApp(
        title: "XX",
        home: Scaffold(
          appBar: AppBar(
            title: Text(appTitle),
          ),
          body: MyCustomForm(),
        ),
      ),
    );
  }
}

FormViewModel 扩展 BaseViewModel。我已验证状态设置正确,但下面的打印语句中没有侦听器:

class BaseViewModel<T> with ChangeNotifier {

  T _state;
  T get state => _state;

  BaseViewModel(T viewState) {
    setState(viewState);
  }

  void setState(T viewState) {
    print("state change: $viewState");
    _state = viewState;
    print('has listeners: $hasListeners');
    notifyListeners();
    handleSideEffects(state);
  }

  @protected
  void handleSideEffects(T _state) {
    print("handle side effects for: $_state");
  }

  @protected
  void handleError(Object e) {
    print(e);
  }
}

您使用了错误的提供商。

如果您的对象是 ChangeNotifier 并且希望提供者在发生变化时重建依赖对象,您应该使用 ChangeNotifierProvider

ChangeNotifierProvider<FormViewModel>(
  create: (_) => FormViewModel(Loading(), FirebaseService(), ImageUploadService()),
)