Code Monkey home page Code Monkey logo

Comments (8)

Gujie-Novade avatar Gujie-Novade commented on June 28, 2024 1

I tried extending the CommonPickerModel by copying the code from DatePickerModel and switching all the left and right functions.
Here is the code:

class _DateDDMMYYYModel extends CommonPickerModel {
  DateTime maxTime;
  DateTime minTime;

  _DateDDMMYYYModel({DateTime currentTime, DateTime maxTime, DateTime minTime})
      : super(currentTime: currentTime) {
    this.maxTime = maxTime ?? DateTime(2049, 12, 31);
    this.minTime = minTime ?? DateTime(1970, 1, 1);

    currentTime = currentTime ?? DateTime.now();
    if (currentTime != null) {
      if (currentTime.compareTo(this.maxTime) > 0) {
        currentTime = this.maxTime;
      } else if (currentTime.compareTo(this.minTime) < 0) {
        currentTime = this.minTime;
      }
    }
    this.currentTime = currentTime;

    _fillLeftLists();
    _fillMiddleLists();
    _fillRightLists();
    int minMonth = _minMonthOfCurrentYear();
    int minDay = _minDayOfCurrentMonth();
    setLeftIndex(this.currentTime.day - minDay);
    setMiddleIndex(this.currentTime.month - minMonth);
    setRightIndex(this.currentTime.year - this.minTime.year);
  }

  void _fillLeftLists() {
    int maxDay = _maxDayOfCurrentMonth();
    int minDay = _minDayOfCurrentMonth();
    this.leftList = List.generate(maxDay - minDay + 1, (int index) {
      return '${minDay + index}${_localeDay()}';
    });
  }

  int _maxMonthOfCurrentYear() {
    return currentTime.year == maxTime.year ? maxTime.month : 12;
  }

  int _minMonthOfCurrentYear() {
    return currentTime.year == minTime.year ? minTime.month : 1;
  }

  int _maxDayOfCurrentMonth() {
    int dayCount = _calcDateCount(currentTime.year, currentTime.month);
    return currentTime.year == maxTime.year &&
            currentTime.month == maxTime.month
        ? maxTime.day
        : dayCount;
  }

  int _minDayOfCurrentMonth() {
    return currentTime.year == minTime.year &&
            currentTime.month == minTime.month
        ? minTime.day
        : 1;
  }

  void _fillMiddleLists() {
    int minMonth = _minMonthOfCurrentYear();
    int maxMonth = _maxMonthOfCurrentYear();

    this.middleList = List.generate(maxMonth - minMonth + 1, (int index) {
      return '${_localeMonth(minMonth + index)}';
    });
  }

  void _fillRightLists() {
    this.rightList =
        List.generate(maxTime.year - minTime.year + 1, (int index) {
      // print('LEFT LIST... ${minTime.year + index}${_localeYear()}');
      return '${minTime.year + index}${_localeYear()}';
    });
  }

  @override
  void setLeftIndex(int index) {
    super.setLeftIndex(index);
    int minDay = _minDayOfCurrentMonth();
    currentTime = currentTime.isUtc
        ? DateTime.utc(
            currentTime.year,
            currentTime.month,
            minDay + index,
          )
        : DateTime(
            currentTime.year,
            currentTime.month,
            minDay + index,
          );
  }

  @override
  void setMiddleIndex(int index) {
    super.setMiddleIndex(index);
    //adjust right
    int minMonth = _minMonthOfCurrentYear();
    int destMonth = minMonth + index;
    DateTime newTime;
    //change date time
    int dayCount = _calcDateCount(currentTime.year, destMonth);
    newTime = currentTime.isUtc
        ? DateTime.utc(
            currentTime.year,
            destMonth,
            currentTime.day <= dayCount ? currentTime.day : dayCount,
          )
        : DateTime(
            currentTime.year,
            destMonth,
            currentTime.day <= dayCount ? currentTime.day : dayCount,
          );
    //min/max check
    if (newTime.isAfter(maxTime)) {
      currentTime = maxTime;
    } else if (newTime.isBefore(minTime)) {
      currentTime = minTime;
    } else {
      currentTime = newTime;
    }

    _fillLeftLists();
    // _fillRightLists();
    int minDay = _minDayOfCurrentMonth();
    setLeftIndex(currentTime.day - minDay);
    // _currentRightIndex = currentTime.day - minDay;
  }

  @override
  void setRightIndex(int index) {
    super.setRightIndex(index);
    //adjust middle
    int destYear = index + minTime.year;
    DateTime newTime;
    //change date time
    if (currentTime.month == 2 && currentTime.day == 29) {
      newTime = currentTime.isUtc
          ? DateTime.utc(
              destYear,
              currentTime.month,
              _calcDateCount(destYear, 2),
            )
          : DateTime(
              destYear,
              currentTime.month,
              _calcDateCount(destYear, 2),
            );
    } else {
      newTime = currentTime.isUtc
          ? DateTime.utc(
              destYear,
              currentTime.month,
              currentTime.day,
            )
          : DateTime(
              destYear,
              currentTime.month,
              currentTime.day,
            );
    }
    //min/max check
    if (newTime.isAfter(maxTime)) {
      currentTime = maxTime;
    } else if (newTime.isBefore(minTime)) {
      currentTime = minTime;
    } else {
      currentTime = newTime;
    }

    _fillMiddleLists();
    _fillLeftLists();
    // _fillRightLists();
    int minMonth = _minMonthOfCurrentYear();
    int minDay = _minDayOfCurrentMonth();
    setMiddleIndex(currentTime.month - minMonth);
    setLeftIndex(currentTime.day - minDay);
    // _currentMiddleIndex = currentTime.month - minMonth;
    // _currentRightIndex = currentTime.day - minDay;
  }

  @override
  String leftStringAtIndex(int index) {
    if (index >= 0 && index < leftList.length) {
      return leftList[index];
    } else {
      return null;
    }
  }

  @override
  String middleStringAtIndex(int index) {
    if (index >= 0 && index < middleList.length) {
      return middleList[index];
    } else {
      return null;
    }
  }

  @override
  String rightStringAtIndex(int index) {
    if (index >= 0 && index < rightList.length) {
      return rightList[index];
    } else {
      return null;
    }
  }

  String _localeYear() {
    if (locale == LocaleType.zh) {
      return '年';
    } else if (locale == LocaleType.ko) {
      return '년';
    } else {
      return '';
    }
  }

  String _localeMonth(int month) {
    if (locale == LocaleType.zh) {
      return '$month月';
    } else if (locale == LocaleType.ko) {
      return '$month월';
    } else {
      List monthStrings = i18nObjInLocale(locale)['monthLong'];
      return monthStrings[month - 1];
    }
  }

  String _localeDay() {
    if (locale == LocaleType.zh) {
      return '日';
    } else if (locale == LocaleType.ko) {
      return '일';
    } else {
      return '';
    }
  }

  @override
  DateTime finalTime() {
    return currentTime;
  }
}

List<int> _leapYearMonths = const <int>[1, 3, 5, 7, 8, 10, 12];

int _calcDateCount(int year, int month) {
  if (_leapYearMonths.contains(month)) {
    return 31;
  } else if (month == 2) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
      return 29;
    }
    return 28;
  }
  return 30;
}

It's working well but there's a last small bug. When I switch from a month with 30 days to another one with 31 days, the 31 doesn't appear in the list of days. See gif:

Day bug

from flutter_datetime_picker.

Realank avatar Realank commented on June 28, 2024

as I wrote in readme, you can create your own PickerModel to feed data

from flutter_datetime_picker.

AndreaMainella avatar AndreaMainella commented on June 28, 2024

Hi sorry if I still bother you, I tried to use the CommonPickerModel as you told me but I found some problems.
It does not show me any dates, there is no way to set the maxTime and minTime not directly on your dependency.
How can I solve, I'm sorry for my English but I'm Italian

