这个问题在这里已经有了答案:
Why can't I use context.read in build(), but I can use Provider.of with listen: false?
(2 个回答)
去年关闭。
我有这个无国籍的出生日期输入类,只读的。点击时,它会显示一个日期选择器,在用户选择一个日期后,它会将值发送到 bloc 状态,它会更改状态和值,以便显示从日期选择器中选择的日期。
这是代码:
class DateOfBirthInput extends StatelessWidget {
DateOfBirthInput({
required this.textEditingController,
required this.focusNode
});
final TextEditingController textEditingController;
final FocusNode focusNode;
@override
Widget build(BuildContext context) {
return BlocBuilder<SignUpBloc, SignUpState>(
buildWhen: (previous, current) => previous.dateOfBirth != current.dateOfBirth,
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Date of Birth',
style: TextStyle(
color: Colors.grey[500],
fontWeight: FontWeight.w600
)
),
TextFormField(
enabled: state.formEnabled,
controller: textEditingController,
focusNode: focusNode,
readOnly: true,
decoration: InputDecoration(
hintText: '1 January 1990',
hintStyle: TextStyle(
color: Colors.grey[400],
fontWeight: FontWeight.w500
),
suffixIcon: Icon(
Icons.calendar_today_outlined,
size: 24.0,
color: Colors.grey[500],
),
errorText: state.dateOfBirthDisplay.invalid ? 'Please enter your date of birth' : null,
errorStyle: TextStyle(
fontSize: 14.0,
color: Colors.red,
fontWeight: FontWeight.w500
),
),
onTap: () async {
DateTime? datePicker = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1900, 1),
lastDate: DateTime.now()
);
if (datePicker != null) {
String dateOfBirth = DateFormat('dd MMMM yyyy').format(DateTime.parse(datePicker.toString()));
textEditingController.text = dateOfBirth;
context.read<SignUpBloc>.add(DateOfBirthChanged(dateOfBirthDisplay: dateOfBirth, dateOfBirth: datePicker));
}
}
),
],
);
},
);
}
}
在这种情况下,我得到了一个错误。这是上下文:context.read<SignUpBloc>.add(DateOfBirthChanged(dateOfBirthDisplay: dateOfBirth, dateOfBirth: datePicker));
这是错误:The prefix 'context' can't be used here because it is shadowed by a local declaration. Try renaming either the prefix or the local declaration.
我试图改变其中一种情况,
builder: (context, state)
, 我已经改成 builder: (ctx, state)
,并且仍然得到相同的错误。请帮忙。
最佳答案
当前,您正尝试从注册 block 的构建器上下文中访问 SignupBloc,context
变量,因为您的无状态小部件的上下文和 blocbuilder 的上下文都被命名为 context
将您的上下文之一重命名为其他内容,build(BuildContext context)
或 builder: (context, state) {
您可以重命名builder: (ctx, state)
那么错误应该消失了。
关于android - 前缀 'context' 不能在此处使用,因为它被本地声明所遮蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67295618/