我正在 Flutter 中制作自定义 TextField。
我需要传递已提交的信息。
但是,当我尝试打印该值时,没有任何变化。 但是当我尝试直接在此小部件中打印时,它打印成功。
class SearchTextField extends StatelessWidget {
const SearchTextField({
required this.hintText,
required this.onSubmitted,
super.key,
});
final String hintText;
final void Function(String value) onSubmitted;
@override
Widget build(BuildContext context) {
final isDark = context.isDarkTheme;
return Container(
height: 48,
width: double.infinity,
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
color: isDark ? AppColors.cardBgDark : AppColors.cardBg,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: TextField(
onSubmitted: onSubmitted,
textInputAction: TextInputAction.search,
style: AppFonts.body15R.copyWith(
color: isDark ? Colors.white : Colors.black,
),
decoration: InputDecoration(
filled: true,
fillColor: isDark ? AppColors.helpCardBgDark : AppColors.cardBg,
contentPadding: const EdgeInsets.symmetric(
vertical: 14,
horizontal: 16,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
prefixIcon: Image.asset(AppImages.search),
hintText: hintText,
hintStyle: const TextStyle(
color: Color(0xFFACACAC),
fontSize: 15,
fontFamily: 'SF Pro Text',
fontWeight: FontWeight.w400,
height: 1.33,
letterSpacing: -0.24,
),
),
),
);
}
}
SearchTextField(
hintText: 'Title',
onSubmitted: (searchText) {
// nothing happens here
print(searchText);
},
),
我尝试过的:
更新: 伙计们,我知道这有多么荒谬。 经过 5 个小时的原始处理,我终于找到了解决方案。 我在错误的屏幕上测试了它。 无论如何,感谢大家的帮助。我希望至少你会笑。
您提供的代码可以正常工作,请考虑到仅当用户指示他们已完成编辑字段中的文本时才会调用
onSubmitted
事件,这意味着如果用户单击“输入”,它将被调用已登录到控制台。如果您想监视更改,可以使用 onChanged
,只要用户添加任何新键,它就会打印该值。
class SearchTextField extends StatelessWidget {
final String hintText;
final Function(String value) onSubmitted;
final Function(String value) onChanged;
const SearchTextField({
required this.hintText,
required this.onSubmitted,
required this.onChanged,
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
height: 48,
width: double.infinity,
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: TextField(
onSubmitted: onSubmitted,
onChanged: onChanged,
....
然后您可以简单地在另一个小部件中使用它,如下所示:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SearchTextField(
hintText: 'Title',
onSubmitted: (searchText) {
print("submitted $searchText");
},
onChanged: (changedText) {
print("changed $changedText");
},
),
],
),
),
您可以在这里尝试一个工作示例: