Flutter日期选择器插件flutter_jalali_date_picker的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter日期选择器插件flutter_jalali_date_picker的使用

简介

flutter_jalali_date_picker 是一个支持Jalali(伊朗)日期格式的日期选择器插件,适用于Android、iOS、macOS、Web、Windows和Linux平台。该插件基于 persian_datetime_picker 开发,提供了丰富的日期选择功能,并且可以将日期格式化为波斯语。

平台支持

平台 支持情况
Android ✔️
iOS ✔️
macOS ✔️
Web ✔️
Windows ✔️
Linux ✔️

使用步骤

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_jalali_date_picker: ^2.2.4 # 最新版本
  shamsi_date: ^1.0.4
2. 引入包

在 Dart 文件中引入 flutter_jalali_date_pickershamsi_date 包:

import 'package:flutter/material.dart';
import 'package:flutter_jalali_date_picker/flutter_jalali_date_picker.dart';
import 'package:shamsi_date/shamsi_date.dart';
3. 使用示例

下面是一个完整的示例代码,展示了如何使用 flutter_jalali_date_picker 插件来实现日期选择功能。这个示例包括了多种日期选择器的用法,如普通日期选择器、范围日期选择器、时间选择器等。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_jalali_date_picker/flutter_jalali_date_picker.dart';
import 'package:shamsi_date/shamsi_date.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Jalali Date Picker Example',
      theme: ThemeData(colorScheme: const ColorScheme.light()),
      darkTheme: ThemeData(colorScheme: const ColorScheme.dark()),
      themeMode: ThemeMode.light,
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  [@override](/user/override)
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  DateTime? selectedDate;
  String? label;

  [@override](/user/override)
  Widget build(BuildContext context) {
    const itemHeight = 40.0;
    final itemWidth = (MediaQuery.of(context).size.width -
            (MediaQuery.of(context).padding.left +
                MediaQuery.of(context).padding.right)) /
        2;

    return Scaffold(
      appBar: AppBar(
        title: const Text('دیت تایم پیکر خورشیدی'),
      ),
      body: GridView.count(
        padding: const EdgeInsets.all(8),
        physics: const AlwaysScrollableScrollPhysics(),
        crossAxisCount: 2,
        childAspectRatio: (itemWidth / itemHeight),
        children: [
          /// 普通日期选择器
          TextButton(
            onPressed: () async {
              final picked = await showJalaliDatePicker(
                context,
                initialDate: Jalali.fromDateTime(selectedDate ?? DateTime.now()),
                firstDate: Jalali.min,
                lastDate: Jalali.max,
                popOnSelectDate: false,
              );

              if (picked != null) {
                final pickedDateTime = picked.toDateTime();

                if (pickedDateTime != selectedDate) {
                  setState(() {
                    selectedDate = pickedDateTime;
                    label = pickedDateTime.dateToYMMMdPersian();
                  });
                }
              }
            },
            child: const Text(
              "Date Picker",
              textAlign: TextAlign.center,
            ),
          ),

          /// 日期选择器组件
          TextButton(
            onPressed: () async {
              final picked = await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => DatePickerScreen(
                            initialDate: Jalali.fromDateTime(
                                selectedDate ?? DateTime.now()),
                            lastDate: Jalali.now(),
                          )));

              if (picked is Jalali) {
                final pickedDateTime = picked.toDateTime();

                if (pickedDateTime != selectedDate) {
                  setState(() {
                    selectedDate = pickedDateTime;
                    label = pickedDateTime.dateToYMMMdPersian();
                  });
                }
              }
            },
            child: const Text(
              "Date Picker Widget",
              textAlign: TextAlign.center,
            ),
          ),

          /// 范围日期选择器组件
          TextButton(
            onPressed: () async {
              final picked = await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => DatePickerRangeScreen(
                            initialDateRange: JalaliRange(
                              start: Jalali(1403, 1, 1),
                              end: Jalali(1403, 1, 13),
                            ),
                            lastDate: Jalali.now(),
                          )));

              if (picked is JalaliRange) {
                setState(() {
                  label =
                      "${picked.start.toDateTime().dateToYMMMdPersian()} تا ${picked.end.toDateTime().dateToYMMMdPersian()}";
                });
              }
            },
            child: const Text(
              "Date Picker Range Widget",
              textAlign: TextAlign.center,
            ),
          ),

          /// Cupertino 风格日期选择器
          TextButton(
            onPressed: () async {
              final picked = await showModalBottomSheet<Jalali>(
                context: context,
                builder: (context) {
                  Jalali? tempPickedDate;

                  return SizedBox(
                    height: 250,
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            CupertinoButton(
                              child: const Text('لغو'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                            CupertinoButton(
                              child: const Text('تایید'),
                              onPressed: () {
                                Navigator.of(context)
                                    .pop(tempPickedDate ?? Jalali.now());
                              },
                            ),
                          ],
                        ),
                        const Divider(
                          height: 0,
                          thickness: 1,
                        ),
                        Expanded(
                          child: PCupertinoDatePicker(
                            mode: PCupertinoDatePickerMode.date,
                            initialDateTime: Jalali.fromDateTime(
                                selectedDate ?? DateTime.now()),
                            onDateTimeChanged: (Jalali dateTime) {
                              tempPickedDate = dateTime;
                            },
                          ),
                        ),
                      ],
                    ),
                  );
                },
              );

              if (picked != null) {
                final pickedDateTime = picked.toDateTime();

                if (pickedDateTime != selectedDate) {
                  setState(() {
                    selectedDate = pickedDateTime;
                    label = pickedDateTime.dateToYMMMdPersian();
                  });
                }
              }
            },
            child: const Text(
              "Date Picker Cupertino",
              textAlign: TextAlign.center,
            ),
          ),

          /// 时间选择器(输入模式)
          TextButton(
            onPressed: () async {
              final picked = await showJalaliTimePicker(
                context,
                initialTime: TimeOfDay.now(),
                initialEntryMode: PTimePickerEntryMode.input,
                builder: (BuildContext context, Widget? child) {
                  return Directionality(
                    textDirection: TextDirection.rtl,
                    child: MediaQuery(
                      data: MediaQuery.of(context)
                          .copyWith(alwaysUse24HourFormat: true),
                      child: child!,
                    ),
                  );
                },
              );

              if (picked != null) {
                setState(() {
                  label = picked.persianFormat(context);
                });
              }
            },
            child: const Text(
              "Time Picker Input Mode",
              textAlign: TextAlign.center,
            ),
          ),

          /// 日期和时间选择器(Cupertino 风格)
          TextButton(
            onPressed: () async {
              final picked = await showModalBottomSheet<Jalali>(
                context: context,
                builder: (context) {
                  Jalali? tempPickedDate;

                  return SizedBox(
                    height: 250,
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            CupertinoButton(
                              child: const Text('لغو'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                            CupertinoButton(
                              child: const Text('تایید'),
                              onPressed: () {
                                Navigator.of(context)
                                    .pop(tempPickedDate ?? Jalali.now());
                              },
                            ),
                          ],
                        ),
                        const Divider(
                          height: 0,
                          thickness: 1,
                        ),
                        Expanded(
                          child: PCupertinoDatePicker(
                            mode: PCupertinoDatePickerMode.dateAndTime,
                            initialDateTime: Jalali.fromDateTime(
                                selectedDate ?? DateTime.now()),
                            onDateTimeChanged: (Jalali dateTime) {
                              tempPickedDate = dateTime;
                            },
                            use24hFormat: false,
                          ),
                        ),
                      ],
                    ),
                  );
                },
              );

              if (picked != null) {
                final pickedDateTime = picked.toDateTime();

                if (pickedDateTime != selectedDate) {
                  setState(() {
                    selectedDate = pickedDateTime;
                    label = pickedDateTime.dateTimeToStringPersian();
                  });
                }
              }
            },
            child: const Text(
              "Date & Time Picker Cupertino",
              textAlign: TextAlign.center,
            ),
          ),

          /// 时间选择器(Cupertino 风格)
          TextButton(
            onPressed: () async {
              Jalali? picked = await showModalBottomSheet<Jalali>(
                context: context,
                builder: (context) {
                  Jalali? tempPickedDate;
                  return SizedBox(
                    height: 250,
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            CupertinoButton(
                              child: const Text('لغو'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                            CupertinoButton(
                              child: const Text('تایید'),
                              onPressed: () {
                                Navigator.of(context)
                                    .pop(tempPickedDate ?? Jalali.now());
                              },
                            ),
                          ],
                        ),
                        const Divider(
                          height: 0,
                          thickness: 1,
                        ),
                        Expanded(
                          child: PCupertinoDatePicker(
                            mode: PCupertinoDatePickerMode.time,
                            onDateTimeChanged: (Jalali dateTime) {
                              tempPickedDate = dateTime;
                            },
                          ),
                        ),
                      ],
                    ),
                  );
                },
              );

              if (picked != null) {
                final pickedDateTime = picked.toDateTime();

                if (pickedDateTime != selectedDate) {
                  setState(() {
                    selectedDate = pickedDateTime;
                    label = picked.toJalaliDateTime();
                  });
                }
              }
            },
            child: const Text(
              "Time Picker Cupertino",
              textAlign: TextAlign.center,
            ),
          ),

          /// 范围日期选择器
          TextButton(
            onPressed: () async {
              final picked = await showJalaliDateRangePicker(
                context,
                initialDateRange: JalaliRange(
                  start: Jalali(1403, 1, 1),
                  end: Jalali(1403, 1, 13),
                ),
                firstDate: Jalali.min,
                lastDate: Jalali.max,
              );

              if (picked != null) {
                setState(() {
                  label =
                      "${picked.start.toDateTime().dateToYMMMdPersian()} تا ${picked.end.toDateTime().dateToYMMMdPersian()}";
                });
              }
            },
            child: const Text(
              "Range Date Picker",
              textAlign: TextAlign.center,
            ),
          ),

          /// 时间选择器
          TextButton(
            onPressed: () async {
              var picked = await showJalaliTimePicker(
                context,
                initialTime: TimeOfDay.now(),
                builder: (BuildContext context, Widget? child) {
                  return Directionality(
                    textDirection: TextDirection.rtl,
                    child: child!,
                  );
                },
              );

              if (picked != null) {
                setState(() {
                  label = picked.persianFormat(context);
                });
              }
            },
            child: const Text(
              "Time Picker",
              textAlign: TextAlign.center,
            ),
          ),

          /// 范围日期选择器(输入模式)
          TextButton(
            onPressed: () async {
              var picked = await showJalaliDateRangePicker(
                context,
                initialEntryMode: PDatePickerEntryMode.input,
                initialDateRange: JalaliRange(
                  start: Jalali(1403, 1, 1),
                  end: Jalali(1403, 1, 13),
                ),
                firstDate: Jalali.min,
                lastDate: Jalali.max,
              );

              if (picked != null) {
                setState(() {
                  label =
                      "${picked.start.toDateTime().dateToYMMMdPersian()} تا ${picked.end.toDateTime().dateToYMMMdPersian()}";
                });
              }
            },
            child: const Text(
              "Range Date Picker Input Mode",
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
      bottomNavigationBar: Directionality(
        textDirection: TextDirection.rtl,
        child: Container(
          height: 70,
          width: double.infinity,
          padding: const EdgeInsets.all(10),
          child: Center(
            child: Text(
              label ?? 'انتخاب تاریخ زمان',
              style: Theme.of(context).textTheme.headlineSmall,
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter日期选择器插件flutter_jalali_date_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日期选择器插件flutter_jalali_date_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用flutter_jalali_date_picker插件的示例代码。这个插件用于选择波斯(Jalali)日历日期的日期选择器。

首先,确保你已经在pubspec.yaml文件中添加了flutter_jalali_date_picker依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_jalali_date_picker: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来获取依赖。

接下来,在你的Flutter应用中,你可以按照以下方式使用flutter_jalali_date_picker

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Jalali Date Picker Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  JalaliDateTime? selectedDate;

  void _selectDate(BuildContext context) async {
    final JalaliDateTime? pickedDate = await showJalaliDatePicker(
      context: context,
      initialDate: selectedDate ?? JalaliDateTime.now(),
      firstDate: JalaliDateTime(1300, 1, 1),
      lastDate: JalaliDateTime(1500, 12, 31)
    );

    if (pickedDate != null && pickedDate != selectedDate) {
      setState(() {
        selectedDate = pickedDate;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Jalali Date Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedDate == null
                  ? 'No date selected.'
                  : 'Selected date: ${selectedDate!.toPersianDateString()}',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _selectDate(context),
              child: Text('Select Date'),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml文件中添加flutter_jalali_date_picker依赖。
  2. 导入包:在Dart文件中导入flutter_jalali_date_picker包。
  3. 创建UI
    • 使用MaterialAppScaffold构建基本的UI结构。
    • 创建一个按钮,当用户点击按钮时,会调用_selectDate函数。
    • _selectDate函数使用showJalaliDatePicker显示日期选择器对话框,并更新选中的日期。
  4. 显示选中的日期:使用Text组件显示选中的日期。如果没有选中日期,则显示"No date selected."。

这个示例展示了如何使用flutter_jalali_date_picker插件在Flutter应用中实现波斯日历的日期选择功能。希望这对你有帮助!

回到顶部