我正在尝试使用 block 模式和 flutter_block
库创建一个应用程序。它正在运行,但现在我想减少代码。
我有很多:
Dart
Padding(
padding:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: TextField(
inputFormatters: [
BlacklistingTextInputFormatter(RegExp("[a-zA-Z]"))
],
decoration: InputDecoration(
labelText: 'label text'),
keyboardType: TextInputType.number,
controller: _service,
onChanged: (value) =>
{_prefsBloc.dispatch(SetServicePrefs(value))},
),
),
我正在将其转换为小部件:
Dart
class SettingTextField extends StatelessWidget {
final String text;
final String labelText;
SettingTextField({this.text, this.labelText});
@override
Widget build(BuildContext context) {
final PrefsBloc _prefsBloc = BlocProvider.of<PrefsBloc>(context);
final TextEditingController _controller = TextEditingController();
_controller.text = this.text;
if (this.text != null) {
_controller.selection = TextSelection.collapsed(offset: this.text.length);
}
return Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: TextField(
inputFormatters: [BlacklistingTextInputFormatter(RegExp("[a-zA-Z]"))],
decoration: InputDecoration(labelText: this.labelText),
keyboardType: TextInputType.number,
controller: _controller,
onChanged: (value) {}
);
}
}
对于每个字段,我有一个不同的事件要分派(dispatch)到 block 中,例如:
_prefsBloc.dispatch(SetServicePrefs(value))
但我真的不知道如何将类型 SetServicePrefs
传递给我的小部件并在 onChanged
函数中使用它。
我该如何解决这个问题?
最佳答案
您可以向 SettingTextField 添加额外的回调字段:
class SettingTextField extends StatelessWidget {
final String text;
final String labelText;
final Function(PrefsBloc bloc, value) onChanged;
...
TextField(
inputFormatters: [BlacklistingTextInputFormatter(RegExp("[a-zA-Z]"))],
decoration: InputDecoration(labelText: this.labelText),
keyboardType: TextInputType.number,
controller: _controller,
onChanged: (value) => onChanged(_prefsBloc, value)
)
...
}
然后调用SettingTextField:
SettingTextField(
...
onChanged: (bloc, value) => bloc.dispatch(SomeEventType(value))
...
)
关于dart - 如何将事件类型传递给具有 block 模式的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55437286/