代码优化:合并重复代码,提高效率
可以将相似的代码合并,重复利用。例如:
//定义一个方法,传入时间段和容器的下标,返回一个Container
Container getContainer(String time, int index, String msg) {
return 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 + '\n' +
eventcahe[index]['qssj']
.toString()
.split(' ')[0]
.substring(0, 5) +
' - ' +
eventcahe[index]['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[index]['kcmc'] + '\n' + eventcahe[index]['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,
),
),
),
);
}
//调用方法
for (var i = 0; i < eventcahe.length; i++) {
String msg = '课程名称:' +
eventcahe[i]['kcmc'] +
'\n' +
'教室:' +
eventcahe[i]['jxcdmc'] +
'\n' +
'第' +
eventcahe[i]['zc'].toString() +
'周课程' +
'\n' +
'教师:' +
eventcahe[i]['teaxms'] +
'\n' +
'教学班级:' +
eventcahe[i]['jxbmc'] +
'\n' +
'额外备注:' +
eventcahe[i]['sknrjj'];
//判断课程时间段,替换对应的Container
if (eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 2) == '08') {
dailycourse[1] = getContainer('1,2节', i, msg);
} else if (eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 2) ==
'09') {
dailycourse[2] = getContainer('3,4节', i, msg);
} else if (eventcahe[i]['jssj'].toString().split(' ')[0].substring(0, 2) ==
'11') {
dailycourse[2] = getContainer('3,4节', i, msg);
} else if (eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 2) ==
'13') {
dailycourse[4] = getContainer('5,6节', i, msg);
}
}
原文地址: http://www.cveoy.top/t/topic/ojFA 著作权归作者所有。请勿转载和采集!