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

Flutter Navigator传参问题:无法将当前页面数据传递到有状态新页面

问题解决步骤

你的错误根源是StatefulWidget的构造函数没有将title参数保存为类成员变量,导致State类无法访问传递过来的数据。以下是完整的修正方案:

1. 修正SongScreen的构造函数

将title参数定义为类的final成员变量,这样State类就能通过widget.title访问它:

class SongScreen extends StatefulWidget {
  // 定义final成员变量,接收传递的title
  final String title;
  
  // 构造函数初始化title
  const SongScreen({super.key, required this.title});

  @override
  State<SongScreen> createState() => _SongScreenState();
}

2. 在State类中添加TextEditingController

要在TextField中显示传递过来的标题,需要使用TextEditingController,并在初始化时传入widget.title:

class _SongScreenState extends State<SongScreen> {
  late TextEditingController _titleController;

  @override
  void initState() {
    super.initState();
    // 初始化控制器,将传递的title设置为初始值
    _titleController = TextEditingController(text: widget.title);
  }

  @override
  void dispose() {
    // 页面销毁时释放控制器,避免内存泄漏
    _titleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.purple, Colors.blue],
            begin: Alignment.bottomLeft,
            end: Alignment.topRight,
          ),
        ),
        child: Center(
          // 替换原来的Text为TextField,使用控制器显示数据
          child: TextField(
            controller: _titleController,
            decoration: const InputDecoration(
              border: OutlineInputBorder(),
              labelText: '歌曲标题',
            ),
            // 可选:设置为只读,防止用户修改
            // readOnly: true,
          ),
        ),
      ),
    );
  }
}

3. 验证跳转逻辑

你的原跳转代码是正确的,不需要修改:

onTap: () {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => SongScreen(title: item.data![index].title),
    ),
  );
},

这样修改后,点击按钮跳转时,传递的歌曲标题会自动显示在SongScreen的TextField中。

内容的提问来源于stack exchange,提问作者HARSH J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:40:22