A persian ( farsi ) datepicker for flutter.

Overview

Persian DatePicker & DateTime Manipulation

A persian ( farsi ) datepicker for flutter.

to see an example of date conversion and manipulation, refer to DateTime section in this page.

Usage

A simple example with a TextField which turns into a datepicker

main.dart

import 'package:flutter/material.dart';
import 'package:persian_datepicker/persian_datepicker.dart';


void main() {
  runApp(Home());
}

class Home extends StatefulWidget {
  @override
  HomeState createState() {
    return new HomeState();
  }
}

class HomeState extends State<Home> {

  // our text controller
  final TextEditingController textEditingController = TextEditingController();

  PersianDatePickerWidget persianDatePicker;

  @override
  void initState() {

    /*Simple DatePicker*/
    persianDatePicker = PersianDatePicker(
      controller: textEditingController,
//      datetime: '1397/06/09',
    ).init();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('دیت پیکر ساده'),),
        body: Builder(builder: (BuildContext context) {


          return Container(
            child: TextField(
              enableInteractiveSelection: false, // *** this is important to prevent user interactive selection ***
              onTap: () {
                FocusScope.of(context).requestFocus(new FocusNode()); // to prevent opening default keyboard
                showModalBottomSheet(
                    context: context,
                    builder: (BuildContext context) {
                      return persianDatePicker;
                    });
              },
              controller: textEditingController,
            ),
          );



        }),
      ),
    );
  }
}

HOW IT LOOKS

Simple DatePicker





Range DatePicker

/*Range DatePicker*/
persianDatePicker = PersianDatePicker(
  controller: textEditingController,
  rangeDatePicker: true,
  // datetime: '1397/06/09',
  // finishDatetime: '1397/06/15',
).init();





Inline DatePicker

/*Inline DatePicker*/
persianDatePicker = PersianDatePicker(
  controller: textEditingController,
  datetime: '1397/06/19',
).init();


....


return Column(
  children: <Widget>[
    // Simple Date Picker
    Container(
      child: persianDatePicker, // just pass `persianDatePicker` variable as child with no ( )
    ),
    
    // you can omit TextField when using datepicker as inline
    TextField(
      enableInteractiveSelection: false,
      controller: textEditingController,
    ),
  ],
);





Customized DatePicker

You can customize datepicker as you wish, there are a lot of options to set, below code is just a few of them.

/*Customized DatePicker*/
persianDatePicker = PersianDatePicker(
    controller: textEditingController,
    outputFormat: 'YYYY/MM/DD',
    datetime: '1397/08/29',
    finishDatetime: '1397/08/30',
    daysBorderWidth: 3,
    weekCaptionsBackgroundColor: Colors.red,
    headerBackgroundColor: Colors.blue.withOpacity(0.5),
    headerTextStyle: TextStyle(color: Colors.blue, fontSize: 17),
    headerTodayIcon: Icon(Icons.access_alarm, size: 15,),
    datePickerHeight: 280
).init();




/*Customized Font Family ( Farsi Digits )*/
persianDatePicker = PersianDatePicker(
    controller: textEditingController,
    farsiDigits: true
).init();

Or if you have a font which supports farsi digits then you can simply pass the font name and everything would be ok

اگر فونتی در برنامه استفاده کرده اید که قابلیت نمایش اعداد فارسی را دارد تنها لازم است اسم فونت را به دیت پیکر بدهید

/*Customized Font Family ( Farsi Digits )*/
persianDatePicker = PersianDatePicker(
    controller: textEditingController,
    fontFamily: 'Vazir' // here I used Vazir font
).init();




Events

onChange: fires after tapping on a day. It has two arguments, oldText and newText which represents the value of datepicker before-tap and after-tap respectively.

persianDatePicker = PersianDatePicker(
  controller: textEditingController,
  onChange: (String oldText, String newText) {
    print(oldText);
    print(newText);
  }
).init();





DateTime

in order to use PersianDateTime methods, you need to add following line into your file.

import 'package:persian_datepicker/persian_datetime.dart';

You can now use following methods with PersianDateTime instances
implemented methods:

  • toJalaali( format ) // see output formats
  • toGregorian( format ) // see output formats
  • isAfter
  • isBefore
  • difference
  • isEqual
  • add
  • subtract

All above methods work on persian ( farsi ) dates. if you want to work with gregorian datetime use Dart DateTime class

