Flutter -自定义日历组件

首先看下效果


2019-01-11 18-28-03.2019-01-11 18_28_22.gif

颜色文件和屏幕适配的文件 可以自己给定

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_xiaoe/utils/ScreenUtil.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xiaoe/utils/TimeUtil.dart';
import 'package:flutter_xiaoe/widgets/common/calendar/DayGridView.dart';
import 'package:flutter_xiaoe/config/Colors.dart';

class Calendar extends StatefulWidget {
  DateTime initTime;
  DateTime firstTime;
  DateTime endTime;
  ValueChanged onChange;

  Calendar({
    Key key,
    this.initTime,
    this.firstTime,
    this.endTime,
    this.onChange,
  }) : super(key: key);

  @override
  State<Calendar> createState() => _CalendarState();
}

class _CalendarState extends State<Calendar> {
  PageController pageController;
  DateTime selectDate;
  int initPage = 0;
  int totalPage = 0;

  @override
  void initState() {
    super.initState();
    print(widget.firstTime.month);
    selectDate = widget.initTime;

    /// 总共的月份数目
    totalPage = (widget.endTime.year - widget.firstTime.year == 0
        ? widget.endTime.month
        : ((widget.endTime.year - widget.firstTime.year) * 12 +
            widget.endTime.month -
            widget.firstTime.month +
            1));

    /// 当前月份处于
    initPage = (widget.initTime.year - widget.firstTime.year == 0
        ? widget.initTime.month
        : ((widget.initTime.year - widget.firstTime.year) * 12 +
            widget.initTime.month -
            widget.firstTime.month +
            1));
    print(totalPage);
    print(initPage);
    pageController = PageController(
      initialPage: totalPage,
    );
  }

  onChange(time) {
    if (selectDate != time) {
      setState(() {
        selectDate = time;
        widget.onChange(time);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: TimeUtil.getDayHeaders(MaterialLocalizations.of(context)),
      ),
      Container(
        color: AppColors.WHITE,
        height: ScreenUtil.px2pt(600),
        child: PageView.builder(
          itemBuilder: (BuildContext context, int index) {
            return DayGridView(
              initDate: DateTime(widget.initTime.year, widget.initTime.month,
                  widget.initTime.day),
              selectDate:
                  DateTime(selectDate.year, selectDate.month, selectDate.day),
              year: widget.firstTime.year +
                  ((widget.firstTime.month + index - 1) / 12).floor(),
              month: (widget.firstTime.month + index) % 12 == 0
                  ? 12
                  : (widget.firstTime.month + index) % 12,
              onChange: onChange,
            );
          },
          itemCount: totalPage,
          controller: pageController,
        ),
      ),
    ]);
  }
}
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_xiaoe/utils/ScreenUtil.dart';
import 'package:flutter_xiaoe/utils/NetUtil.dart';
import 'package:flutter_xiaoe/config/Api.dart';
import 'package:flutter_xiaoe/config/Colors.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:flutter_xiaoe/utils/TimeUtil.dart';

class DayGridView extends StatefulWidget {
  DateTime initDate;
  DateTime selectDate;
  int year;
  int month;
  ValueChanged onChange;

  DayGridView({
    Key key,
    @required this.initDate,
    @required this.selectDate,
    @required this.year,
    @required this.month,
    this.onChange,
  });

  @override
  State<DayGridView> createState() => _DayGridViewState();
}

class _DayGridViewState extends State<DayGridView> {
  @override
  void initState() {
    super.initState();
  }

  List<Widget> dayItems() {
    List days = TimeUtil.getDay(
        widget.year, widget.month, MaterialLocalizations.of(context));
    List dayWidgets = days.map((value) {
      if (value is int) {
        return Container();
      }
      if (value == widget.selectDate) {
        return GestureDetector(
          onTap: () {
            widget.onChange(widget.selectDate);
          },
          child: Container(
            color: AppColors.WHITE,
            alignment: Alignment.center,
            child: Container(
              width: ScreenUtil.px2pt(60),
              height: ScreenUtil.px2pt(60),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: AppColors.BLUE_TEXT,
                borderRadius: BorderRadius.all(Radius.circular(100)),
              ),
              child: Text(
                value.day.toString(),
                style: TextStyle(color: AppColors.WHITE),
              ),
            ),
          ),
        );
      } else {
        if (value == widget.initDate) {
          return GestureDetector(
            onTap: () {
              widget.onChange(widget.initDate);
            },
            child: Container(
                color: AppColors.WHITE,
                alignment: Alignment.center,
                child: Text(
                  value.day.toString(),
                  style: TextStyle(color: AppColors.BLUE_TEXT),
                )),
          );
        } else {
          if (value.isAfter(widget.initDate)) {
            /// 在今天之后的时间无法点击
            return GestureDetector(
              child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    value.day.toString(),
                    style: TextStyle(color: AppColors.BLACK3),
                  )),
            );
          } else {
            /// 在今天之前的时间可以点击
            return GestureDetector(
              onTap: () {
                widget.onChange(value);
              },
              child: Container(
                  color: AppColors.WHITE,
                  alignment: Alignment.center,
                  child: Container(
                    child: Text(
                      value.day.toString(),
                      style: TextStyle(color: AppColors.BLACK1),
                    ),
                  )),
            );
          }
        }
      }
    }).toList();
    return dayWidgets;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> list = dayItems();
    return Container(
      height: ScreenUtil.px2pt(600),
      child: GridView.custom(
          gridDelegate:
          _DayPickerGridDelegate(mainAxisNumber: list.length > 35 ? 6 : 5),
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.all(0),
          childrenDelegate:
          SliverChildListDelegate(list, addRepaintBoundaries: false)),
    );
  }
}

