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

Flutter/Dart中如何在子组件及State类中访问父组件传递的变量

解决方案

1. State类获取传入参数的方法

StatefulWidget对应的State子类中,可直接通过内置的widget属性访问父组件定义的参数,你要获取传入的text变量,直接使用widget.text即可。你注释的Text组件部分可以直接修改为:

Text(
  widget.text, // 替换原来的硬编码文本和注释的text
  style: TextStyle(fontSize: 24),
)

2. 生成分词列表并渲染实现

你可以对widget.text做分词处理后生成列表,以下是按空格分词后用ListView渲染的完整示例代码:

class SecondRoute extends StatefulWidget {
  final String text; // 不可变组件参数建议加final修饰
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();
}

class _SecondRouteState extends State<SecondRoute> {
  @override
  Widget build(BuildContext context) {
    // 分词逻辑,可根据需求替换为更复杂的中文分词逻辑
    List<String> wordList = widget.text.split(' ');
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: ListView.builder(
        itemCount: wordList.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(wordList[index], style: const TextStyle(fontSize: 24)),
          );
        },
      ),
    );
  }
}

注意:如果是中文分词需求,你可以引入第三方分词库替换当前的简单split逻辑即可。

3. StatelessWidget实现方案

如果你当前页面不需要维护内部可变状态(仅需要展示传入参数对应的内容,没有用户交互修改数据的需求),完全可以用StatelessWidget实现,代码更简洁:

class SecondRoute extends StatelessWidget {
  final String text;
  const SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<String> wordList = text.split(' ');
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: ListView.builder(
        itemCount: wordList.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(wordList[index], style: const TextStyle(fontSize: 24)),
          );
        },
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者masfiq reza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:06:00