您的问题首先很简单,您违反了 DRY 概念(不要重复自己,https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)。
一旦您开始复制粘贴代码,请花点时间考虑一下您的代码以及如何将其抽象为可重用的组件。
我认为您缺少的另一个大问题是变量命名。这是编写代码的一个非常非常重要的部分。可能看起来微不足道,但很难理解名为 cardOne1 和 cardTwo2 的变量的实际含义。该变量的目的是什么?它有什么作用?
话虽如此,我知道您的应用与汽车销售有关,但除此之外,我不确定我在看什么。在那里,我将很难为这段代码找到一个好的变量,但这里有一个例子。
所以让我们将卡片中的内容分解为一个可重复使用的小部件,我们还可以创建一个数据类(或模型)来存储我们然后提供给小部件的数据。
//car_details.dart
class CarDetails {
String title;
String diffNumber;
String diffPercent;
Color colorIndicator;
CarDetails({
this.title,
this.diffNumber,
this.diffPercent,
this.colorIndicator,
});
}
//car_card_details.dart
class CarCardDetails extends StatelessWidget {
final double padding;
final CarDetails carDetails;
CarCardDetails({
this.carDetails,
this.padding = 15,
});
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
carDetails.colorIndicator != null
? Container(
color: carDetails.colorIndicator,
height: 60,
width: 2,
)
: Container(),
Padding(
padding: EdgeInsets.all(padding),
child: Column(children: [
Text(carDetails.title),
Text(carDetails.diffNumber),
Text(carDetails.diffPercent),
VerticalDivider(color: Colors.blue),
])),
],
);
}
}
为了使用这个组件,我们制作了一个 CarCard 小部件,它带有一个标题和一个 CarDetails 列表,如下所示:
// car_card.dart
class CarCard extends StatelessWidget {
final String title;
final List<CarDetails> carDetails;
CarCard({this.title, this.carDetails});
@override
Widget build(BuildContext context) {
List<Widget> detailRow = List();
if (carDetails != null) {
carDetails.forEach((element) {
detailRow.add(CarCardDetails(
top: element.title,
middle: element.diffNumber,
bottom: element.diffPercent,
lineColor: element.colorIndicator,
));
});
}
return Container(
//height: 150, //I would not hardcode the height, let the childrent expand the widget instead
child: SingleChildScrollView(
child: Card(
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
child: InkWell(
child: Column(children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(children: [
Text(
title,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
Spacer(),
Icon(Icons.favorite)
]),
),
Divider(color: Colors.black),
Row(children: detailRow),
]),
),
),
),
);
}
}
现在我们可以将它们放入 CarDetails 列表中,而不是保存您在应用程序中拥有的所有变量,其中每个元素都包含字符串。
// some other widget
...
List<CarDetails> carDetails = [
CarDetails(
title: "2 hrs ago",
diffNumber: "+/ TRACK",
diffPercent: "% to DBJ",
),
CarDetails(
title: "CHEVEROLET",
diffNumber: "-2706",
diffPercent: "42.2%",
colorIndicator: Colors.red,
),
CarDetails(
title: "BUICK",
diffNumber: "+300",
diffPercent: "50%",
colorIndicator: Colors.green,
),
CarDetails(
title: "GMC",
diffNumber: "-712",
diffPercent: "52.1%",
colorIndicator: Colors.black26,
),
];
@override
Widget build(BuildContext context) {
return CarCard(
title: "US Daily Retail Delieveries by Brand",
carDetails: carDetails,
);
}
...
这当然可以用卡片组等进一步抽象。但我希望你明白。
这是您如何做到这一点的一个示例,也就是说我不知道您打算使用什么数据以及您想如何构建它。因此,将其视为一个起点并从那里开始。 :)