/// 自定义GridView
class _DayPickerGridDelegate extends SliverGridDelegate {
  final int mainAxisNumber;

  const _DayPickerGridDelegate({
    this.mainAxisNumber,
  });

  @override
  SliverGridLayout getLayout(SliverConstraints constraints) {
    const int columnCount = DateTime.daysPerWeek;
    final double tileWidth = constraints.crossAxisExtent / columnCount;
    final double tileHeight = ScreenUtil.px2pt(600) / mainAxisNumber;
    return SliverGridRegularTileLayout(
      crossAxisCount: columnCount,
      mainAxisStride: tileHeight,
      crossAxisStride: tileWidth,
      childMainAxisExtent: tileHeight,
      childCrossAxisExtent: tileWidth,
      reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
    );
  }

  @override
  bool shouldRelayout(_DayPickerGridDelegate oldDelegate) => false;
}

const _DayPickerGridDelegate _kDayPickerGridDelegate = _DayPickerGridDelegate();
import 'package:flutter/cupertino.dart';
import 'package:flutter_xiaoe/utils/ScreenUtil.dart';
import 'package:flutter_xiaoe/utils/NetUtil.dart';
import 'package:flutter_xiaoe/config/Api.dart';
import 'package:flutter_xiaoe/config/Colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xiaoe/widgets/login/ImageInputWidget.dart';
import 'package:flutter_xiaoe/config/Constant.dart';
import 'package:flutter_xiaoe/config/ImageConfig.dart';
import 'package:flutter_xiaoe/widgets/common/ShadowContainer.dart';
import 'package:flutter_xiaoe/widgets/login/GradientButton.dart';
import 'package:flutter_xiaoe/widgets/common/Header.dart';

class TimeUtil {
  static const List<int> _daysInMonth = <int>[
    31,
    -1,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31
  ];

  /// 获取这个月的天数
  static int getDaysInMonth(int year, int month) {
    if (month == DateTime.february) {
      final bool isLeapYear =
          (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
      if (isLeapYear) return 29;
      return 28;
    }
    return _daysInMonth[month-1];
  }

  /// 获取周Header
  static List<Widget> getDayHeaders(MaterialLocalizations localizations) {
    List<Widget> list = [];
    for (int i = localizations.firstDayOfWeekIndex; true; i = (i + 1) % 7) {
      final String weekday = localizations.narrowWeekdays[i];
      list.add(Flexible(
          child: Container(
        height: ScreenUtil.px2pt(80),
        child: Center(
          child: Text(
            weekday,
            style: TextStyle(
              color: AppColors.BLACK1,
              fontSize: ScreenUtil.px2ptFont(34),
            ),
          ),
        ),
      )));
      if (i == (localizations.firstDayOfWeekIndex - 1) % 7) break;
    }
    return list;
  }

  /// 得到这个月的第一天是星期几(0 是 星期日 1 是 星期一...)
  static int computeFirstDayOffset(
      int year, int month, MaterialLocalizations localizations) {
    // 0-based day of week, with 0 representing Monday.
    final int weekdayFromMonday = DateTime(year, month).weekday - 1;
    // 0-based day of week, with 0 representing Sunday.
    final int firstDayOfWeekFromSunday = localizations.firstDayOfWeekIndex;
    // firstDayOfWeekFromSunday recomputed to be Monday-based
    final int firstDayOfWeekFromMonday = (firstDayOfWeekFromSunday - 1) % 7;
    // Number of days between the first day of week appearing on the calendar,
    // and the day corresponding to the 1-st of the month.
    return (weekdayFromMonday - firstDayOfWeekFromMonday) % 7;
  }

  /// 获取天
  static List getDay(int year, int month, MaterialLocalizations localizations) {
    List labels = [];
    final int daysInMonth = getDaysInMonth(year, month);
    final int firstDayOffset =
        computeFirstDayOffset(year, month, localizations);
    for (int i = 0; true; i += 1) {
      // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on
      // a leap year.
      final int day = i - firstDayOffset + 1;
      if (day > daysInMonth) break;
      if (day < 1) {
        labels.add(0);
      } else {
        labels.add(DateTime(year, month, day));
      }
    }
    return labels;
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,802评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,109评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,683评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,458评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,452评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,505评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,901评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,550评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,763评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,556评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,629评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,330评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,898评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,897评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,140评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,807评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,339评论 2 342