Flutter Bloc:RepositoryProvider和RepositoryProvider.value之间的差



我知道RepositoryProvider和RepositoryProvider.value之间的区别:第一个为您创建存储库,第二个接收已经创建的存储库。

请查看这两个代码块之间的差异-第一个代码块可以,第二个代码块给出以下错误。

RepositoryProvider.of() called with a context that does not contain a repository of type AuthRepository.
No ancestor could be found starting from the context that was passed to RepositoryProvider.of<AuthRepository>().
This can happen if the context you used comes from a widget above the RepositoryProvider.
The context used was: HomeScreen(dirty)

我不明白为什么代码2会出现错误。

代码1:成功

class MyApp {
void main() {
// 1) Let the RepositoryProvider create the AuthRepository
runApp(RepositoryProvider(
crate: (context) => AuthRepository(),
child: BlocProvider(
create: (context) => AuthCubit(authRepository: RepositoryProvider.of<AuthRepository>(context)),
child: const MaterialApp(
// 2) Show HomeScreen that will access the AuthRepository instance
home: HomeScreen()
)
)
)
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final authCubit = BlocProvider.of<AuthCubit>(context);
// 3) This will succeed
final authRepo = RepositoryProvider.of<AuthRepository>(context);
return Scaffold(
body: BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
return const Text(state.toString());
},
),
);
}
}

代码2:错误

class MyApp {
void main() {
// 1) Create a repository instance of AuthRepository
final authRepo = AuthRepository();
// 2) Add this AuthRepository instance to the RepositoryProvider.value
runApp(RepositoryProvider.value(
value: (context) => authRepo,
child: BlocProvider(
create: (context) => AuthCubit(authRepository: authRepo),
child: const MaterialApp(
// 3) Show HomeScreen that will access the AuthRepository instance
home: HomeScreen()
)
)
)
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final authCubit = BlocProvider.of<AuthCubit>(context);
// 4) This will fail
final authRepo = RepositoryProvider.of<AuthRepository>(context);
return Scaffold(
body: BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
return const Text(state.authenticationStatus.toString());
},
),
);
}

}

值应该是存储库,而不是函数。

代替

runApp(RepositoryProvider.value(
value: (context) => authRepo,

尝试

runApp(RepositoryProvider.value(
value: authRepo,

相关内容

  • 没有找到相关文章

最新更新