PersianDateTime persianDate1 = PersianDateTime(jalaaliDateTime: '1397/06/09'); // default is now
/*
  persianDate1 contains following properties

  jalaaliYear               1397
  jalaaliMonth              6
  jalaaliDay                9
  jalaaliShortYear          97
  jalaaliZeroLeadingMonth   06
  jalaaliZeroLeadingDay     09
  jalaaliMonthName          شهریور

  gregorianYear             2018
  gregorianMonth            8
  gregorianDay              31
  gregorianShortYear        18
  gregorianZeroLeadingDay   31
  gregorianZeroLeadingMonth 08
  gregorianMonthName        October
  gregorianShortMonthName   Oct

  datetime                  Dart DateTime class of current persian date

 */
print(persianDate1.toGregorian()); // 2018-08-31
print(persianDate1.datetime); // 2018-08-31 00:00:00.000


PersianDateTime persianDate2 = persianDate1.add(Duration(days: 10));
print(persianDate2.isBefore(persianDate1)); // false
print(persianDate2.isAfter(persianDate1)); // true
print(persianDate2.difference(persianDate1).inDays); // 10
print(persianDate2.difference(persianDate1).inHours); // 240

PersianDateTime persianDate3 = PersianDateTime(); // default is now
print(persianDate3.isEqual(persianDate1)); // false



// you can accept date as gregorian using `.fromGregorian` constructor. it will automatically convert into jalaali date
PersianDateTime persianDate3 = PersianDateTime.fromGregorian(); // default is now
print(persianDate3.toJalaali(format: 'YYYY/MM/DD')); // 1397/11/19




Output formats

