Is there a way to implement this kind of horizontal Month selector in flutter? For This I need to show the month and year and when clicked on the buttons on the side to go to the next month and when clicked on the Month to open a calendar.
2
the table_calendar package is the right one on your case, give it a try
if you dont want to use package here simple code, you can customize with your own style :
import 'package:flutter/material.dart'; typedef OnHorizontalDatePickerSelected = void Function(DateTime dateTime); typedef OnHorizontalDatePickerSubmitted = void Function(DateTime dateTime); class HorizontalDatePicker extends StatefulWidget { final DateTime? initial; final OnHorizontalDatePickerSelected onSelected; final OnHorizontalDatePickerSubmitted? onSubmitted; const HorizontalDatePicker({Key? key, this.initial, required this.onSelected, this.onSubmitted}) : super(key: key); @override State<HorizontalDatePicker> createState() => _HorizontalDatePickerState(); } class _HorizontalDatePickerState extends State<HorizontalDatePicker> { static const Map<int, String> _monthList = {DateTime.january: 'Jan', DateTime.february: 'Feb', DateTime.march: 'Mar', DateTime.april: 'Apr', DateTime.may: 'May', DateTime.june: 'Jun', DateTime.july: 'Jul', DateTime.august: 'Aug', DateTime.september: 'Sep', DateTime.october: 'Okt', DateTime.november: 'Nov', DateTime.december: 'Des'}; late DateTime _current; @override void initState() { super.initState(); _current = widget.initial ?? DateTime.now(); } @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _previous(), _month(), _year(), _next(), widget.onSubmitted !=null? _button() : const SizedBox() ], ); } Widget _previous() { return IconButton( onPressed: () { setState(() { _current = DateTime(_current.year, _current.month - 1); }); widget.onSelected(_current); }, icon: const Icon(Icons.arrow_back_ios_sharp)); } Widget _next() { return IconButton( onPressed: () { setState(() { _current = DateTime(_current.year, _current.month + 1); }); widget.onSelected(_current); }, icon: const Icon(Icons.arrow_forward_ios_sharp)); } Widget _month() { return Padding( padding: const EdgeInsets.all(10.0), child: Text('${_monthList[_current.month]}'), ); } Widget _year() { return Padding( padding: const EdgeInsets.all(10.0), child: Text('${_current.year}'), ); } Widget _button(){ return Row( children: [ TextButton(onPressed: (){ widget.onSubmitted!(_current); }, child: const Text("Select")) ], ); } }
use it anywhere you want :
Scaffold( body: HorizontalDatePicker( onSelected: (DateTime time){ print(time); }, onSubmitted: (DateTime time){ print(time); }, ), ),
Click here to cancel reply.
2
Answers
the table_calendar package is the right one on your case, give it a try
if you dont want to use package here simple code, you can customize with your own style :
use it anywhere you want :