1

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

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')),
    );
  }
}

4

1 回答 1

1

简单的方法是


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()

于 2021-10-31T20:07:44.047 回答