Dart 代码优化:使用函数精简课程时间段判断
可以将重复的代码块提取出来,使用一个函数来判断课程时间段并替换对应的 Container。例如:
void replaceContainer(int index, String time, Map<String, dynamic> event) {
if (event['qssj'].toString().split(' ')[0].substring(0, 2) == time) {
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(
'$time 节
' +
event['qssj'].toString().split(' ')[0].substring(0, 5) +
' - ' +
event['jssj'].toString().split(' ')[0].substring(0, 5),
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
),
),
),
),
contents: GestureDetector(
onTap: (() => Dialogs.bottomMaterialDialog(
color: Colors.white,
msg: '课程名称:' +
event['kcmc'] +
'
' +
'教室:' +
event['jxcdmc'] +
'
' +
'第' +
event['zc'].toString() +
'周课程' +
'
' +
'教师:' +
event['teaxms'] +
'
' +
'教学班级:' +
event['jxbmc'] +
'
' +
'额外备注:' +
event['sknrjj'],
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(
event['kcmc'] + '
' + event['jxcdmc'],
style: TextStyle(color: Colors.white),
),
),
),
),
node: TimelineNode(
indicator: DotIndicator(
color: Global.home_currentcolor,
),
endConnector: SolidLineConnector(
color: Global.home_currentcolor,
),
),
),
);
}
}
// 使用函数替换代码
for (var i = 0; i < eventcahe.length; i++) {
replaceContainer(1, '1,2', eventcahe[i]);
replaceContainer(2, '3,4', eventcahe[i]);
// ... 其他时间段判断
}
这样可以使代码更加简洁易懂,并提高代码的可维护性。如果以后需要添加新的时间段判断,只需要修改函数内部逻辑,而不需要修改原代码。
优点:
- 代码更加简洁易懂
- 提高代码可维护性
- 更易于添加新的时间段判断
- 减少代码重复
建议:
- 可以将函数命名为更具描述性的名称,例如
updateCourseContainer - 可以根据实际需求调整函数参数
- 可以使用更简洁的方式获取课程时间段,例如使用
DateTime对象
希望以上信息能够帮助您优化代码。
原文地址: http://www.cveoy.top/t/topic/ojFj 著作权归作者所有。请勿转载和采集!