如何将数据传递给从另一个无状态小部件调用的无状态小部件?

How to pass data to stateless widget calling from another stateless widget?

我正在尝试将一些颜色信息从一个小部件传递到另一个小部件,但我无法在目标小部件中获取该颜色。我想构建一个包含一些 UI 代码的单个 class 并在我的主小部件中调用此 class 这样我就不必再次重复代码,但是我无法传递数据, 这是我正在处理的代码:我做错了什么?

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'),
          StatelessTwo(key: key, param: Colors.green),
          StatelessTwo(key: key, param: Colors.pink),
          StatelessTwo(key: key, param: Colors.blue),
          StatelessTwo(key: key, param: Colors.orange),
        ],
      ),
    );
  }
}

class StatelessTwo extends StatelessWidget {
  StatelessTwo({Key? key, @required param}) : super(key: key);

  final Map param = {};

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 120,
      width: 250,
      color: param['color'],
      child: Center(child: Text('Your Repetitive Widget $key')),
    );
  }
}

简单的方法就是


class StatelessTwo extends StatelessWidget {
  final Color color;

  const StatelessTwo({
    Key? key,
    required this.color,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 120,
      width: 250,
      color: color,
      child: Center(
          child: Text('Your Repetitive Widget ${key ?? "no key found"}')),
    );
  }
}
 -----
  color: color, //use

传色 StatelessTwo(key: key, color: Colors.green), 并且您似乎传递了相同的 key,避免 Ui-逻辑没有必要。很可能,您不需要通过 key,如果您仍想通过使用 UinqueKey()