下面的 Dart 代码可以进行精简,将重复的部分封装成一个函数,减少冗余代码。

Widget buildCourseTile(String title, String time, String content, Function onTap) {
  return TimelineTile(
    oppositeContents: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Card(
        child: Container(
          width: widthx,
          padding: EdgeInsets.all(8.0),
          child: Text(
            title + '\n' + time,
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    ),
    contents: GestureDetector(
      onTap: onTap,
      child: Card(
        color: Global.home_currentcolor,
        child: Container(
          width: widthx,
          padding: EdgeInsets.all(8.0),
          child: Text(
            content,
            style: TextStyle(color: Colors.white),
          ),
        ),
      ),
    ),
    node: TimelineNode(
      indicator: DotIndicator(
        color: Global.home_currentcolor,
      ),
    ),
  );
}

// 使用 buildCourseTile 函数
if (eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 2) == '08') {
  dailycourse[1] = Container(
    child: buildCourseTile(
      '1,2节',
      eventcahe[i]['qssj'].toString().split(' ')[0].substring(0, 5) + '\n' + eventcahe[i]['jssj'].toString().split(' ')[0].substring(0, 5),
      eventcahe[i]['kcmc'] + '\n' + eventcahe[i]['jxcdmc'] + '\n' + '第' + eventcahe[i]['zc'].toString() + '周课程' + '\n' + eventcahe[i]['teaxms'] + '\n' + eventcahe[i]['jxbmc'] + '\n' + eventcahe[i]['sknrjj'],
      () => Dialogs.bottomMaterialDialog(
        color: Colors.white,
        msg: msg,
        title: '详细信息',
        lottieBuilder: Lottie.asset(
          'assets/course.json',
          fit: BoxFit.contain,
        ),
        context: context,
      )
    )
  );
}

这样,就可以用 buildCourseTile 函数来构建课程时间安排的 TimelineTile,减少代码重复,提高代码可读性和可维护性。

注意:

  • 函数中的 widthxGlobal.home_currentcolor 需要在函数外部定义。
  • 函数中的 onTap 参数应该是一个函数,它会在用户点击课程信息时被调用。
  • msg 变量需要在函数外部定义,用于存储课程的详细信息。
  • Dialogs.bottomMaterialDialog 函数需要在代码中引入。
Dart 代码精简优化:使用函数封装重复代码

原文地址: http://www.cveoy.top/t/topic/ojE5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录