代码优化:简化课程时间段判断逻辑
以下是优化后的代码:
for (var i = 0; i < eventcahe.length; i++) {
String msg = '课程名称:' +
eventcahe[i]['kcmc'] +
'
' +
'教室:' +
eventcahe[i]['jxcdmc'] +
'
' +
'第' +
eventcahe[i]['zc'].toString() +
'周课程' +
'
' +
'教师:' +
eventcahe[i]['teaxms'] +
'
' +
'教学班级:' +
eventcahe[i]['jxbmc'] +
'
' +
'额外备注:' +
eventcahe[i]['sknrjj'];
var qssj = eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 2);
var jssj = eventcahe[i]['jssj'].toString().split(' ')[0].substring(0, 2);
var index = -1;
switch (qssj) {
case '08':
index = 1;
break;
case '09':
index = 2;
break;
}
if (jssj == '11') {
index = 2;
}
if (index != -1) {
dailycourse[index] = Container(
child: TimelineTile(
oppositeContents: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
width: widthx,
padding: EdgeInsets.all(8.0),
child: Text(
'${index + 1},${index + 2}节
' +
eventcahe[i]['qssj']
.toString()
.split(' ')[0]
.substring(0, 5) +
' - ' +
eventcahe[i]['jssj']
.toString()
.split(' ')[0]
.substring(0, 5),
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
),
),
),
),
contents: GestureDetector(
onTap: (() => Dialogs.bottomMaterialDialog(
color: Colors.white,
msg: msg,
title: '详细信息',
lottieBuilder: Lottie.asset(
'assets/course.json',
fit: BoxFit.contain,
),
context: context,
)),
child: Card(
color: Global.home_currentcolor,
child: Container(
width: widthx,
padding: EdgeInsets.all(8.0),
child: Text(
eventcahe[i]['kcmc'] + '
' + eventcahe[i]['jxcdmc'],
style: TextStyle(color: Colors.white),
),
),
),
),
node: TimelineNode(
indicator: DotIndicator(
color: Global.home_currentcolor,
),
startConnector: SolidLineConnector(
color: Global.home_currentcolor,
),
endConnector: SolidLineConnector(
color: Global.home_currentcolor,
),
),
),
);
}
}
优化要点:
- 使用 switch 语句: 将原本多个 if 语句判断替换为 switch 语句,使代码更简洁易读。
- 简化条件判断: 使用
index变量来记录课程时间段,并使用index != -1来判断是否需要更新 UI,避免了冗余的 if 语句。 - 合并重复代码: 将重复的代码块提取出来,减少代码重复,提高可维护性。
通过以上优化,代码逻辑更加清晰,可读性和可维护性也得到了提升。
注意:
- 确保
dailycourse数组的长度足够容纳所有课程时间段。 - 确保
eventcahe数组中包含课程时间段的信息。 - 确保
Dialogs.bottomMaterialDialog方法已经定义并能正常使用。 - 确保
Global.home_currentcolor变量已经定义并能正常使用。
原文地址: http://www.cveoy.top/t/topic/ojFv 著作权归作者所有。请勿转载和采集!