【Flutter】日历打卡

在这里插入图片描述

  • 获取当前月份天数
  // 获取当前月份天数
  int _getCurrentMonthDays({int year, int month}) {
    if (month == 2) {
      if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
        return 29;
      } else {
        return 28;
      }
    } else if (month == 1 ||
        month == 3 ||
        month == 5 ||
        month == 7 ||
        month == 8 ||
        month == 10 ||
        month == 12) {
      return 31;
    } else {
      return 30;
    }
  }
  • 获取占位天数
  // 获取占位天数
  int _getPlaceholderDays({int year, int month}) {
    return DateTime(year, month).weekday % 7;
  }
  • 获取行数
  // 获取行数
  int _getRowsForMonthYear({int year, int month}) {
    var _currentMonthDays = _getCurrentMonthDays(year: year, month: month);
    var _placeholderDays = _getPlaceholderDays(year: year, month: month);
    int rows = (_currentMonthDays + _placeholderDays) ~/ 7;
    int remainder = (_currentMonthDays + _placeholderDays) % 7;
    if (remainder > 0) {
      rows = rows + 1;
    }
    return rows;
  }
完整代码如下:

import 'package:flutter/material.dart';

class MyClockInAllInfoPage extends StatefulWidget {
  final Map<String, dynamic> arguments;
  MyClockInAllInfoPage({Key key, this.arguments}) : super(key: key);

  @override
  _MyClockInAllInfoPageState createState() => _MyClockInAllInfoPageState();
}

class _MyClockInAllInfoPageState extends State<MyClockInAllInfoPage> {
  GlobalKey<ClockInCalendarState> clockInCalendarKey = GlobalKey();
  var _title = "";

  int _year = DateTime.now().year;
  int _month = DateTime.now().month;

  @override
  void initState() {
    super.initState();
    _title = widget.arguments["title"];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            _title,
            style: Theme.of(context)
                .textTheme
                .headline2
                .copyWith(fontSize: 18, color: AppColors.app_back27),
          ),
        ),
        body: Container(
          child: Column(
            children: [
              ClockInCalendar(
                key: clockInCalendarKey,
                year: _year,
                month: _month,
                lastMonth: _lastMonth,
                nextMonth: _nextMonth,
              )
            ],
          ),
        ));
  }

  // 上月
  _lastMonth() {
    if (_month == 1) {
      _year = _year - 1;
      _month = 12;
    } else {
      _month = _month - 1;
    }
    clockInCalendarKey.currentState.updateCurrentWidget(_year, _month);
  }

  // 下月
  _nextMonth() {
    if (_month == 12) {
      _year = _year + 1;
      _month = 1;
    } else {
      _month = _month + 1;
    }
    clockInCalendarKey.currentState.updateCurrentWidget(_year, _month);
  }
}


/*
 * @Descripttion: 
 * @version: 
 * @Author: lichuang
 * @Date: 2020-11-16 17:17:45
 * @LastEditors: lichuang
 * @LastEditTime: 2020-11-16 17:54:02
 */
import 'package:flutter/material.dart';

class ClockInCalendar extends StatefulWidget {
  final int year;
  final int month;
  final Function lastMonth;
  final Function nextMonth;
  ClockInCalendar(
      {Key key,
      @required this.year,
      @required this.month,
      this.lastMonth,
      this.nextMonth})
      : super(key: key);

  @override
  ClockInCalendarState createState() => ClockInCalendarState();
}

class ClockInCalendarState extends State<ClockInCalendar> {
  List<CalendarModel> _datas = [];

  var _year = 2020;
  var _month = 11;

  @override
  void initState() {
    super.initState();
    _year = widget.year;
    _month = widget.month;

    _setDatas(year: _year, month: _month);
  }

