我正在尝试将一些颜色信息从一个小部件传递到另一个小部件,但我无法在目标小部件中获得该颜色。我想构建一个包含一些 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')),
);
}
}