flutter - Flutter BLoc pass parameters
问题描述
I'm trying to pass parameters to a bloc event following the bloc pattern, I have found this article however my dart document couldn't find the dispatch
(event) method.
Flutter BLoC - How to pass parameter to event?
How do I pass parameters to something like this
main.dart
this works
_counterBloc.add(Counter.increment);
But this doesn't
_counterBloc.add(Counter.increment(3));
bloc.dart
import 'package:bloc/bloc.dart';
enum CounterEvents { increment }
class CounterBloc extends Bloc<CounterEvents, int> {
@override
int get initialState => 0;
@override
Stream<int> mapEventToState(CounterEvents event) async* {
switch (event) {
case CounterEvents.increment:
print(event);
yield state + 1;
break;
}
}
}
解决方案
你应该像下面这样写 CounterEvent:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum EventStatus { INCREMENT, DECREMENT }
class CounterEvent {
final int value;
final EventStatus status;
const CounterEvent({@required this.value, @required this.status});
}
class CounterBLoC extends Bloc<CounterEvent, int> {
@override
int get initialState => 0;
@override
Stream<int> mapEventToState(event) async* {
if (event.status == EventStatus.INCREMENT) {
yield state + event.value;
} else if (event.status == EventStatus.DECREMENT) {
yield state - event.value;
}
}
}
并在小部件中使用它们,如下所示:
@override
Widget build(BuildContext context) {
final counterBloc = BlocProvider.of<CounterBLoC>(context);
return Scaffold(
body: Center(
child: BlocBuilder<CounterBLoC, int>(
builder: (ctx, state) {
return Text(
'count: $state',
style: TextStyle(fontSize: 28),
);
},
),
),
floatingActionButton: Align(
alignment: Alignment.bottomRight,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton(
onPressed: () {
counterBloc
.add(CounterEvent(value: 5, status: EventStatus.INCREMENT));
},
child: Icon(Icons.add_circle),
),
FloatingActionButton(
onPressed: () {
counterBloc
.add(CounterEvent(value: 5, status: EventStatus.DECREMENT));
},
child: Icon(Icons.remove_circle),
),
],
),
),
);
}
确保在 main 中初始化您的 bloc:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BlocProvider<CounterBLoC>(
create: (ctx) => CounterBLoC(),
child: TestBlocWidget(),
),
);
}
}
推荐阅读
- go - 供应商问题:在我的供应商中找到包文本 (doc.go) 和转换 (examples_test.go)
- c# - 无法将 Heyzap 广告集成到我的 Unity 应用程序中
- java - 带有咖啡因的 Spring Boot 同步缓存不起作用
- ios - Swift:UIView 的背景渐变
- c# - 如何在后面的代码中使引导输入日历完全可见
- postgresql - Sequelize 中带日期的 Where 子句
- python - 用 numpy 计算矩阵乘积
- powershell - SCVMM Powershell 限制最大数量
- php - 从另一个 php 文件的文本框中的 php 文件执行函数
- checkbox - *ngFor 循环中的 Angular 5 Checkbox 并获取选中和未选中的特定复选框