YYYY full year
YY 2 digits year
MMMM full month name ( doesn't work in datepicker )
MMM short month name ( this only works in gregorian dates and also doesn't work in datepicker )
MM leading zero month digit
M month without leading zero
DD leading zero day digit
D day without leading zero





Important Notes نکات مهم

up to this version all output dates are in persian.

تا این نسخه تمام تاریخ های خروجی پارسی(جلالی) هستند

rangeSeparator and your custom date separator should not be equal, otherwise datepicker will return null

مقدار ورودی rangeSeparator و جداکننده ای که برای فرمت خروجی انتخاب کرده اید نباید یکی باشند در این صورت دیت پیکر خروجی جداکننده های محدوده و خروجی مشابه هستند برمیگرداند


Persian input dates must respect YYYY/MM/DD format. output format is up to you
Gregorian input dates must respect YYYY-MM-DD format. output format is persian and up to you

فرمت تاریخ های ورودی که پارسی (جلالی) هستند باید بصورت YYYY/MM/DD باشد. فرمت خروجی به دلخواه شماست

فرمت تاریخ های ورودی که میلادی هستند باید بصورت YYYY-MM-DD باشد. فرمت تاریخ خروجی، پارسی و به دلخواه شما خواهد بود


Version 1.3 features

/// حداکثر تاریخی که میتوان در دیت پیکر انتخاب کرد String maxDatetime;

/// حداقل تاریخی که میتوان در دیت پیکر انتخاب کرد String minDatetime;

/// حداکثر فاصله ای که تاریخ شروع و تاریخ پایان میتوانند نسبت به یکدیگر داشته باشند Duration maxSpan;

/// حداقل فاصله ای که تاریخ شروع و تاریخ پایان میتوانند نسبت به یکدیگر داشته باشند Duration minSpan;

in order to update these options programmatically you can use update method, like so

...

  FlatButton(
      onPressed: () {
        minSpan = Duration(days: 10);
        setState(() {
          
          
          // here you can update the options
          persianDatePicker.update(
              minSpan: minSpan,
              minDatetime: '1397/12/19',
              maxDatetime: '1397/12/29');



        });
      },
      child: Container(
        child: Text('Update Datepicker'),
      ),
  )

...

Examples

You can find the full example in the Git Repository, example directory

Comments
  • Add persian number  option

    Add persian number option

    It would be great if you create a feature for supporting Persian number in date picker because this is a Persian date picker with numbers should be in a Persian format not English.

    enhancement good first issue 
    opened by DanialV 8
  • The method 'call' was called on null.

    The method 'call' was called on null.

    Hi, An issue I am currently facing with this widget is, when I am tapping on a day to select, a DEBUG CONSOLE exception appears at console as following:

    I/flutter (26259): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5) I/flutter (26259): #1 _PersianDatePickerWidgetState._dayBlock.<anonymous closure> package:persian_datepicker/persian_datepicker.dart:1080 I/flutter (26259): #2 _InkResponseState._handleTap package:flutter/…/material/ink_well.dart:635 I/flutter (26259): #3 _InkResponseState.build.<anonymous closure> package:flutter/…/material/ink_well.dart:711 I/flutter (26259): #4 GestureRecognizer.invokeCallback package:flutter/…/gestures/recognizer.dart:182 I/flutter (26259): #5 TapGestureRecognizer._checkUp package:flutter/…/gestures/tap.dart:365 I/flutter (26259): #6 TapGestureRecognizer.acceptGesture package:flutter/…/gestures/tap.dart:312 I/flutter (26259): #7 GestureArenaManager.sweep package:flutter/…/gestures/arena.dart:156 I/flutter (26259): #8 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent package:flutter/…/gestures/binding.dart:222 I/flutter (26259): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent package:flutter/…/gestures/binding.dart:198 I/flutter (26259): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent package:flutter/…/gestures/binding.dart:156 I/flutter (26259): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue package:flutter/…/gestures/binding.dart:102 I/flutter (26259): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket package:flutter/…/gestures/binding.dart:86 I/flutter (26259): #16 _invoke1 (dart:ui/hooks.dart:250:10) I/flutter (26259): #17 _dispatchPointerDataPacket (dart:ui/hooks.dart:159:5) I/flutter (26259): (elided 3 frames from package dart:async) I/flutter (26259): Handler: "onTap" I/flutter (26259): Recognizer: I/flutter (26259): TapGestureRecognizer#a72df I/flutter (26259):

    Here is my widget:

    import 'package:flutter/material.dart';
    import 'package:persian_datepicker/persian_datepicker.dart';
    
    class TestScreen extends StatefulWidget {
      @override
      _TestScreenState createState() => _TestScreenState();
    }
    
    class _TestScreenState extends State<TestScreen> {
      final TextEditingController textEditingController = TextEditingController();
      PersianDatePickerWidget persianDatePicker;
    
      @override
      void initState() {
        super.initState();
    
        persianDatePicker = PersianDatePicker(
          controller: textEditingController,
          //datetime: '1397/06/09',
          outputFormat: 'YYYY/MM/DD',
        ).init();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(
              "Sample App",
              style:
                  Theme.of(context).textTheme.title.copyWith(color: Colors.white),
            ),
            actions: <Widget>[
              Container(
                child: Image.asset("assets/images/white-logo.png"),
                padding: EdgeInsets.all(8),
              ),
            ],
          ),
          body: Container(
            child: Padding(
                padding: const EdgeInsets.all(8.0), child: persianDatePicker),
          ),
        );
      }
    }
    
    opened by wkhaksar 5
  • سورس کد اصلی برنامه

    سورس کد اصلی برنامه

    سلام دوست من ممنون بخاطر لایبرری فوق‌العاده‌ای که نوشتی ولی سوال من اینه که خود سورس‌کدش کجاست من می‌خوام کانتریبیوت کنم ولی دیدم تووی "لیب" فقط "مین" هست که اونم عملا اپ تسته. ممنون.

    opened by alizera 2
  • نحوه غیرفعال کردن روزای ماقبل روز فعلی

    نحوه غیرفعال کردن روزای ماقبل روز فعلی

    سلام ببخشید دوتاسوال دارم ممنون میشم جواب بدین:

    1- چرا موقعی که فارسی میکنیم تقویم رو عددی که تومتغیر ذخیره میکنیم هم فارسی میده نمیشه نمایش برای کاربر اعداد فارسی باشه ولی چیزی که ست میشه تو متغیر با اعداد انگلیسی باشه

    2- چطوری میتونم روزای ماقبل روز فعلی رو غیر فعال کنم یا رنگشون عوض کنم که کاربر نتونه انتخاب کنه

    opened by sardarmz 1
  • close datepicker on tap to date

    close datepicker on tap to date

    سلام اول از همه بابت این پیکری که نوشتین تشکر میکنم خیلی خوب هست و قابلیت شخصی سازی عالی داره. فقط یک مشکلی که من دارم و نتونستم شاید پیداش کنم. بسته شدن پیکر با انتخاب یک تاریخ هست. الان تنها گزینه ای که هست اینه روی فضای خالی بالای پیکر تپ کنیم تا بسته بشه؟ این گزینه اگر هست کدوم هست؟ اگر نیست اضافه کنین عالی میشه. با تشکر

    opened by mahmoudparandeh 1
  • How to change the months name?

    How to change the months name?

    First, thank you for this package. How can I change the month's name? I'm from Afghanistan and as you know in here the month's name is different for example instead of فروردین we have حمل.

    opened by AzadCoder 0
Owner
FullStack Developer. Flutter, Dart. Master of Computer Science (ImamReza University) Looking for a remote job Full Stack Web Developer + Flutter
null
🆙🚀 Flutter application upgrade/ Flutter App Upgrade /Flutter App Update/Flutter Update / download Plug-in