  // 更新数据显示
  updateCurrentWidget(int year, int month) {
    _year = year;
    _month = month;
    _datas.clear();
    _setDatas(year: _year, month: _month);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          _yearHeader(),
          _weekHeader(),
          _everyDay(),
        ],
      ),
    );
  }

  Widget _yearHeader() {
    return Container(
      height: 40,
      margin: EdgeInsets.only(top: 10, bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(onPressed: widget.lastMonth, child: Text("上月")),
          Text("$_year 年$_month 月"),
          FlatButton(onPressed: widget.nextMonth, child: Text("下月")),
        ],
      ),
    );
  }

  Widget _weekHeader() {
    var array = ["日", "一", "二", "三", "四", "五", "六"];
    return Container(
      height: 50,
      child: GridView.builder(
        itemCount: array.length,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //横轴元素个数
            crossAxisCount: 7,
            //纵轴间距
            // mainAxisSpacing: ScreenUtil().setHeight(10),
            // 横轴间距
            // crossAxisSpacing: ScreenUtil().setWidth(15),
            //子组件宽高长度比例
            childAspectRatio: 2),
        itemBuilder: (context, index) {
          return Container(
              alignment: Alignment.center,
              child: Text(
                array[index],
                style: Theme.of(context)
                    .textTheme
                    .headline2
                    .copyWith(fontSize: 16),
              ));
        },
      ),
    );
  }

  Widget _everyDay() {
    return Container(
      child: GridView.builder(
        itemCount: _getRowsForMonthYear(year: _year, month: _month) * 7,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //横轴元素个数
            crossAxisCount: 7,
            //纵轴间距
            // mainAxisSpacing: ScreenUtil().setHeight(10),
            // 横轴间距
            // crossAxisSpacing: ScreenUtil().setWidth(15),
            //子组件宽高长度比例
            childAspectRatio: 0.8),
        itemBuilder: (context, index) {
          return Container(
            child: Column(
              children: [
                Text(
                  _datas[index].month.toString() +
                      "-" +
                      _datas[index].day.toString(),
                  style: _datas[index].month == _month
                      ? Theme.of(context)
                          .textTheme
                          .headline6
                          .copyWith(fontSize: 14)
                      : Theme.of(context)
                          .textTheme
                          .headline4
                          .copyWith(fontSize: 14),
                ),
                Text(
                  _datas[index].month == _month ? "09:00" : "",
                  style: Theme.of(context)
                      .textTheme
                      .headline4
                      .copyWith(fontSize: 10),
                ),
                Text(
                  _datas[index].month == _month ? "18:00" : "",
                  style: Theme.of(context)
                      .textTheme
                      .headline4
                      .copyWith(fontSize: 10),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // 获取占位天数
  int _getPlaceholderDays({int year, int month}) {
    return DateTime(year, month).weekday % 7;
  }

  // 获取行数
  int _getRowsForMonthYear({int year, int month}) {
    var _currentMonthDays = _getCurrentMonthDays(year: year, month: month);
    var _placeholderDays = _getPlaceholderDays(year: year, month: month);
    int rows = (_currentMonthDays + _placeholderDays) ~/ 7;
    int remainder = (_currentMonthDays + _placeholderDays) % 7;
    if (remainder > 0) {
      rows = rows + 1;
    }
    return rows;
  }

  // 获取当前月份天数
  int _getCurrentMonthDays({int year, int month}) {
    if (month == 2) {
      if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
        return 29;
      } else {
        return 28;
      }
    } else if (month == 1 ||
        month == 3 ||
        month == 5 ||
        month == 7 ||
        month == 8 ||
        month == 10 ||
        month == 12) {
      return 31;
    } else {
      return 30;
    }
  }

  /// 获取展示信息
  _setDatas({int year, int month}) {
    /// 上个月占位
    var lastYear = year;
    var lastMonth = month - 1;
    if (month == 1) {
      lastYear = year - 1;
      lastMonth = 12;
    }

    var placeholderDays = _getPlaceholderDays(year: year, month: month);
    print("placeholderDays == $placeholderDays");
    var lastMonthDays = _getCurrentMonthDays(year: lastYear, month: lastMonth);
    print("lastMonthDays == $lastMonthDays");
    var firstDay = lastMonthDays - placeholderDays;
    for (var i = 0; i < placeholderDays; i++) {
      _datas.add(CalendarModel(
          year: lastYear, month: lastMonth, day: firstDay + i + 1));
    }

    /// 本月显示
    var currentMonthDays = _getCurrentMonthDays(year: year, month: month);
    print("currentMonthDays == $currentMonthDays");
    for (var i = 0; i < currentMonthDays; i++) {
      _datas.add(CalendarModel(year: year, month: month, day: i + 1));
    }

    /// 下个月占位
    var nextYear = year;
    var nextMonth = month + 1;
    if (month == 12) {
      nextYear = year + 1;
      nextMonth = 1;
    }
    var nextPlaceholderDays =
        _getPlaceholderDays(year: nextYear, month: nextMonth);
    for (var i = 0; i < 7 - nextPlaceholderDays; i++) {
      _datas.add(CalendarModel(year: nextYear, month: nextMonth, day: i + 1));
    }
  }
}

class CalendarModel {
  int year;
  int month;
  int day;
  String am;
  String pm;
  CalendarModel.fromJson(Map<String, dynamic> json)
      : year = json['year'],
        month = json['month'],
        day = json['day'],
        am = json['am'],
        pm = json['pm'];
  CalendarModel({this.year, this.month, this.day, this.am, this.pm});
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值