Flutter实现列表选中name值回显至TextFormField
实现列表选中项返回并填充TextFormField
修改TextFormField所在页面的跳转逻辑
将原onTap改为异步调用,接收列表页返回的选中值并更新输入框内容:
final TextEditingController _musteri = TextEditingController(); TextFormField( controller: _musteri, onTap: () async { // 跳转列表页并等待返回值 final selectedName = await Navigator.push( context, MaterialPageRoute<void>( builder: (BuildContext context) => const MusteriList(), ), ); // 若返回值不为空,设置到输入框 if (selectedName != null) { _musteri.text = selectedName; } }, textAlign: TextAlign.center, decoration: InputDecoration( labelText: 'Müşteri', labelStyle: TextStyle( fontFamily: 'Montserrat', color: Color.fromARGB(255, 139, 158, 131)), prefixIcon: Icon( Icons.person_outline, color: Color.fromARGB(255, 180, 147, 133), ), ), ),
修改用户列表页面的点击事件
将列表项点击时的跳转改为返回上一页,并传递选中的用户名称:
List<Map<String, dynamic>> _foundUsers = []; @override initState() { _foundUsers = _allUsers; super.initState(); } ListView.builder( itemCount: _foundUsers.length, itemBuilder: (context, index) => GestureDetector( onTap: () { // 返回上一页并传递选中的name字段值 Navigator.pop(context, _foundUsers[index]["name"]); }, child: Card( key: ValueKey(_foundUsers[index]["id"]), color: Colors.blueAccent, elevation: 4, margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15), child: ListTile( leading: Text( _foundUsers[index]["id"].toString(), style: TextStyle(fontSize: 24, color: Colors.white), ), title: Text( _foundUsers[index]["name"], style: TextStyle(fontSize: 14, color: Colors.white), ), ), ), ), ),
核心逻辑:
- 列表页通过
Navigator.pop(context, 返回值)向上一页传递选中数据 - 上一页用
await Navigator.push()接收返回值,更新TextEditingController内容完成输入框填充
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

