我正在寻找使用bloc实现流的正确方法。我有一个AppUser
类型的appUser
,它根据stream
变化。我想在整个应用程序中使用bloc
来收听这个appUser
。
我现在的实现。
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(lazy: false, create: (context) => UserCubit())
],
child: MaterialApp(
theme: customTheme(context),
home: const MyWidget(),
));
}
UserCubit.dart
class UserCubit extends Cubit<UserState> {
final _firestore = FirebaseFirestore.instance;
final User? _currentUser = FirebaseAuth.instance.currentUser;
AppUser? appUser;
UserCubit() : super(UserInitialState()) {
emit(UserMainLoadingState());
_firestore
.collection("users")
.doc(_currentUser?.uid) // or whatever your collection name is
.snapshots()
.listen((event) {
event.exists
? {
print(" The user is ${event.data()}"),
appUser = AppUser.fromjson(event.data()!, event.id), // here it changes
emit(UserExists(user: appUser!))
}
: {print("Oops no user"), emit(UserNotExists())};
});
}
MyWidget.dart
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(
child: BlocBuilder(builder: (context, state) {
return Text(BlocProvider.of<UserCubit>(context).appUser.toString()); // I want to get the changes of appUser
})));
}
}
你应该像这样移动你的AppUser
到UserState
:
abstract class UserState extends Equatable {
final AppUser? appUser;
const UserState({this.appUser});
@override
List<Object?> get props => [appUser];
}
class UserExists extends UserState {
const UserExists({required AppUser user}) : super(appUser: user);
}
然后你可以从BlocBuilder
的状态中读取它,像这样:
BlocBuilder<UserCubit, UserState>(
builder: (context, state) {
return Text(state.appUser.toString());
},
);