Flutter日期选择插件scrollable_date_picker的使用

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

Flutter日期选择插件scrollable_date_picker的使用

Scrollable Date Picker允许使用单日期、多日期和日期范围选择器。

此包依赖于super_sliver_list包,主要为了使用“滚动到项目”(滚动到初始日期)功能。同时,它也依赖于intl包,主要为了使用日期格式化功能。

开始使用

指令

  1. 打开命令行并进入你的项目根目录;
  2. 在你的pubspec.yaml文件中添加包依赖项(如下所示);
  3. 调用initializeDateFormatting()方法以加载适当的数据。
dependencies:
  scrollable_date_picker: ^1.2.1
import 'package:scrollable_date_picker/scrollable_date_picker.dart';
Future<void> main() async {
  await initializeDateFormatting();
  runApp(const MyApp());
}

使用

简单的使用示例:

ScrollableDatePicker(
  minDate: DateTime(DateTime.now().year - 2),
  maxDate: DateTime.now().copyWith(month: 12),
  onDateSelect: (singleDate, dates, dateRange,) {},
),

完整示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用scrollable_date_picker插件来实现单日期、多日期和日期范围选择器。

import 'dart:async';

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

Future<void> main() async {
  // 初始化日期格式化
  await initializeDateFormatting();

  runApp(const ScrollableDatePickerApp());
}

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

  [@override](/user/override)
  State<ScrollableDatePickerApp> createState() => _ScrollableDatePickerAppState();
}

