gpt4 book ai didi

即使在事件重新触发后 Flutter BlocListener 也只执行一次

转载 作者:行者123 更新时间:2023-12-03 13:30:37 25 4
gpt4 key购买 nike

我正在实现 Reso Coder's clean architecture在 flutter 中。我按照他的指南将项目划分为层并使用依赖注入(inject)。在其中一种情况下,我希望有以下场景:管理员用户登录,在其主屏幕上查看数据,对其进行编辑,然后按一个按钮,将数据保存到本地数据库 (sqflite)。保存数据后,我想显示 Snackbar带有某种文本“设置已保存!”例如。这是我的代码(部分):

class AdministratorPage extends StatefulWidget {
@override
_AdministratorPageState createState() => _AdministratorPageState();
}

class _AdministratorPageState extends State<AdministratorPage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
centerTitle: true,
leading: Container(),
title: Text(AppLocalizations.of(context).translate('adminHomeScreen')),
),
body: SingleChildScrollView(
child: buildBody(context),
),
);
}

BlocProvider<SettingsBloc> buildBody(BuildContext context) {
return BlocProvider(
create: (_) => serviceLocator<SettingsBloc>(),
child: BlocListener<SettingsBloc, SettingsState>(
listener: (context, state) {
if (state is SettingsUpdatedState) {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).translate('settingsUpdated')),
backgroundColor: Colors.blue,
),
);
}
},
child: Column(
children: <Widget>[
SizedBox(
height: 20.0,
),
AdministratorInput(),
SizedBox(
width: double.infinity,
child: RaisedButton(
child: Text('LOG OUT'),
onPressed: () {
serviceLocator<AuthenticationBloc>().add(LoggedOutEvent());
Routes.sailor(Routes.loginScreen);
},
),
),
],
),
),
);
}
}

这是 AdministratorInput小部件:
class AdministratorInput extends StatefulWidget {
@override
_AdministratorInputState createState() => _AdministratorInputState();
}

class _AdministratorInputState extends State<AdministratorInput> {
String serverAddress;
String daysBack;
final serverAddressController = TextEditingController();
final daysBackController = TextEditingController();

@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: BlocBuilder<SettingsBloc, SettingsState>(
builder: (context, state) {
if (state is SettingsInitialState) {
BlocProvider.of<SettingsBloc>(context)
.add(SettingsPageLoadedEvent());
} else if (state is SettingsFetchedState) {
serverAddressController.text =
serverAddress = state.settings.serverAddress;
daysBackController.text =
daysBack = state.settings.daysBack.toString();
}

return Column(
children: <Widget>[
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(AppLocalizations.of(context)
.translate('serverAddress')),
],
),
),
Container(
height: 40.0,
child: TextField(
controller: serverAddressController,
decoration: InputDecoration(
border: OutlineInputBorder(),
),
onChanged: (value) {
serverAddress = value;
},
),
),
SizedBox(
height: 5.0,
),
// Days Back Text Field
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(AppLocalizations.of(context).translate('daysBack')),
],
),
),
Container(
height: 40.0,
child: TextField(
controller: daysBackController,
decoration: InputDecoration(
border: OutlineInputBorder(),
),
onChanged: (value) {
daysBack = value;
},
),
),
SizedBox(
width: double.infinity,
child: RaisedButton(
child: Text('SAVE CHANGES'),
onPressed: updatePressed,
),
),
SizedBox(
width: double.infinity,
child: RaisedButton(
child: Text('REFRESH'),
onPressed: refreshPressed,
),
),
],
);
},
),
),
);
}

void updatePressed() {
BlocProvider.of<SettingsBloc>(context).add(
SettingsUpdateButtonPressedEvent(
settings: SettingsAggregate(
serverAddress: serverAddress,
daysBack: int.parse(daysBack),
),
),
);
}

void refreshPressed() {
BlocProvider.of<SettingsBloc>(context).add(
SettingsRefreshButtonPressedEvent(),
);
}
}

