首页 > 解决方案 > 使用 copywith 时 Flutter Bloc 状态未更新

问题描述

大纲:

  1. 导航到个人资料页面
  2. 传入用户 ID 以从 firestore 获取文档
  3. 将检索到的数据传递给 state.copyWith(data:data)
  4. 产生一个成功的状态并呈现用户界面

我的问题是,当我使用 state.copyWith(data:data) 时,即使数据 100% 存在,状态也不会更新,因为我可以在控制台中打印它。

代码:

UI: 
class ProfileView extends StatelessWidget {
  final String uid;

  final UserRepository userRepository = UserRepository();

  ProfileView({required this.uid});

  @override
  Widget build(BuildContext context) {
    // Init repository
    return BlocProvider<ProfileBloc>(
        create: (context) => ProfileBloc(
            // Should be able to pull user repo from context
            userRepository: UserRepository(),
            isCurrentUser: UserRepository().isCurrentUser(uid))
          ..add(InitializeProfile(uid: uid)),
        // Get User Doc
        child: _profileView(context));
  }

  Widget _profileView(context) {
    return BlocListener<ProfileBloc, ProfileState>(
      listener: (context, state) {
        if (state.imageSourceActionSheetIsVisible) {
          _showImageSourceActionSheet(context);
        }
        final loadingStatus = state.loadingStatus;
        if (loadingStatus is LoadingFailed) {
          showSnackBar(context, state.loadingStatus.exception.toString());
        }
        if (loadingStatus is LoadingInProgress) {
          LoadingView();
        }
        if (loadingStatus is LoadingFailed) {
          LoadingFailedView(exception: loadingStatus.exception.toString());
        }
      },
      child: Scaffold(
        appBar: _appBar(),
        body: _profilePage(),
        bottomNavigationBar: bottomNavbar(context),
      ),
    );
  }



BLoC:
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  final bool isCurrentUser;
  final UserRepository userRepository;
  final _imagePicker = ImagePicker();

  ProfileBloc({
    required this.isCurrentUser,
    required this.userRepository,
  }) : super(ProfileState(
            isCurrentUser: isCurrentUser, loadingStatus: LoadingInProgress()));

  @override
  Stream<ProfileState> mapEventToState(
    ProfileEvent event,
  ) async* {
    if (event is InitializeProfile) {
      yield* _initProfile(uid: event.uid);
    }
  }

  Stream<ProfileState> _initProfile({required String uid}) async* {
    // Loading View
    yield state.copyWith(loadingStatus: LoadingInProgress());
    // Fetch profile data
    try {
      final snapshot = await userRepository.getUserDoc(uid);
      if (snapshot.exists) {
        final data = snapshot.data();
        print(data['fullName']);

        yield state.copyWith(
          fullName: data["fullName"].toString(),

        );
        print(state.fullName);
        yield state.copyWith(loadingStatus: LoadingSuccess());
      }
 
      else {
        yield state.copyWith(
            loadingStatus: LoadingFailed("Profile Data Not present :("));
      }
    } catch (e) {
      print(e);
    }
  }


State:
part of 'profile_bloc.dart';

class ProfileState {
  final bool isCurrentUser;
  final String? fullName;
  final LoadingStatus loadingStatus;
  bool imageSourceActionSheetIsVisible;

  ProfileState({
    required bool isCurrentUser,
    this.fullName,
    this.loadingStatus = const InitialLoadingStatus(),
    imageSourceActionSheetIsVisible = false,
  })  : this.isCurrentUser = isCurrentUser,
        this.imageSourceActionSheetIsVisible = imageSourceActionSheetIsVisible;

  ProfileState copyWith({
    bool? isCurrentUser,
    String? fullName,
    LoadingStatus? loadingStatus,
    bool? imageSourceActionSheetIsVisible,

  }) {
    print('State $fullName');
    print('State ${this.fullName}');
    return ProfileState(
      isCurrentUser: this.isCurrentUser,
      fullName: fullName ?? this.fullName,
      loadingStatus: loadingStatus ?? this.loadingStatus,
      imageSourceActionSheetIsVisible: imageSourceActionSheetIsVisible ??
          this.imageSourceActionSheetIsVisible,
    );
  }
}


新更新的代码实现 Bloc 构建器而不是建议的侦听器

  Widget _profileView(context) {
    return BlocBuilder<ProfileBloc, ProfileState>(builder: (context, state) {
      final loadingStatus = state.loadingStatus;
      if (loadingStatus is LoadingInProgress) {
        return LoadingView();
      }
      if (loadingStatus is LoadingFailed) {
        return LoadingFailedView(exception: loadingStatus.exception.toString());
      }
      if (loadingStatus is LoadingSuccess) {
        return Scaffold(
          appBar: _appBar(),
          body: _profilePage(),
          bottomNavigationBar: bottomNavbar(context),
        );
      }
      return LoadingView();
    });
  }

此代码仍然停留在加载屏幕上,当我打印出各种状态时,它被注册为一个事件,但是在使用 copy with 后状态打印出 null

谢谢您的帮助

标签: firebasefluttergoogle-cloud-firestorebloc

解决方案


从 bloc 文档中,我认为这是我的错误所在。

当我们在私有 mapEventToState 处理程序中产生一个状态时,我们总是产生一个新状态而不是改变状态。这是因为每次我们 yield 时,bloc 都会将 state 与 nextState 进行比较,并且只有在两个 state 不相等时才会触发 state 更改(transition)。如果我们只是变异并产生相同的状态实例,那么 state == nextState 将评估为 true 并且不会发生状态更改。


推荐阅读