我有这个代码用于在屏幕上收听 bloc。
late MyBloc myBloc;
@override
void initState() {
print('inside init state');
super.initState();
myBloc = BlocProvider.of<MyBloc>(context);
myBloc.stream.listen((state) {
if (state is MyAddCompletedState) {
print('listening to bloc');
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我添加一个事件,它将打印一次监听 bloc 。如果我转到另一个屏幕并返回到同一屏幕,它将打印两次“listening to bloc”。看来我的第一次聆听仍然活跃。接下来,我尝试关闭我的处置块,认为它会停止第一次监听。这样,当我回到屏幕时,它将进行新的监听,但会出现错误:错误状态:调用 close 后无法添加新事件。我尝试对此进行研究,并提到要处置该块,但它不再具有该语法。请帮助我在更改屏幕后如何正确关闭或停止监听。谢谢!
//this is found on my screen
late MyBloc myBloc;
@override
void initState() {
print('inside init state');
super.initState();
myBloc = BlocProvider.of<MyBloc>(context);
myBloc.stream.listen((state) {
if (state is MyAddCompletedState) {
print('listening to bloc'); …Run Code Online (Sandbox Code Playgroud) 请帮助解释为什么有时我的 SnackBar 显示错误。我不明白在什么情况下会出现这个问题。我还想指出,即使它显示错误,但在应用程序本身中,它工作正常。
这是我的代码:
void showFailedSnackBar(String s) {
SnackBar snackBar = SnackBar(
content: Text(s),
duration: Duration(seconds: 3),
backgroundColor: Theme.of(context).primaryColor,
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
E/flutter ( 7879): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 7879): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
Run Code Online (Sandbox Code Playgroud) 我正在使用 bloc: ^7.0.0 这是目前最新的 bloc 包,现在说听方法现在已被弃用。相反,我应该使用stream.listen。但我不明白如何使用stream.listen。请帮忙解释一下。谢谢!
下面是我的代码:
signInBloc.l?i?s?t?e?n?((state) {
if (state is CheckIfSignedInEventCompletedState) {
if (state.isSignedIn) {
print('logged in');
} else {
print('not logged in');
}
}
Run Code Online (Sandbox Code Playgroud)
class SignInBloc extends Bloc<SignInEvent, SignInState> {
@override
Stream<SignInState> mapEventToState(
SignInEvent event,
) async* {
if (event is CheckIfSignedInEvent) {
yield* mapCheckIfSignedInEventToState();
}
}
Stream<SignInState> mapCheckIfSignedInEventToState() async* {
try {
bool isSignedIn = await authenticationRepository.checkIfSignedIn();
if (isSignedIn != null) {
if (isSignedIn) {
yield CheckIfSignedInEventCompletedState(true);
} else {
yield CheckIfSignedInEventCompletedState(false);
}
} else { …Run Code Online (Sandbox Code Playgroud) 我正在使用https://pub.dev/packages/flutter_secure_storage(使用 Await/Async 函数)来存储值并稍后检索它。请注意,每次打开应用程序时,我都会更新该值。我只是将其用于在应用程序打开时存储和检索值的目的。不要存储,以便当应用程序关闭然后再次打开时,我可以检索它。
现在我已经了解了https://pub.dev/packages/get,它很有前途,因为我可以使我的变量可观察,这似乎更容易使用,编码更少。
现在我只想向那些了解这两个 flutter 包的专家寻求建议,是否值得从使用flutter_secure_storage迁移到get。谢谢!
我只想了解为什么会发生以下情况:
Msgbox True
Output: True
Msgbox -True
Output: 1
Run Code Online (Sandbox Code Playgroud)
为什么会变成1?