You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中modal bottom sheet内TextField文本获取为空问题咨询

问题根本原因

你当前使用的AddTaskScreen是无状态组件(StatelessWidget),这类组件本身不支持持久化存储可变的内部状态,你声明的newTaskTitle变量在组件触发任何重绘行为时都会被重置为初始的空值,因此回调拿到的结果始终为空。

方案1:将组件改为有状态组件(StatefulWidget,官方推荐做法)

将可变状态放到State类中管理,修改后的AddTaskScreen代码如下:

import 'package:flutter/material.dart';

class AddTaskScreen extends StatefulWidget {
  final Function(String) addTaskCallback;

  const AddTaskScreen(this.addTaskCallback, {super.key});

  @override
  State<AddTaskScreen> createState() => _AddTaskScreenState();
}

class _AddTaskScreenState extends State<AddTaskScreen> {
  String newTaskTitle = "";

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff757575),
      child: Container(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              "Add Task",
              style: TextStyle(
                color: Colors.blueAccent,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            TextField(
              autofocus: true,
              onChanged: (newText) {
                // 状态变化时调用setState更新存储的值
                setState(() {
                  newTaskTitle = newText;
                });
              },
            ),
            const SizedBox(
              height: 30,
            ),
            ElevatedButton(
              // 兼容新版Flutter,废弃的RaisedButton改用ElevatedButton
              onPressed: () {
                // 可选:增加空值判断,避免提交空内容
                if (newTaskTitle.trim().isNotEmpty) {
                  widget.addTaskCallback(newTaskTitle);
                  // 提交后自动关闭底部弹窗
                  Navigator.pop(context);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blueAccent,
              ),
              child: const Text(
                "Add",
                style: TextStyle(color: Colors.white),
              ),
            )
          ],
        ),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(20),
              topLeft: Radius.circular(20)
          ),
        ),
      ),
    );
  }
}

方案2:使用TextEditingController获取输入值(无需自行维护状态变量)

如果你不想修改组件类型,可以直接用TextField自带的控制器获取输入内容,不需要监听onChanged存值:

import 'package:flutter/material.dart';

class AddTaskScreen extends StatelessWidget {
  final Function(String) addTaskCallback;
  // 声明文本控制器
  final TextEditingController _controller = TextEditingController();

  AddTaskScreen(this.addTaskCallback, {super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff757575),
      child: Container(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              "Add Task",
              style: TextStyle(
                color: Colors.blueAccent,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            TextField(
              autofocus: true,
              // 绑定控制器
              controller: _controller,
            ),
            const SizedBox(
              height: 30,
            ),
            ElevatedButton(
              onPressed: () {
                final String newTaskTitle = _controller.text.trim();
                if (newTaskTitle.isNotEmpty) {
                  addTaskCallback(newTaskTitle);
                  Navigator.pop(context);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blueAccent,
              ),
              child: const Text(
                "Add",
                style: TextStyle(color: Colors.white),
              ),
            )
          ],
        ),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(20),
              topLeft: Radius.circular(20)
          ),
        ),
      ),
    );
  }
}

额外注意

你原来的代码里回调函数只声明了Function类型,没有指定参数类型,建议修改为Function(String)明确参数类型,避免类型不匹配导致的空值问题。

内容的提问来源于stack exchange,提问作者Aditya Dixit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:06:04