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

如何从一个StatelessWidget调用另一个时传递参数数据?

问题错误点

  • 入参未正确接收赋值:StatelessTwo 构造函数中声明了param入参,但没有将其赋值给类成员变量,反而将成员变量param固定初始化为空Map,无法获取外部传入的值
  • 类型不匹配:外部传入的param是Color类型,但StatelessTwo中将param声明为Map类型,还尝试读取param['color']字段,类型完全不对应,无法正常获取颜色值
  • 重复使用同一Key:你给所有StatelessTwo实例都传入了StatelessOne的Key,同一Key不能被多个Widget同时使用,会导致Widget树匹配异常,无特殊需求时无需手动传入Key

修正后代码

void main(List<String> args) => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Stateless/Clean Code'),
        ),
        body: const StatelessOne(),
      ),
    );
  }
}

class StatelessOne extends StatelessWidget {
  const StatelessOne({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const Text(
              'Widget color can be customised without \nhaving to retype the entire code'),
          const StatelessTwo(param: Colors.green),
          const StatelessTwo(param: Colors.pink),
          const StatelessTwo(param: Colors.blue),
          const StatelessTwo(param: Colors.orange),
        ],
      ),
    );
  }
}

class StatelessTwo extends StatelessWidget {
  const StatelessTwo({Key? key, required this.param}) : super(key: key);
  // 直接声明为Color类型匹配传入参数
  final Color param;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 120,
      width: 250,
      // 直接使用param变量即可
      color: param,
      child: Center(child: Text('Your Repetitive Widget $key')),
    );
  }
}

如果你确实需要用Map传递多个参数,仅需调整调用处传参格式即可:

StatelessTwo(param: {'color': Colors.green})

同时将StatelessTwo的param成员变量改为Map类型,构造函数中完成赋值即可,其余代码无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:24:00