父小部件
class _FamilyListPageState extends State<FamilyListPage> {
String initialValue = 'Search Families';
void eraseInitialValue() { <-------------- This function is passed down to the child widget
setState(() {
initialValue = '';
print('Inside the set state'); <-------- This line gets executed.
});
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Search Families'),
centerTitle: true,
),
backgroundColor: StaticEntry.backColor,
body: Center(
child: FractionallySizedBox(
widthFactor: 0.8,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SearchInput( <----------------------------------------- Child Widget
initialValue: initialValue,
onTapHandler: eraseInitialValue,
),
],
),
),
),
),
);
}
}
子小部件
import 'package:flutter/material.dart';
class SearchInput extends StatelessWidget {
final String initialValue;
final Function onTapHandler; <----------- Function from the parent widget is stored in here
SearchInput({this.initialValue, this.onTapHandler});
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: Icon(
Icons.search,
size: 40,
),
title: Container(
child: TextFormField(
initialValue: initialValue,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins',
letterSpacing: 1),
onTap: onTapHandler, <--------------- This is where I have made a pointer at the function received from the parent widget to be executed when tapped.
),
),
),
),
);
}
}
背景
我有一个包含TextFormField的子小部件。该TextFormField的初始值是'Search Families'。当用户点击该TextFormField时,我试图删除该初始值,以便用户可以在该TextFormField中键入他/她想要的内容,而无需自己手动删除它。
我做了什么
为了实现这一点,我使我的父小部件成为有状态的小部件。我的父小部件的状态有一个名为initialValue的实例变量,它保存值“Search Families”,用于配置子小部件内TextFormField的initialValue属性。
然后我在父小部件中定义了一个名为eraseInitialValue的方法,它通过调用setState将initialValue实例变量的值重置为空字符串。
最后在子窗口小部件中,我在这个函数上给出了一个指针,以便TextFormField的onTap属性执行声明的函数,该函数又应该更新应用程序的状态。
问题
但是,“搜索家庭”文本永远不会改变。
(我在setState中添加了一条打印语句,以查看保存setState的函数是否被执行。确实如此。但状态没有更新。)
有人可以帮我理解这段代码不起作用吗?谢谢。