Flutter Cubit:获取存储变量的好方法?

Flutter Cubit: good way to get stored variable?

我是第一次使用 Flutter 和 Cubit,我想知道这是否是检索存储变量的好方法,在我的 cas 中是当前登录的用户。

登录后,用户可以转到他的个人资料页面并查看it/update。

登录表单:

submit(BuildContext context) async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

      final authCubit = context.read<AuthCubit>();
      authCubit.login(
        email: _data.email!,
        password: _data.password!,
        deviceName: _deviceInfos.deviceName,
      );
    }
  }

AuthCubit:登录方法:

class AuthCubit extends Cubit<AuthState> {
  dynamic user;
  
  Future<void> login({
    required String email,
    required String password,
    required String deviceName,
  }) async {
    emit(AuthLoading());

    // Get the user from the API
    this.user = apiResponse['user'];

    emit(AuthConnected(user));
  }
}

个人资料页面:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: BlocBuilder<AuthCubit, AuthState>(
        builder: (context, state) {
          final user = context.read<AuthCubit>().user;

          return Center(
            child: Column(
              children: <Widget>[
                Text('Hello, ' + (user != null ? user['name'] : 'stranger.')),
                ElevatedButton(
                  onPressed: () {
                    context.read<AuthCubit>().logout();
                  },
                  child: Text('Logoout'),
                ),
              ],
            ),
          );
        },
      ),
    );
}

任何 suggestion/advice 真的很感激。谢谢!

好的,你的例子有什么问题是你根本没有使用状态。 User 是你状态的一部分,我看到你已经把它存储在这里 (emit(AuthConnected(user)),所以只需从 BLoC 中删除 user 对象:

class AuthCubit extends Cubit<AuthState> {
  Future<void> login({
    required String email,
    required String password,
    required String deviceName,
  }) async {
    emit(AuthLoading());

    // Get the user from the API
    final user = apiResponse['user'];

    emit(AuthConnected(user));
  }
}

然后,在 UI 中,您应该从状态对象而不是直接从 BLoC 获取用户:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: BlocBuilder<AuthCubit, AuthState>(
        builder: (context, state) {
          final user = state.user; // You should get the error here

          return Center(
            child: Column(
              children: <Widget>[
                Text('Hello, ' + (user != null ? user['name'] : 'stranger.')),
                ElevatedButton(
                  onPressed: () {
                    context.read<AuthCubit>().logout();
                  },
                  child: Text('Logoout'),
                ),
              ],
            ),
          );
        },
      ),
    );
}

现在您应该得到一个错误,因为并非所有状态都包含 user 对象,例如AuthLoading 缺少那个。要解决这个问题,您应该检查状态类型并相应地呈现 UI:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: BlocBuilder<AuthCubit, AuthState>(
        builder: (context, state) {
          if (state is AuthLoading) {
            return CircularProgressIndicator(); // E.g. show loader
          }

          final user = state.user;

          return Center(
            child: Column(
              children: <Widget>[
                Text('Hello, ' + (user != null ? user['name'] : 'stranger.')),
                ElevatedButton(
                  onPressed: () {
                    context.read<AuthCubit>().logout();
                  },
                  child: Text('Logoout'),
                ),
              ],
            ),
          );
        },
      ),
    );
}