gpt4 book ai didi

flutter_block : BlockProvider vs. RepositoryProvider

转载 作者:行者123 更新时间:2023-12-04 10:48:18 27 4
gpt4 key购买 nike

我想澄清一下 BlocProviderRepositoryProvider .从官方 API 引用来看,它们提供了相同的功能——它们为它的后代小部件提供了一个对象的实例。
但是,从名称来看,我猜 BlocProvider应该用于 Bloc仅限对象,以及 RepositoryProvider对于其他一切。它是否正确?

最佳答案

RepositoryProvider 的行为类似于 Repository 模式
它的数据提供者向 Bloc 提供数据,因此 Bloc 不需要知道数据来自云或 sqflite 或......
并进行合并/过滤,请参见下面的官方示例

在下面的 LoginForm 示例中
存储库是 Bloc 的一部分,您可以使用 _userRepository.login

class LoginFormBloc extends FormBloc<String, String> {
final emailField = TextFieldBloc(validators: [Validators.email]);
final passwordField = TextFieldBloc();

final UserRepository _userRepository;

LoginFormBloc(this._userRepository);

@override
List<FieldBloc> get fieldBlocs => [emailField, passwordField];

@override
Stream<FormBlocState<String, String>> onSubmitting() async* {
try {
_userRepository.login(
email: emailField.value,
password: passwordField.value,
);
yield currentState.toSuccess();
} catch (e) {
yield currentState.toFailure();
}
}
}

您可以将您的存储库注入(inject) Bloc
代码片段
class LoginForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider<LoginFormBloc>(
builder: (context) =>
LoginFormBloc(RepositoryProvider.of<UserRepository>(context)),
child: Builder(
builder: (context) {
final formBloc = BlocProvider.of<LoginFormBloc>(context);

return Scaffold(
appBar: AppBar(title: Text('Simple login')),
body: FormBlocListener<LoginFormBloc, String, String>(
onSubmitting: (context, state) => LoadingDialog.show(context),
onSuccess: (context, state) {
LoadingDialog.hide(context);
Navigator.of(context).pushReplacementNamed('success');
},
onFailure: (context, state) {
LoadingDialog.hide(context);
Notifications.showSnackBarWithError(
context, state.failureResponse);
},

可以引用 https://flutterawesome.com/create-beautiful-forms-in-flutter/

官方示例 https://bloclibrary.dev/#/architecture
bloc 层可以依赖一个或多个存储库来检索构建应用程序状态所需的数据。
class Repository {
final DataProviderA dataProviderA;
final DataProviderB dataProviderB;

Future<Data> getAllDataThatMeetsRequirements() async {
final RawDataA dataSetA = await dataProviderA.readData();
final RawDataB dataSetB = await dataProviderB.readData();

final Data filteredData = _filterData(dataSetA, dataSetB);
return filteredData;
}
}

class BusinessLogicComponent extends Bloc<MyEvent, MyState> {
final Repository repository;

Stream mapEventToState(event) async* {
if (event is AppStarted) {
try {
final data = await repository.getAllDataThatMeetsRequirements();
yield Success(data);
} catch (error) {
yield Failure(error);
}
}
}
}

关于flutter_block : BlockProvider vs. RepositoryProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598151/

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