Later I leave you my code:

import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    locale: Locale("it"),
    title: "DateTimePicker",
    home: Home(),
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  EventList<Event> markedDateMap = new EventList(events: {
    new DateTime(2019, 3, 21): [
      new Event(date: DateTime(2019, 03, 21), title: "Prova")
    ]
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Calendar"),
      ),
      body: SingleChildScrollView(
        child: Container(
          color: Colors.white,
          child: Column(
            children: <Widget>[
              FlatButton(
                  onPressed: () {
                    DatePicker.showPicker(context,
                        showTitleActions: true,
                        locale: LocaleType.it,
                        pickerModel: prova(), onConfirm: (date) {
                      print(date);
                    });
//                    DatePicker.showDateTimePicker(
//                        context,
//                        showTitleActions: true,
//                        onChanged: (date) {}, onConfirm: (date) {
//                      setState(() {
//                        markedDateMap.add(
//                            date,
//                            Event(
//                                date: date,
//                                title: "Aula prenotata",
//                                icon: Icon(Icons.add)));
//                        print(markedDateMap.getEvents(date).length);
//                        print('confirm $date');
//                      });
//                    }, currentTime: DateTime.now(), locale: LocaleType.it);
                  },
                  child: Text(
                    'Date Time Picker',
                    style: TextStyle(color: Colors.blue),
                  )),
              Material(
                  child: Column(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 16.0),
                    child: CalendarCarousel(
                      onDayPressed: (DateTime date, List<Event> events) {
                        events.forEach((event) =>
                            print(event.title + event.date.toString()));
                      },
                      weekendTextStyle: TextStyle(
                        color: Colors.red,
                      ),
                      thisMonthDayBorderColor: Colors.grey,
                      weekFormat: false,
                      markedDatesMap: markedDateMap,
                      height: 450,
                      isScrollable: false,
                      customGridViewPhysics: NeverScrollableScrollPhysics(),
                      selectedDateTime: DateTime.now(),
                      daysHaveCircularBorder: true,
                      locale: "it",
                    ),
                  ),
                  ListTile(
                    title: Text("27/03/2019"),
                    subtitle: Text("Aula occupata da: Fabio"),
                  ),
                  ListTile(
                    title: Text("28/03/2019"),
                    subtitle: Text("Aula occupata da: Mainella"),
                  )
                ],
              )),
            ],
          ),
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text("Home"),
        ),
        BottomNavigationBarItem(icon: Icon(Icons.event), title: Text("Eventi"))
      ]),
    );
  }
}

prova() {
  CommonPickerModel current = new CommonPickerModel();
  current.locale = LocaleType.it;
  current.currentTime = DateTime.now();
  current.setLeftIndex(current.currentTime.day);
  current.setMiddleIndex(current.currentTime.month);
  current.setRightIndex(current.currentTime.year);
  return current;
}

Screenshot_1553005435

from flutter_datetime_picker.

Realank avatar Realank commented on June 28, 2024

Hi, you should extends CommonPickerModel, not init a instance, you should provide your own data

from flutter_datetime_picker.

steve28100 avatar steve28100 commented on June 28, 2024

@Gujie-Novade Have you fix the switch month issue yet?

from flutter_datetime_picker.

Gujie-Novade avatar Gujie-Novade commented on June 28, 2024

@Gujie-Novade Have you fix the switch month issue yet?

Eventually we ended up using the Android style date picker...

from flutter_datetime_picker.

steve28100 avatar steve28100 commented on June 28, 2024

I also have modified the codes and have solve the problem for the detail you can see this issue #93

from flutter_datetime_picker.

sbergmair avatar sbergmair commented on June 28, 2024

Any changes here?
Tried to create a CustomModel, but have the same problem as others:
Switching from a month with less 31 days to a month with 31 days does update the list only if I scroll to 31 (although 31 is not shown before).

from flutter_datetime_picker.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.