Flutter通过用户输入调用NumbersApi获取数字趣闻不展示问题求助
问题排查及修复方案
核心遗漏点
- 没有把输入框的文本值赋值给全局
number变量:你在AlertDialog的OK按钮点击事件里,直接调用了userInputForTrivia(),但始终没有把_textFieldController里的输入内容转为int类型赋值给你定义的int number变量,导致API请求的路径一直是/null/trivia,自然拿不到对应数字的趣闻。 initState中提前调用userInputForTrivia()无意义:页面初始化时用户还没有输入数字,此时调用接口只会请求到无效结果。- 未处理输入为空的边界情况,同时
fact初始值为空,直接调用toString()会显示null文本。 - 点击OK后未关闭弹窗,体验不友好。
修复代码示例
1. 调整OK按钮的点击事件
ElevatedButton( onPressed: () { // 新增:把输入框内容转为int赋值给number String inputText = _textFieldController.text.trim(); if (inputText.isNotEmpty) { number = int.parse(inputText); // 调用接口前先清空输入框,关闭弹窗 _textFieldController.clear(); Navigator.of(context).pop(); userInputForTrivia(); } }, child: const Text("OK"), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.purple[400]!), ), )
2. 调整数据拉取函数和初始值
// 给fact设置初始默认值 String fact = "请输入数字获取对应趣闻"; int? number; // 改成可空类型避免空警告 void userInputForTrivia() async { // 新增校验:number为空直接返回 if (number == null) return; http.Response response; response = await http.get(Uri.http('numbersapi.com', '$number/trivia')); if (response.statusCode == 200) { setState(() { fact = response.body; }); } } @override void initState() { // 删除初始化时的接口调用 super.initState(); }
3. 调整展示文本组件(可选优化)
Text( fact, style: TextStyle( fontSize: 20.0, color: Colors.purple[400], ), )
内容的提问来源于stack exchange,提问作者NightyKnight
相关产品推荐
相关产品推荐

