I want my widget to listen to updates to the provided FormViewModel
, a ChangNotifier
. In the widget, the notifier is accessed and subscribed using:
FormViewModel model = Provider.of<FormViewModel>(context);
FormViewModel
is created using:
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
extends BaseViewModel
. I've verified that state is being set correctly, but there's no listeners in the print statements below:
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);
}
}
You're using the wrong provider.
You should use ChangeNotifierProvider
if your object is a ChangeNotifier
and wants the provider to rebuild dependents when there's a change.
ChangeNotifierProvider<FormViewModel>(
create: (_) => FormViewModel(Loading(), FirebaseService(), ImageUploadService()),
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.