???? Flutter application upgrade/ Flutter App Upgrade /Flutter App Update/Flutter Update / download Plug-in (with notice bar progress), supports full upgrade, hot update and incremental upgrade

PengHui Li 344 Dec 30, 2022
ABC of Flutter widgets. Intended for super beginners at Flutter. Play with 35+ examples in DartPad directly and get familiar with various basic widgets in Flutter

Basic Widgets Examples This is aimed for complete beginners in Flutter, to get them acquainted with the various basic widgets in Flutter. Run this pro

Pooja Bhaumik 815 Jan 3, 2023
Minha primeira aplicação android utilizando Flutter feito no curso de Flutter da Cod3r Cursos Online. O foco dessa aplicação foi um contato inicial com o Flutter.

expenses Expenses é uma aplicação android simples feita em Flutter para controlar despesas pessoais. A aplicação consiste em: Listar transações feitas

Guilherme Teixeira Ais 2 Apr 19, 2022
Flutter Github Following Application, Using Flutter Provider and Flutter HTTP to get data from Github API.

Flutter Github Following Application Watch it on Youtube Previous Designs Checkout my Youtube channel Installation Please remember, after cloning this

Mohammad Rahmani 110 Dec 23, 2022
Flutter RSS feed parsing - A demo application of flutter which parse RSS XML contents to the flutter application

Flutter RSS feed parsing demo This is demo application of flutter which shows ho

Nyakuri Levite 3 Nov 15, 2022
Boris Gautier 1 Jan 31, 2022
Code for Flutter Talk from Flutter Vikings 2022: Custom User Interactions in Flutter

Custom User Interactions - Flutter Vikings 2022 A companion app for the Flutter Vikings 2022 talk - Custom User Interactions with Shortcuts, Intents,

Justin McCandless 9 Sep 16, 2022
Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flutter app.

Flutter Tutorial - User Profile Page UI 1/2 Create a Flutter User Profile Page UI where you can access and edit your user's information within your Fl

Johannes Milke 46 Dec 6, 2022
Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flutter app.

Flutter Tutorial - User Profile Page UI #2 Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flu

Johannes Milke 45 Dec 15, 2022
Let's create a selectable Flutter Navigation Drawer with routing that highlights the current item within the Flutter Sidebar Menu.

Flutter Tutorial - Sidebar Menu & Selectable Navigation Drawer Let's create a selectable Flutter Navigation Drawer with routing that highlights the cu

Johannes Milke 12 Dec 26, 2022
Components that optimize Flutter fluency.(Flutter 流畅度优化的通用方案,轻松解决卡顿问题)

Flutter fluency optimization component "Keframe" Page switching fluency improved: How to use Project depend on: Quick learning Constructor Description

Ke Technologies 793 Dec 30, 2022
Challenge yourself every weekend with flutter. Join me to implement challenging UI & digital designs using Flutter.

Weekend With Flutter This is my new challenge. Every weekend, I want to implement challenging UI & digital designs using Flutter. you can join me with

Payam Zahedi 16 Feb 24, 2022
Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Flutter Tutorial - User Profile & SharedPreferences Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's inf

Johannes Milke 21 Dec 3, 2022
Let's create a Flutter Collapsible Sidebar Menu that can collapse and expand the Navigation Drawer in Flutter.

Flutter Tutorial - Collapsible Sidebar Menu & Navigation Drawer Let's create a Flutter Collapsible Sidebar Menu that can collapse and expand the Navig

Johannes Milke 22 Jan 3, 2023
🚗 Apple CarPlay for Flutter Apps. Aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay.

CarPlay with Flutter ?? Flutter Apps now on Apple CarPlay! flutter_carplay aims to make it safe to use iPhone apps made with Flutter in the car by int

Oğuzhan Atalay 156 Dec 26, 2022
Flutter ui boilerplate is easiest way to create new flutter project with clean code and well organized file folder.

Flutter UI Boilerplate "Sharing for fun" Flutter ui boilerplate is easiest way to create new flutter project with clean code and well organized file f

Dimas Ibnu Malik 122 Dec 1, 2022
This is a Flutter app which shows how to use the PageView Class in your Flutter App

page_view_class A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Shehzaan Mansuri 1 Oct 25, 2021
Flutter Architecture Blueprints is a project that introduces MVVM architecture and project structure approaches to developing Flutter apps.

Flutter Architecture Blueprints Flutter Architecture Blueprints is a project that introduces MVVM architecture and project structure approaches to dev

Katsuyuki Mori 2 Apr 9, 2022