클린 아키텍쳐 따라가면서 프로젝트 진행하던 도중, viewModel 에 접근해서 상태값 변경하려고 했다. 갑자기 Provider<모델> 을 접근할 수없으니
다른 방식으로 접근해봐라 라는 의미이다.
Error: Could not find the correct Provider<SearchViewModel> above this SearchScreen Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that SearchScreen is under your MultiProvider/Provider<SearchViewModel>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>().toString()),
);
}
di 폴더를 만들어서 의존성을 주입해주자.
import 'package:provider/provider.dart';
import 'package:what_do_you_want_to_sing/presentation/search/search_view_model.dart';
// 이곳에서 의존성을 한번에 불러 생성한 다음, main.dart 에 주입하겠다.
List<ChangeNotifierProvider<SearchViewModel>> getProviders() {
SearchViewModel searchViewModel = SearchViewModel();
return [
ChangeNotifierProvider(create: (_) => searchViewModel),
];
}
void main() {
// provider 호출
final providers = getProviders();
runApp(
MultiProvider(
providers: providers,
child: const MyApp(),
),
);
}