SettingsBloc 是具有事件和状态以及映射器方法的标准 block 模式。它正在使用 get_it 注入(inject)。包裹。这是实例化的方式:
serviceLocator.registerFactory(
() => SettingsBloc(
pullUsersFromServerCommand: serviceLocator(),
getSettingsQuery: serviceLocator(),
updateSettingsCommand: serviceLocator(),
),
);

bloc 构造函数的所有命令实例和查询都以相同的方式正确实例化。

这是集团:
class SettingsBloc extends Bloc<SettingsEvent, SettingsState> {
final PullUsersFromServerCommand pullUsersFromServerCommand;
final UpdateSettingsCommand updateSettingsCommand;
final GetSettingsQuery getSettingsQuery;

SettingsBloc({
@required PullUsersFromServerCommand pullUsersFromServerCommand,
@required UpdateSettingsCommand updateSettingsCommand,
@required GetSettingsQuery getSettingsQuery,
}) : assert(pullUsersFromServerCommand != null),
assert(updateSettingsCommand != null),
assert(getSettingsQuery != null),
pullUsersFromServerCommand = pullUsersFromServerCommand,
updateSettingsCommand = updateSettingsCommand,
getSettingsQuery = getSettingsQuery;

@override
SettingsState get initialState => SettingsInitialState();

@override
Stream<SettingsState> mapEventToState(SettingsEvent event) async* {
if (event is SettingsPageLoadedEvent) {
final getSettingsEither = await getSettingsQuery(NoQueryParams());

yield* getSettingsEither.fold((failure) async* {
yield SettingsFetchedFailureState(error: "settingsDatabaseError");
}, (result) async* {
if (result != null) {
yield SettingsFetchedState(settings: result);
} else {
yield SettingsFetchedFailureState(
error: "settingsFetchFromDatabaseError");
}
});
} else if (event is SettingsUpdateButtonPressedEvent) {
final updateSettingsEither = await updateSettingsCommand(
UpdateSettingsParams(settingsAggregate: event.settings));

yield* updateSettingsEither.fold((failure) async* {
yield SettingsUpdatedFailureState(error: "settingsDatabaseError");
}, (result) async* {
if (result != null) {
yield SettingsUpdatedState();
} else {
yield SettingsUpdatedFailureState(
error: "settingsUpdateToDatabaseError");
}
});
} else if (event is SettingsRefreshButtonPressedEvent) {
final pullUsersFromServerEither =
await pullUsersFromServerCommand(NoCommandParams());

yield* pullUsersFromServerEither.fold((failure) async* {
yield SettingsRefreshedFailureState(
error: "settingsRefreshDatabaseError");
}, (result) async* {
if (result != null) {
yield SettingsUpdatedState();
} else {
yield SettingsRefreshedFailureState(error: "settingsRefreshedError");
}
});
}
}
}

我第一次进入这个屏幕时,一切都很完美。数据是从数据库中获取的,加载到屏幕上,如果我更改它并按 SAVE,它会显示 snackbar .我的问题是如果我想在停留在该屏幕上时再次编辑数据。我再次编辑它,因此触发更改事件,bloc 获取它,调用下面的正确命令并将数据保存在数据库中。然后更改 bloc 的状态以试图告诉 UI,“嘿,我有一个新状态,使用它”。但是 BlocListener永远不会再被调用。

我应该如何实现我想要的行为?

编辑:
我在登录用户的应用程序中添加了我之前使用的另一个 block 。登录页面使用了该 block ,并且在错误的用户名或密码时,我显示了一个 snackbar ,清除输入字段并让页面准备好更多。如果我使用错误的凭据再次尝试,我可以再次看到 snackbar 。

