Flutter自定义月份选择器插件flutter_custom_month_picker的使用

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

Flutter Custom Month Picker

A Flutter package for selecting a month and year using a dialog.

Usage

To use this package, add flutter_custom_month_picker as a dependency in your pubspec.yaml file.

dependencies:
  flutter_custom_month_picker: ^1.0.0

Example

Below is a complete demo that demonstrates how to use the flutter_custom_month_picker package:

Full Demo Code

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int month = DateTime.now().month;
  int year = DateTime.now().year;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Month Picker Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                showMonthPicker(
                  context,
                  onSelected: (selectedMonth, selectedYear) {
                    if (kDebugMode) {
                      print('Selected month: $selectedMonth, year: $selectedYear');
                    }
                    setState(() {
                      month = selectedMonth;
                      year = selectedYear;
                    });
                  },
                  initialSelectedMonth: month,
                  initialSelectedYear: year,
                  firstEnabledMonth: 1,
                  lastEnabledMonth: 12,
                  firstYear: 2000,
                  lastYear: 2050,
                  selectButtonText: 'OK',
                  cancelButtonText: 'Cancel',
                  highlightColor: Colors.purple,
                  textColor: Colors.black,
                  contentBackgroundColor: Colors.white,
                  dialogBackgroundColor: Colors.grey[200],
                );
              },
              child: const Text('Show Month Picker'),
            ),
            Text('Selected month: $month, year: $year')
          ],
        ),
      ),
    );
  }
}

Arguments

The showMonthPicker function accepts several arguments to customize its behavior and appearance:

Argument Type Description
context BuildContext The context in which to show the dialog.
onSelected Function Called when a month is selected. Receives the selected month and year.
initialSelectedMonth int The initial month to select. Defaults to the current month.
initialSelectedYear int The initial year to select. Defaults to the current year.
firstYear int The first year that can be selected. Defaults to 1900.
lastYear int The last year that can be selected. Defaults to the current year.
firstEnabledMonth int The first month of the first year that can be selected. Defaults to 1.
lastEnabledMonth int The last month of the last year that can be selected. Defaults to 12.
selectButtonText String The text for the “OK” button. Defaults to ‘OK’.
cancelButtonText String The text for the “Cancel” button. Defaults to ‘Cancel’.
highlightColor Color The highlight color for the selected month and year. Also affects the ‘OK’ button. Defaults to green.
textColor Color The color of the text. Defaults to black.
contentBackgroundColor Color The background color of the dialog content. Defaults to white.
dialogBackgroundColor Color The background color of the dialog. Defaults to light grey.

Screenshots

Screenshot 1 Screenshot 2

Contributing

Contributions are welcome! Please feel free to file an issue or submit a pull request.


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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用flutter_custom_month_picker插件的示例代码。这个插件允许你创建一个自定义的月份选择器。请注意,为了运行以下代码,你需要先确保在pubspec.yaml文件中添加了flutter_custom_month_picker依赖。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加flutter_custom_month_picker依赖:

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

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

2. 导入插件并创建UI

在你的Dart文件中,导入flutter_custom_month_picker并创建一个自定义月份选择器。以下是一个完整的示例:

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

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Custom Month Picker Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedMonth == null
                  ? 'Select a month'
                  : '${selectedMonth!.year}-${selectedMonth!.month.toString().padLeft(2, '0')}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                final DateTime? pickedMonth = await showMonthPicker(
                  context: context,
                  initialDate: selectedMonth ?? DateTime.now(),
                  firstDate: DateTime(2000),
                  lastDate: DateTime(2100),
                  locale: Localizations.localeOf(context),
                );
                if (pickedMonth != null && pickedMonth != selectedMonth) {
                  setState(() {
                    selectedMonth = pickedMonth;
                  });
                }
              },
              child: Text('Select Month'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 运行应用

将上述代码添加到你的主Dart文件中(通常是lib/main.dart),然后运行你的Flutter应用。你将看到一个按钮,点击按钮后会弹出一个月份选择器,选择月份后,选择的月份会显示在按钮上方。

解释

  • 依赖导入:通过import 'package:flutter_custom_month_picker/flutter_custom_month_picker.dart';导入插件。
  • 状态管理:使用_MyHomePageState类中的selectedMonth变量来存储用户选择的月份。
  • UI布局:使用Column布局来组织文本和按钮。
  • 显示月份选择器:使用showMonthPicker函数来显示月份选择器,并在用户选择月份后更新UI。

这个示例展示了如何使用flutter_custom_month_picker插件创建一个基本的月份选择器界面。根据具体需求,你可以进一步自定义和扩展这个界面。

回到顶部