Bor*_*ski 5 dependency-injection flutter bloc
我正在颤振中实现Reso Coder 的简洁架构。我按照他的指南将项目划分为层并使用依赖注入。在其中一种情况下,我希望有以下场景:管理员用户登录,在其主屏幕上查看数据,对其进行编辑,然后按一个按钮,将数据保存到本地数据库 (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);
},
),
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是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(),
);
}
}
Run Code Online (Sandbox Code Playgroud)
SettingsBloc 是具有事件和状态以及映射器方法的标准块模式。它正在使用get_it包注入。下面是实例化的方法:
serviceLocator.registerFactory(
() => SettingsBloc(
pullUsersFromServerCommand: serviceLocator(),
getSettingsQuery: serviceLocator(),
updateSettingsCommand: serviceLocator(),
),
);
Run Code Online (Sandbox Code Playgroud)
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");
}
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
我第一次进入这个屏幕时一切正常。数据是从数据库中获取的,加载到屏幕上,如果我更改它并按 SAVE,它会显示snackbar. 我的问题是我是否想在停留在该屏幕上的同时再次编辑数据。我再次编辑它,因此触发更改事件,集团获取它,调用下面的正确命令并将数据保存在数据库中。然后更改块的状态以试图告诉 UI,“嘿,我有一个新状态,使用它”。但是BlocListener永远不会再被调用。
我应该如何实现我想要的行为?
编辑: 我正在添加我之前在我登录用户的应用程序中使用的另一个块。登录页面使用该块,如果用户名或密码错误,我将显示一个小吃栏,清除输入字段并让页面为更多内容做好准备。如果我用错误的凭据再试一次,我可以再次看到小吃店。
这是登录块:
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");
}
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里的Event和State类扩展了Equatable。由于它按预期工作,因此我在“设置”页面(失败的地方)中以相同的方式进行了操作。从用户界面中,我可以LoginButtonPressedEvent根据需要多次提出并BlocListener分别调用。
Fed*_*han 10
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");
}
});
Run Code Online (Sandbox Code Playgroud)
一般来说,如果您想优化代码以减少重新构建的次数,您应该使用 Equatable。如果您希望相同的状态背靠背触发多个转换,则不应使用 Equatable。
来源: 何时使用等同
它如何与 flutter_bloc 一起工作是你不能产生相同的状态。是的,当您发出事件时,yield 状态之前的上述函数工作正常,但不会调用 yield 本身。
所以基本上你的集团会发生什么,
如何解决这个问题?我没有足够的信心根据我目前的知识给出建议,所以也许试试引用所说的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()
@Federick Jonathan已经对这个问题给出了足够的解释,但我想在这方面做插件。
首先:
这是 的标准行为Equatable,当状态发生变化时事件监听器被调用。如果你yield每次都处于相同的状态,那么什么都不会发生。
让我们讨论所有可能的解决方案。
从块中删除Equatable,然后每个事件在state更改时触发。
为状态进行定义start和说明。end例如,创建第一个stateasStartDataUpdate和第二个 as EndDataUpdate。
参考下面的代码
yield StartDataUpdate();
//Here... Please specified data changes related to operation.
yield EndDataUpdate();
Run Code Online (Sandbox Code Playgroud)
Stream<ReportsState> setupState({required ReportsState state}) async* {
yield StartReportsState();
yield state;
yield EndReportsState();
}
Run Code Online (Sandbox Code Playgroud)
使用:
yield* setupState( state: NavigationState() );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4522 次 |
| 最近记录: |