这是登录 block :
class LoginBloc extends Bloc<LoginEvent, LoginState> {
final AuthenticateUserCommand authenticateUserCommand;
final AuthenticationBloc authenticationBloc;

LoginBloc({
@required AuthenticateUserCommand authenticateUserCommand,
@required AuthenticationBloc authenticationBloc,
}) : assert(authenticateUserCommand != null),
assert(authenticationBloc != null),
authenticateUserCommand = authenticateUserCommand,
authenticationBloc = authenticationBloc;

@override
LoginState get initialState => LoginInitialState();

@override
Stream<LoginState> mapEventToState(LoginEvent event) async* {
if (event is LoginButtonPressedEvent) {
yield LoginLoadingState();

final authenticateUserEither = await authenticateUserCommand(
AuthenticateUserParams(
username: event.username, password: event.password));

yield* authenticateUserEither.fold((failure) async* {
yield LoginFailureState(error: "loginDatabaseError");
}, (result) async* {
if (result != null) {
authenticationBloc.add(LoggedInEvent(token: result));
yield LoginLoggedInState(result);
} else {
yield LoginFailureState(error: "loginUsernamePasswordError");
}
});
}
}
}
EventState这里的类(class)扩展 Equatable .而且由于它按照预期工作,我在“设置”页面中以同样的方式进行了操作(失败的地方)。从 UI 我提出 LoginButtonPressedEvent我想要多少次都可以, BlocListener分别被调用。

最佳答案

    else if (event is SettingsUpdateButtonPressedEvent) {
final updateSettingsEither = await updateSettingsCommand(
UpdateSettingsParams(settingsAggregate: event.settings));

yield* updateSettingsEither.fold((failure) async* {
yield SettingsUpdatedFailureState(error: "settingsDatabaseError");
}, (result) async* {
if (result != null) {
//
// this part is the problem.
yield SettingsUpdatedState();
} else {
yield SettingsUpdatedFailureState(
error: "settingsUpdateToDatabaseError");
}
});

In general, you should use Equatable if you want to optimize your code to reduce the number of rebuilds. You should not use Equatable if you want the same state back-to-back to trigger multiple transitions.



来源: when-to-use-equatable

它与 flutter_bloc 的工作原理是你不能产生相同的状态。是的,当您发出事件时,yield 状态之前的上述函数工作正常,但不会调用 yield 本身。

所以基本上你的集团会发生什么,
  • 当前状态为 SettingsFetchedState(settings: result)
  • 你发出 SettingsUpdateButtonPressedEvent()
  • 集团 yield SettingsUpdatedState()
  • 状态从 SettingsFetchedState(settings: result) 更改为 SettingsUpdatedState()
  • 当前状态为 SettingsUpdatedState()
  • BlocListener 监听从 SettingsFetchedState(settings: result) 到 SettingsUpdatedState() 的状态变化
  • 你发出 SettingsUpdateButtonPressedEvent()
  • Bloc 不会产生 SettingsUpdatedState(),它会被忽略,因为相等比较返回 true)
  • BlocListener 什么都不做,因为没有状态变化。

  • 如何解决这个问题?根据我目前的知识,我没有足够的信心给出建议,所以不妨试试报价中所说的 You should not use Equatable if you want the same state back-to-back to trigger multiple transitions.
    编辑:

    LoginBloc 之所以起作用,仅仅是因为它为每个事件产生不同的状态。我认为您没有注意到,但它会在产生 LoginLoggedInState(result) 或 LoginFailureState(error: "loginUsernamePasswordError") 之前产生 LoginLoadingState()
  • 当前状态为 LoginInitialState()
  • 发射事件
  • 产生 LoginLoadingState()
  • 状态从 LoginInitialState() 更改为 LoginLoadingState()
  • 产生 LoginLoggedInState() 或 LoginFailurestate()
  • 状态从 LoginLoadingState() 更改为 LoginLoggedInState() 或 LoginFailurestate()
  • 对于每个事件返回第 2 步
  • 关于即使在事件重新触发后 Flutter BlocListener 也只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596635/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com