我只是在一瞬间就知道了一肘。我在教程视频中学习,因此在该视频中,导师制作了一个登录页面,其中包含电子邮件和密码文本字段以及一个登录按钮。在该视频中,导师仍然使用旧版本的 flutter_bloc。当我遵循其中一行代码时出现警告
child: ElevatedButton(
onPressed: () {
context.watch<AuthCubit>().signIn(
_emailController.text,
_passwordController.text);
}
Run Code Online (Sandbox Code Playgroud)
该代码写在 onPressed 函数按钮内。它说这context.bloc已被弃用。当我尝试运行该应用程序时,它返回一个错误,因为我使用的 flutter_bloc 版本不支持空安全,因此我将其升级到当前版本(7.3.1),我在版本 6.1.0 变更日志中找到了这一点(你可以看到它在flutter_bloc 更改日志中)
deprecated: context.bloc in favor of context.read and context.watch
Run Code Online (Sandbox Code Playgroud)
因为我不知道区别,所以我只是更改context.bloc为context.watch然后再次运行该应用程序,它返回另一个错误
Tried to listen to a value exposed with a provider, from outside of the widget tree.
This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.
To fix, write:
Provider.of<AuthCubit>(context, listen: false);
It is unsupported …Run Code Online (Sandbox Code Playgroud) 所以,我在Cubit类中做了一个函数,它是从API获取数据。现在,如果我按下按钮,我就可以获得数据。我想让该函数在页面/屏幕打开时自动调用。供您参考,此页面是用户打开应用程序时将启动的第一个页面。这是我的一些代码。
class UsersCubit extends Cubit<UsersState> {
UsersCubit() : super(UsersInitial());
UserRepository _userRepository = UserRepository();
void getAllUsers() async{
emit(UsersLoading());
try{
ResponseUsers _data = await _userRepository.getUsers();
emit(UsersSuccess(_data));
} catch(e){
emit(UsersError(e.toString()));
}
}
}
Run Code Online (Sandbox Code Playgroud)
class UsersPage extends StatefulWidget {
const UsersPage({Key? key}) : super(key: key);
@override
_UsersPageState createState() => _UsersPageState();
}
class _UsersPageState extends State<UsersPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Users")),
body: BlocProvider(
create: (context) => UsersCubit(),
child: BlocConsumer<UsersCubit, UsersState>(
listener: (context, state) {
if(state is UsersLoading){
print("getting users …Run Code Online (Sandbox Code Playgroud)