简体   繁体   English

Flutter 创建下拉月/年选择器

[英]Flutter Create Dropdown month/year selector

I want to create the month-year drop-down selector in the picture below and I need it to be inside the app bar.我想在下图中创建月-年下拉选择器,我需要它在应用程序栏中。 I am using Flutter.我正在使用颤振。 Are there any controls, or I have to write my own.是否有任何控件,或者我必须自己编写。 and how to start?以及如何开始? Thanks.谢谢。

月年选择器图像

I've been searching for the same thing as you.我一直在寻找和你一样的东西。 The screenshot you provided inspired me and I wrote it :) I placed it on the page, but you can place it in the bottom attribute of AppBar .你提供的截图启发了我,我写了它:) 我把它放在页面上,但你可以把它放在AppBarbottom属性中。 If enyone needs it - enjoy, but take it as example and finish it to be secure & stable.如果有人需要它 - 享受它,但以它为例并完成它以确保安全和稳定。

Here is the code of a full Scaffold widget (one of my pages).这是一个完整的Scaffold小部件(我的页面之一)的代码。

在此处输入图片说明

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

class Time extends StatefulWidget {
  @override
  _TimeState createState() => _TimeState();
}

class _TimeState extends State<Time> with SingleTickerProviderStateMixin {
  bool pickerIsExpanded = false;
  int _pickerYear = DateTime.now().year;
  DateTime _selectedMonth = DateTime(
    DateTime.now().year,
    DateTime.now().month,
    1,
  );

  dynamic _pickerOpen = false;

  void switchPicker() {
    setState(() {
      _pickerOpen ^= true;
    });
  }

  List<Widget> generateRowOfMonths(from, to) {
    List<Widget> months = [];
    for (int i = from; i <= to; i++) {
      DateTime dateTime = DateTime(_pickerYear, i, 1);
      final backgroundColor = dateTime.isAtSameMomentAs(_selectedMonth)
          ? Theme.of(context).accentColor
          : Colors.transparent;
      months.add(
        AnimatedSwitcher(
          duration: kThemeChangeDuration,
          transitionBuilder: (Widget child, Animation<double> animation) {
            return FadeTransition(
              opacity: animation,
              child: child,
            );
          },
          child: TextButton(
            key: ValueKey(backgroundColor),
            onPressed: () {
              setState(() {
                _selectedMonth = dateTime;
              });
            },
            style: TextButton.styleFrom(
              backgroundColor: backgroundColor,
              shape: CircleBorder(),
            ),
            child: Text(
              DateFormat('MMM').format(dateTime),
            ),
          ),
        ),
      );
    }
    return months;
  }

  List<Widget> generateMonths() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: generateRowOfMonths(1, 6),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: generateRowOfMonths(7, 12),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Material(
            color: Theme.of(context).cardColor,
            child: AnimatedSize(
              curve: Curves.easeInOut,
              vsync: this,
              duration: Duration(milliseconds: 300),
              child: Container(
                height: _pickerOpen ? null : 0.0,
                child: Column(
                  children: [
                    Row(
                      children: [
                        IconButton(
                          onPressed: () {
                            setState(() {
                              _pickerYear = _pickerYear - 1;
                            });
                          },
                          icon: Icon(Icons.navigate_before_rounded),
                        ),
                        Expanded(
                          child: Center(
                            child: Text(
                              _pickerYear.toString(),
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                        IconButton(
                          onPressed: () {
                            setState(() {
                              _pickerYear = _pickerYear + 1;
                            });
                          },
                          icon: Icon(Icons.navigate_next_rounded),
                        ),
                      ],
                    ),
                    ...generateMonths(),
                    SizedBox(
                      height: 10.0,
                    ),
                  ],
                ),
              ),
            ),
          ),
          SizedBox(
            height: 20.0,
          ),
          Text(DateFormat.yMMMM().format(_selectedMonth)),
          ElevatedButton(
            onPressed: switchPicker,
            child: Text(
              'Select date',
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

try this:尝试这个:

import 'package:flutter/material.dart';

class CustomDatePicker extends StatefulWidget {
  @override
  _CustomDatePickerState createState() => _CustomDatePickerState();
}

class _CustomDatePickerState extends State<CustomDatePicker> {
  DateTime selectedDate = DateTime.now();
  _buildMaterialDatePicker(BuildContext context) async {
  final DateTime picked = await showDatePicker(
    context: context,
    initialDate: selectedDate,
    firstDate: DateTime(2000),
    lastDate: DateTime(2025),
    initialEntryMode: DatePickerEntryMode.calendar,
    initialDatePickerMode: DatePickerMode.day,
    helpText: 'Choose date',
    cancelText: 'Cancel',
    confirmText: 'Save',
    errorFormatText: 'Invalid date format',
    errorInvalidText: 'Invalid date format',
    fieldLabelText: 'Start date',
    fieldHintText: 'Year/Month/Date',
    builder: (context, child) {
      return Theme(
        data: ThemeData.dark(),
        child: child,
      );
    },
  );
  if (picked != null && picked != selectedDate)
    setState(() {
      selectedDate = picked;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: GestureDetector(
              onTap: () {
              _buildMaterialDatePicker(context);
            },
            child: Text(
              "${selectedDate.toLocal()}".split(' ')[0] ?? 'Select Date',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

output:输出: date_picker_on_appbar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM