Flutter日期选择插件week_day_picker的使用

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

Flutter日期选择插件week_day_picker的使用

week_day_picker是一个用于在Flutter应用中显示日历并允许用户选择日期的插件。它以周视图模式显示日历,并返回用户选择的日期或取消操作的结果。

安装

首先,将week_day_picker添加到您的pubspec.yaml文件中作为依赖项:

dependencies:
  week_day_picker: ^1.1.5

然后运行flutter pub get来安装该插件。

使用

导入包

在使用之前,请确保导入了week_day_picker包:

import 'package:week_day_picker/week_day_picker.dart';

基本用法

创建一个WeekDayPicker实例并调用show方法。请注意,您需要等待用户的响应:

var weekDayPicker = WeekDayPicker(
    context: context,
    firstDate: DateTime(2021, 1, 13),
    lastDate: DateTime(2023, 10, 19),
);
DateTime? selectedDate = await weekDayPicker.show();

设置当前日期

默认情况下,当前日期是系统的日期。您可以使用currentDate参数来设置要高亮显示的日期:

var weekDayPicker = WeekDayPicker(
    context: context,
    firstDate: DateTime(2021),
    lastDate: DateTime(2023),
    currentDate: DateTime(2022, 10, 1),
);

设置初始选中日期

使用initialDate参数可以设置初始选中的日期(不要与currentDate混淆):

var weekDayPicker = WeekDayPicker(
    context: context,
    firstDate: DateTime(2021, 1, 13),
    lastDate: DateTime(2023, 10, 19),
    initialDate: DateTime(2022, 10, 1),
);

设置可选日期

通过selectableDay参数指定哪些日期是可以被选择的:

WeekDayPicker(
    ...
    selectableDay: [
        DateTime(2022, 9, 12),
        DateTime(2022, 9, 21)
    ],
);

或者,使用selectableDayInWeek参数仅允许选择特定星期几的日期(如周一和周五):

WeekDayPicker(
    ...
    selectableDayInWeek: [1, 5], // 1代表周一,5代表周五
);

合并条件

如果需要同时使用selectableDayselectableDayInWeek,可以通过selectableBitwiseOperator参数指定逻辑运算符:

  • BitwiseOperator.or:表示或运算
  • BitwiseOperator.and:表示与运算

示例代码如下:

var response = await WeekDayPicker(
   context: context,
   initialDate: DateTime.now(),
   firstDate: DateTime(2021, 1, 13),
   lastDate: DateTime(2023, 10, 19),
   selectableDay: [
       DateTime(2022, 9, 12),
       DateTime(2022, 9, 21)
   ],
   selectableDayInWeek: [1, 5],
   selectableBitwiseOperator: BitwiseOperator.or,
).show();

国际化

通过传递上下文,对话框会使用应用程序的默认区域设置。如果需要更改语言,可以使用locale参数:

var response = WeekDayPicker(
    context: context,
    firstDate: DateTime(2021, 1, 13),
    lastDate: DateTime(2023, 10, 19),
    locale: const Locale('en', ''),
).show();

主题定制

可以通过以下参数自定义对话框的主题:

  • colorHeader: 标题背景色
  • colorOnHeader: 标题文字颜色
  • colorIcon: 图标颜色(上一周和下一周按钮)
  • colorDisabled: 禁用日期的文字颜色和图标颜色
  • colorSelected: 选中日期的背景色
  • colorOnSelected: 选中日期的文字颜色
  • backgroundColor: 表面背景色

示例代码如下:

var dayWeekPicker = WeekDayPicker(
    context: context,
    initialDate: DateTime.now(),
    currentDate: DateTime.now().add(const Duration(days: -3)),
    firstDate: DateTime.now().add(const Duration(days: -356)),
    lastDate: DateTime.now().add(const Duration(days: 356)),
    colorHeader: Colors.blue[700],
    colorOnHeader: Colors.blue[100],
    colorIcon: Colors.blueAccent[200],
    colorDisabled: Colors.blueGrey[100],
    colorSelected: Colors.blue[800],
    colorOnSelected: Colors.lightBlue[100],
);

示例Demo

