我有一個登錄cubit,它將接受兩個引數,電子郵件和密碼。然后它會要求存盤庫給他該請求的回應。在呼叫存盤庫的函式之前,我發出加載狀態,當我從存盤庫接收到資料時,發出另一個狀態,即 SigninLoaded。我的登錄Cubit:
final SignInRepository signInRepository;
SigninCubit({required this.signInRepository}) : super(SigninInitial());
Future<void> signIn({String email = '', String password = ''}) async {
print("Cubit is invoked");
emit(SigninInLoading());
Timer(Duration(seconds: 0), () async {
await signInRepository
.signIn(email: email, password: password)
.then((signinModel) {
// print("SignIn Model is : ${signinModel}");??
emit(SigninLoaded(signInModel: signinModel));
});
});
}
}
登錄狀態
@immutable
abstract class SigninState {}
class SigninInitial extends SigninState {}
class SigninInLoading extends SigninState {}
class SigninLoaded extends SigninState {
SignInModel? signInModel;
SigninLoaded({required this.signInModel});
}
這就是我從 LoginPage 類呼叫我的 signinCubit 的方式。
BlocProvider.of<SigninCubit>(context).signIn(email: email, password: password);
當從 LoginPage 類呼叫 signinCubit 時,我看到它在同一個類中使用 BlocBuilder 像這樣回應;
BlocBuilder<SigninCubit, SigninState>(
builder: (context, state) {
if ((state is SigninInitial)) {
print("Initial State");
} else if (state is SigninInLoading) {
return Center(
child: CircularProgressIndicator(
color: AppColors.mainColor,
),
);
} else {
final signinData = (state as SigninLoaded).signInModel;
data = signinData;
}
但是,當我嘗試訪問回應或上次發出的 SigninLoaded 狀態時,我在其他類中獲得了初始狀態,我試圖在 Profile 類中像這樣獲得回應;
BlocBuilder<SigninCubit, SigninState>(
builder: (context, state) {
print("State : $state");
if (state is SigninLoaded) {
name = (state as SigninLoaded).signInModel?.data?.firstName;
print("Name $name");
}
return Text(
'Welcome, ${name}!',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w800,
),
);
},
),
我沒有得到回應,因為它說它處于初始狀態。
即使我也像這樣提供了 Blocs;
BlocProvider 到 LoginPage 類;
MaterialPageRoute(
builder: (_) => BlocProvider(
create: (BuildContext context) =>
SigninCubit(signInRepository: signInRepository),
child: LoginPage(),
),
);
BlocProvider 到 Profile 類;
MaterialPageRoute(
builder: (_) => BlocProvider(
create: (context) =>
SigninCubit(signInRepository: signInRepository),
child: Profile(),
));
uj5u.com熱心網友回復:
可能是我錯了,但在我看來,如果你想在 Profile 頁面中使用 SignInModel,你必須再次呼叫 signIn 函式
另一種解決方案:僅將 SignInCubit 的一個 BlocProvider 定義為 Profile 頁面和 SignIn 頁面的父級,例如:
MaterialPageRoute(builder: (_) => BlocProvider( create: (context) => SigninCubit(signInRepository: signInRepository), child: MyApp(), ));
將signinModel或(登錄資訊)保存在本地資料庫中,當我們進入ProfilePage時,從db中獲取
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449860.html
