Flutter输入字符串与列表匹配并更新状态的技术求助
解决方案
一、修正列表匹配与状态更新逻辑
你原来的判断条件textController == listOfStrings完全错误——textController是控制器对象,无法直接和字符串列表比较。正确逻辑如下:
- 先获取输入框的文本内容,用
trim()去除前后空格避免匹配误差 - 判断列表是否包含该文本:
listOfStrings.contains(inputText) - 匹配成功时,在
setState里把activated设为true,并从列表中删除该文本
修改后的灰色Container点击事件代码:
InkWell( onTap: () { final inputText = textController.text.trim(); setState(() { if (listOfStrings.contains(inputText)) { activated = true; listOfStrings.remove(inputText); } else { // 可选:输入不匹配时重置状态,让容器回到红色 activated = false; } }); // 可选:匹配成功后清空输入框,方便下一次输入 textController.clear(); }, child: Container( height: 20, width: 60, color: Colors.blueGrey, ), )
二、实现键盘回车触发状态更新
可以通过TextFormField的onFieldSubmitted回调实现——因为你设置了textInputAction: TextInputAction.done,用户按下键盘回车(完成键)时会触发这个回调,直接复用点击事件的逻辑即可。
修改后的TextFormField代码:
TextFormField( autofocus: false, controller: textController, style: const TextStyle( color: Colors.white, fontSize: 12, ), textInputAction: TextInputAction.done, onFieldSubmitted: (_) { final inputText = textController.text.trim(); setState(() { if (listOfStrings.contains(inputText)) { activated = true; listOfStrings.remove(inputText); } else { activated = false; } }); textController.clear(); }, )
优化后完整代码
为了避免代码重复,我们可以把判断逻辑提取成公共方法:
import 'package:flutter/material.dart'; class Test extends StatefulWidget { const Test({Key? key}) : super(key: key); @override State<Test> createState() => _TestState(); } class _TestState extends State<Test> { bool activated = false; final TextEditingController textController = TextEditingController(); List<String> listOfStrings = [ 'String01', 'String02', 'String03', 'String04', 'String05', 'String06', 'String07', 'String08', 'String09', 'String10', ]; // 提取公共逻辑,减少代码冗余 void checkAndUpdateList() { final inputText = textController.text.trim(); setState(() { if (listOfStrings.contains(inputText)) { activated = true; listOfStrings.remove(inputText); } else { activated = false; } }); textController.clear(); } @override void dispose() { textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ const SizedBox(height: 20), Container( padding: const EdgeInsets.symmetric(horizontal: 10), alignment: Alignment.center, child: TextFormField( autofocus: false, controller: textController, style: const TextStyle( color: Colors.white, fontSize: 12, ), textInputAction: TextInputAction.done, onFieldSubmitted: (_) => checkAndUpdateList(), ), ), const SizedBox(height: 20), InkWell( onTap: checkAndUpdateList, child: Container( height: 20, width: 60, color: Colors.blueGrey, ), ), const SizedBox(height: 60), Container( width: 20, height: 20, color: activated ? Colors.green : Colors.red, ), ], ), ); } }
额外说明
- 用
trim()处理输入文本,避免用户误输入前后空格导致匹配失败 - 匹配成功后清空输入框,提升连续输入的体验
- 输入不匹配时重置
activated为false,让颜色容器回到红色状态(可根据需求去掉这部分)
内容的提问来源于stack exchange,提问作者Nomad09
相关产品推荐
相关产品推荐