下面是一个完整的示例代码,展示了如何在Flutter应用中使用week_day_picker插件:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:week_day_picker/week_day_picker.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late ThemeMode theme;

  @override
  void initState() {
    super.initState();
    theme = ThemeMode.light;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Week day picker Demo',
      themeMode: theme,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF00b266),
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF00b266),
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: MyHomePage(
        title: 'Week day picker Demo',
        isDark: theme == ThemeMode.dark,
        callback: () {
          setState(() {
            theme = (theme == ThemeMode.dark) ? ThemeMode.light : ThemeMode.dark;
          });
        },
      ),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('fr', ''),
        Locale('ar', ''),
        Locale('es', ''),
        Locale('de', ''),
        Locale('it', ''),
      ],
      locale: const Locale('en'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final bool isDark;
  final VoidCallback callback;

  const MyHomePage({
    super.key,
    required this.title,
    required this.isDark,
    required this.callback,
  });

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

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

  @override
  Widget build(BuildContext context) {
    DateTime firstDate = DateTime.now().add(const Duration(days: -356));
    DateTime lastDate = DateTime.now().add(const Duration(days: 356));

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: [
          IconButton(
            icon: Icon(widget.isDark ? Icons.light_mode_rounded : Icons.dark_mode_rounded),
            tooltip: 'Theme',
            onPressed: widget.callback,
          ),
          const SizedBox(width: 30),
        ],
      ),
      body: Center(
        child: ListView(
          children: <Widget>[
            Center(
              child: Text(
                (selectedDate != null)
                    ? 'Selected Date: ${selectedDate.toString().substring(0, 10)}'
                    : 'Select a date',
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
            const SizedBox(height: 10),
            Center(
              child: ElevatedButton(
                onPressed: () async {
                  var dayWeekPicker = WeekDayPicker(
                    context: context,
                    firstDate: firstDate,
                    lastDate: lastDate,
                    initialDate: selectedDate,
                  );
                  var response = await dayWeekPicker.show();
                  setState(() {
                    selectedDate = response;
                  });
                },
                child: const Text('Simple Week Day'),
              ),
            ),
            // 其他按钮示例省略...
          ],
        ),
      ),
    );
  }
}

以上代码展示了一个简单的Flutter应用,其中包含多个按钮,每个按钮演示了week_day_picker的不同功能。您可以根据自己的需求进一步修改和完善。


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

1 回复

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


当然,关于week_day_picker这个Flutter日期选择插件的使用,下面是一个基本的代码示例,展示了如何在Flutter应用中集成并使用这个插件来选择星期几。

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

dependencies:
  flutter:
    sdk: flutter
  week_day_picker: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  DateTime? selectedDay;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Week Day Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedDay == null
                  ? 'No day selected'
                  : 'Selected Day: ${selectedDay!.weekday}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate: DateTime(DateTime.now().year - 1),
                  lastDate: DateTime(DateTime.now().year + 1),
                ).then((selectedDate) {
                  if (selectedDate != null && selectedDate != selectedDay) {
                    setState(() {
                      selectedDay = selectedDate;
                    });
                    // Use WeekDayPicker to get the selected weekday
                    final WeekDayPicker weekDayPicker = WeekDayPicker();
                    final String weekday = weekDayPicker.getWeekDay(selectedDate);
                    print('Selected weekday: $weekday');
                  }
                });
              },
              child: Text('Select Date'),
            ),
          ],
        ),
      ),
    );
  }
}

// 假设WeekDayPicker类是这样定义的(实际上这个类来自week_day_picker插件,这里只是为了展示如何调用)
class WeekDayPicker {
  String getWeekDay(DateTime date) {
    switch (date.weekday) {
      case DateTime.monday:
        return 'Monday';
      case DateTime.tuesday:
        return 'Tuesday';
      case DateTime.wednesday:
        return 'Wednesday';
      case DateTime.thursday:
        return 'Thursday';
      case DateTime.friday:
        return 'Friday';
      case DateTime.saturday:
        return 'Saturday';
      case DateTime.sunday:
        return 'Sunday';
      default:
        return '';
    }
  }
}

// 注意:实际上,week_day_picker插件可能提供了更直接的方法来获取星期几,
// 这里只是为了展示如何基于日期对象获取星期几。你应该参考插件的官方文档来使用正确的方法。

注意

  1. 上面的WeekDayPicker类只是为了展示如何基于DateTime对象获取星期几,实际上week_day_picker插件可能已经提供了这样的功能,你应该参考插件的官方文档来使用正确的方法。
  2. showDatePicker是Flutter自带的日期选择器,它返回选中的日期。你需要使用这个日期结合week_day_picker插件来获取星期几。
  3. 由于week_day_picker插件的具体API可能有所不同,因此你可能需要参考插件的README或官方文档来调整代码。

确保你查阅了week_day_picker插件的最新文档,以获取最准确的使用方法。

回到顶部