class _ScrollableDatePickerAppState extends State<ScrollableDatePickerApp> {
  [@override](/user/override)
  Widget build(BuildContext context) => MaterialApp(
        title: 'Scrollable Date Picker',
        home: Builder(
            builder: (context) => Scaffold(
                  backgroundColor: Colors.grey[800],
                  body: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 250,
                          child: _ActionButton(
                            title: "单日期选择器",
                            color: Colors.red,
                            onTap: () => Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (_) => const _ScrollableDatePickerScreen(
                                  selectionType: DateSelectionType.singleDate,
                                ),
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(vertical: 15),
                          child: SizedBox(
                            width: 250,
                            child: _ActionButton(
                              title: "多日期选择器",
                              color: Colors.green,
                              onTap: () => Navigator.of(context).push(
                                MaterialPageRoute(
                                  builder: (_) => const _ScrollableDatePickerScreen(
                                    selectionType: DateSelectionType.multipleDates,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 250,
                          child: _ActionButton(
                            title: "日期范围选择器",
                            color: Colors.blue,
                            onTap: () => Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (_) => const _ScrollableDatePickerScreen(
                                  selectionType: DateSelectionType.dateRange,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                )),
      );
}

class _ScrollableDatePickerScreen extends StatefulWidget {
  final DateSelectionType selectionType;

  const _ScrollableDatePickerScreen({
    required this.selectionType,
  });

  [@override](/user/override)
  State<_ScrollableDatePickerScreen> createState() => _ScrollableDatePickerScreenState();
}

class _ScrollableDatePickerScreenState extends State<_ScrollableDatePickerScreen> {
  DateTime? _selectedSingleDate;
  List<DateTime>? _selectedDates;
  DateRangeModel? _dateRange;

  String get _selectedDatesText => _selectedDates is List<DateTime>
      ? "$_selectedDates"
      : _selectedSingleDate is DateTime
          ? "$_selectedSingleDate"
          : "${_dateRange?.startDate} - ${_dateRange?.endDate}";

  [@override](/user/override)
  Widget build(BuildContext context) => Scaffold(
        backgroundColor: Colors.grey[800],
        body: SafeArea(
          child: Stack(
            children: [
              SizedBox(
                child: ScrollableDatePicker(
                  datePickerPadding: const EdgeInsets.fromLTRB(10, 10, 10, 100),
                  minDate: DateTime(DateTime.now().year - 2),
                  maxDate: DateTime.now().copyWith(month: 12),
                  onDateSelect: (
                    singleDate,
                    dates,
                    dateRange,
                  ) {
                    setState(
                      () {
                        _selectedSingleDate = singleDate;
                        _selectedDates = dates;
                        _dateRange = dateRange;
                      },
                    );
                  },
                  dateSelectionType: widget.selectionType,
                  selectedDates: _selectedDates,
                  futureDatesAreAvailable: false,
                  initialDate: DateTime.now(),
                ),
              ),
              if (_selectedSingleDate is DateTime || _dateRange is DateRangeModel || _selectedDates is List<DateTime>)
                Positioned(
                  bottom: 20,
                  left: 20,
                  right: 20,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(
                        child: _ActionButton(
                          color: Colors.red,
                          title: "清除",
                          onTap: () => setState(
                            () {
                              _selectedSingleDate = null;
                              _selectedDates = null;
                              _dateRange = null;
                            },
                          ),
                        ),
                      ),
                      const SizedBox(width: 20),
                      Expanded(
                        child: _ActionButton(
                          color: Colors.green,
                          title: "选择",
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Column(
                                  children: [
                                    const Text(
                                      "已选日期:",
                                      textAlign: TextAlign.center,
                                    ),
                                    const SizedBox(height: 20),
                                    Text(
                                      _selectedDatesText,
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                )
            ],
          ),
        ),
      );
}

class _ActionButton extends StatelessWidget {
  final String title;
  final Color? color;
  final VoidCallback? onTap;

  const _ActionButton({
    required this.title,
    this.color,
    this.onTap,
  });

  [@override](/user/override)
  Widget build(BuildContext context) => MaterialButton(
        highlightElevation: 0,
        elevation: 0,
        color: color,
        onPressed: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Text(
            title,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      );
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用scrollable_date_picker插件的一个代码示例。scrollable_date_picker是一个流行的日期选择插件,允许用户滚动选择日期。

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

dependencies:
  flutter:
    sdk: flutter
  scrollable_date_picker: ^0.0.6  # 请确保使用最新版本号

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

接下来,在你的Dart文件中使用ScrollableDatePicker组件。以下是一个完整的示例,展示了如何在Flutter应用中使用这个插件:

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

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

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

class DatePickerScreen extends StatefulWidget {
  @override
  _DatePickerScreenState createState() => _DatePickerScreenState();
}

class _DatePickerScreenState extends State<DatePickerScreen> {
  DateTime _selectedDate = DateTime.now();

  void _onDateChanged(DateTime date) {
    setState(() {
      _selectedDate = date;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Scrollable Date Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Date: ${_selectedDate.toLocal()}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ScrollableDatePicker(
              dateTime: _selectedDate,
              onDateChanged: _onDateChanged,
              leftChild: Icon(
                Icons.arrow_back,
                color: Colors.grey,
              ),
              rightChild: Icon(
                Icons.arrow_forward,
                color: Colors.grey,
              ),
              isExpandable: true,
              onExpandChanged: (bool isExpanded) {
                print('Is Expanded: $isExpanded');
              },
              weekdayTextStyle: TextStyle(color: Colors.black),
              dayTextStyle: TextStyle(color: Colors.black),
              monthTextStyle: TextStyle(color: Colors.black),
              yearTextStyle: TextStyle(color: Colors.black),
              headerDecoration: BoxDecoration(
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖引入:在pubspec.yaml中添加了scrollable_date_picker依赖。
  2. 主应用MyApp是一个简单的Flutter应用,包含了一个DatePickerScreen作为首页。
  3. 日期选择屏幕DatePickerScreen是一个有状态的Widget,包含一个ScrollableDatePicker组件。
  4. 日期选择回调_onDateChanged函数会在日期改变时被调用,并更新状态中的_selectedDate
  5. 界面布局:使用Column布局,显示选中的日期和一个ScrollableDatePicker组件。

这个示例展示了如何使用scrollable_date_picker插件创建一个简单的日期选择器,并处理日期选择事件。你可以根据需要进一步自定义和扩展这个示例。

回到顶部