【问题标题】:What is the correct way to add date picker in flutter app?在颤振应用程序中添加日期选择器的正确方法是什么?
【发布时间】:2019-03-14 14:47:16
【问题描述】:

在我的应用程序中,我正在创建需要添加 DOB 的注册页面。我想在其中添加日期选择器,但我没有得到正确的方法来做到这一点。

【问题讨论】:

    标签: android ios flutter flutter-layout dart-2


    【解决方案1】:

    首先,您需要创建一个变量。在该变量中,您可以按如下方式存储所选日期:

    import 'package:flutter/material.dart';
    import 'package:intl/intl.dart'; //this is an external package for formatting date and time
    
    class DatePicker extends StatefulWidget {
      @override
      _DatePickerState createState() => _DatePickerState();
    }
    
    class _DatePickerState extends State<DatePicker> {
      DateTime _selectedDate;
    
      //Method for showing the date picker
      void _pickDateDialog() {
        showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                //which date will display when user open the picker
                firstDate: DateTime(1950),
                //what will be the previous supported year in picker
                lastDate: DateTime
                    .now()) //what will be the up to supported date in picker
            .then((pickedDate) {
          //then usually do the future job
          if (pickedDate == null) {
            //if user tap cancel then this function will stop
            return;
          }
          setState(() {
            //for rebuilding the ui
            _selectedDate = pickedDate;
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            RaisedButton(child: Text('Add Date'), onPressed: _pickDateDialog),
            SizedBox(height: 20),
            Text(_selectedDate == null //ternary expression to check if date is null
                ? 'No date was chosen!'
                : 'Picked Date: ${DateFormat.yMMMd().format(_selectedDate)}'),
          ],
        );
      }
    }
    

    第二个选项: 使用https://pub.dev/packages/date_time_picker 这个库可以使用另一个选项。您可以在您的小部件树中使用此库,并将选取的日期或时间作为字符串存储在变量中:

    首先,在 pubspec.yaml 中添加包,然后点击获取包。下面只给出一个日期选择的demo,具体实现可以在给定的包url中找到。

    import 'package:flutter/material.dart';
    
    import 'package:date_time_picker/date_time_picker.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
    
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Date Time'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String _selectedDate;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: DateTimePicker(
                    initialValue: '', // initialValue or controller.text can be null, empty or a DateTime string otherwise it will throw an error.
                    type: DateTimePickerType.date,
                    dateLabelText: 'Select Date',
                    firstDate: DateTime(1995),
                    lastDate: DateTime.now()
                        .add(Duration(days: 365)), // This will add one year from current date
                    validator: (value) {
                      return null;
                    },
                    onChanged: (value) {
                      if (value.isNotEmpty) {
                        setState(() {
                        _selectedDate = value;
                        });
                      }
                    },
                    // We can also use onSaved
                    onSaved: (value) {
                      if (value.isNotEmpty) {
                        _selectedDate = value;
                      }
                    },
                  ),
                ),
                SizedBox(height: 16),
                Text(
                  'Your Selected Date: $_selectedDate',
                  style: TextStyle(fontSize: 16),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案2】:
          DateTime _chosenDateTime;
      
         // Show the modal that contains the CupertinoDatePicker
          void _showDatePicker(context) {
          // showCupertinoModalPopup is a built-in function of the cupertino library
         showCupertinoModalPopup(
         context: context,
         builder: (_) => Container(
        height: 500,
        color: Color.fromARGB(255, 255, 255, 255),
        child: Column(
          children: [
            Container(
              height: 400,
              child: CupertinoDatePicker(
                  initialDateTime: DateTime.now(),
                  onDateTimeChanged: (val) {
                    setState(() {
                      _chosenDateTime = val;
                    });
                  }),
              ),
             ],
           ),
        ));
      

      【讨论】:

        【解决方案3】:

        这是适用于 Android 和 iOS 的现代且流行的日期时间选择器。

           DateTime _chosenDateTime;
        
           // Show the modal that contains the CupertinoDatePicker
             void _showDatePicker(ctx) {
             // showCupertinoModalPopup is a built-in function of the cupertino library
            showCupertinoModalPopup(
            context: ctx,
            builder: (_) => Container(
              height: 500,
              color: Color.fromARGB(255, 255, 255, 255),
              child: Column(
                children: [
                  Container(
                    height: 400,
                    child: CupertinoDatePicker(
                        initialDateTime: DateTime.now(),
                        onDateTimeChanged: (val) {
                          setState(() {
                            _chosenDateTime = val;
                          });
                        }),
                  ),
        
                  // Close the modal
                  CupertinoButton(
                    child: Text('OK'),
                    onPressed: () => Navigator.of(ctx).pop(),
                  )
                ],
              ),
            ));
         [More details][2]
        

        【讨论】:

          【解决方案4】:

          Flutter 提供了showDatePicker 函数来实现这一点。它是颤振材料库的一部分。

          您可以在 showDatePicker 找到完整的文档。

          你也可以在这里找到实现的例子:Date and Time Picker

          【讨论】:

          • 示例链接是 404。请考虑更新它。
          【解决方案5】:

          这也是一个很好的方法:

            import 'package:flutter/material.dart';
            import 'dart:async';
          
            void main() => runApp(new MyApp());
          
            class MyApp extends StatelessWidget {
              // This widget is the root of your application.
              @override
              Widget build(BuildContext context) {
                return new MaterialApp(
                  title: 'Flutter Demo',
                  theme: new ThemeData(
                    primarySwatch: Colors.blue,
                  ),
                  home: new MyHomePage(title: 'Flutter Date Picker Example'),
                );
              }
            }
          
            class MyHomePage extends StatefulWidget {
              MyHomePage({Key key, this.title}) : super(key: key);
              final String title;
              @override
              _MyHomePageState createState() => new _MyHomePageState();
            }
          
            class _MyHomePageState extends State<MyHomePage> {
              var finaldate;
          
              void callDatePicker() async {
                var order = await getDate();
                setState(() {
                  finaldate = order;
                });
              }
          
              Future<DateTime> getDate() {
                // Imagine that this function is
                // more complex and slow.
                return showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate: DateTime(2018),
                  lastDate: DateTime(2030),
                  builder: (BuildContext context, Widget child) {
                    return Theme(
                      data: ThemeData.light(),
                      child: child,
                    );
                  },
                );
              }
          
              @override
              Widget build(BuildContext context) {
                return new Scaffold(
                  appBar: new AppBar(
                    title: new Text(widget.title),
                  ),
                  body: new Center(
                    child: new Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          decoration: BoxDecoration(color: Colors.grey[200]),
                          padding: EdgeInsets.symmetric(horizontal: 30.0),
                          child: finaldate == null
                              ? Text(
                                  "Use below button to Select a Date",
                                  textScaleFactor: 2.0,
                                )
                              : Text(
                                  "$finaldate",
                                  textScaleFactor: 2.0,
                                ),
                        ),
                        new RaisedButton(
                          onPressed: callDatePicker,
                          color: Colors.blueAccent,
                          child:
                              new Text('Click here', style: TextStyle(color: Colors.white)),
                        ),
                      ],
                    ),
                  ),
                );
              }
            }
          

          这是来自https://fluttercentral.com/Articles/Post/1199/Flutter_DatePicker_Example

          【讨论】:

            【解决方案6】:

            一个展示其用途的简单应用:

            import 'dart:async';
            
            import 'package:flutter/material.dart';
            
            void main() => runApp(MyApp());
            
            class MyApp extends StatelessWidget {
              @override
              Widget build(BuildContext context) {
                return MaterialApp(
                  title: 'Flutter Demo',
                  home: MyHomePage(title: 'Flutter Demo Home Page'),
                );
              }
            }
            
            class MyHomePage extends StatefulWidget {
              MyHomePage({Key key, this.title}) : super(key: key);
            
              final String title;
            
              @override
              _MyHomePageState createState() => _MyHomePageState();
            }
            
            class _MyHomePageState extends State<MyHomePage> {
              DateTime selectedDate = DateTime.now();
            
              Future<void> _selectDate(BuildContext context) async {
                final DateTime picked = await showDatePicker(
                    context: context,
                    initialDate: selectedDate,
                    firstDate: DateTime(2015, 8),
                    lastDate: DateTime(2101));
                if (picked != null && picked != selectedDate)
                  setState(() {
                    selectedDate = picked;
                  });
              }
            
              @override
              Widget build(BuildContext context) {
                return Scaffold(
                  appBar: AppBar(
                    title: Text(widget.title),
                  ),
                  body: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Text("${selectedDate.toLocal()}".split(' ')[0]),
                        SizedBox(height: 20.0,),
                        RaisedButton(
                          onPressed: () => _selectDate(context),
                          child: Text('Select date'),
                        ),
                      ],
                    ),
                  ),
                );
              }
            }
            

            还有一个飞镖盘:

            https://dartpad.dev/e5a99a851ae747e517b75ac221b73529

            【讨论】:

            • 如何去掉我只想要日期的时间?
            • 您可以根据年份、月份和日期创建自己的版本,也可以使用以下Text("${selectedDate.toLocal()}".split(' ')[0]),
            • 您也可以从以下位置删除 Future
            • 我已将其更改为Future&lt;void&gt;。因为它是一个不返回任何内容的async 函数,所以与其返回void,不如返回Future&lt;void&gt; 更正确
            【解决方案7】:

            简单的方法是使用CupertinoDatePicker类:

            首先导入它在flutter中构建的包:

            import 'package:flutter/cupertino.dart';
            

            然后在表单中添加这个小部件:

                        Container(
                          height: 200,
                          child: CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.date,
                            initialDateTime: DateTime(1969, 1, 1),
                            onDateTimeChanged: (DateTime newDateTime) {
                              // Do something
                            },
                          ),
                        ),
            

            结果将如下图:

            您还可以将模式更改为 (dateAndTime,time)...例如 dateAndTime 模式:

                        Container(
                          height: 200,
                          child: CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.dateAndTime,
                            initialDateTime: DateTime(1969, 1, 1, 11, 33),
                            onDateTimeChanged: (DateTime newDateTime) {
                              //Do Some thing
                            },
                            use24hFormat: false,
                            minuteInterval: 1,
                          ),
                        ),
            

            结果将如下图:

            【讨论】:

            • 如何在点击按钮时打开第一张图片的代码并在文本字段中设置值?
            • 应该是公认的答案。在 Flutter 中以本地方式将日期和时间纠察在一起的唯一方法。
            【解决方案8】:

            时间选择器-

            在类级别声明这个变量

            TimeOfDay selectedTime =TimeOfDay.now();
            

            并调用此方法:-

            Future<Null> _selectTime(BuildContext context) async {
                final TimeOfDay picked_s = await showTimePicker(
                    context: context,
                    initialTime: selectedTime, builder: (BuildContext context, Widget child) {
                       return MediaQuery(
                         data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
                        child: child,
                      );});
            
                if (picked_s != null && picked_s != selectedTime )
                  setState(() {
                    selectedTime = picked_s;
                  });
              }
            

            【讨论】:

              猜你喜欢
              • 2020-11-23
              • 2019-02-20
              • 2021-02-28
              • 2021-12-27
              • 1970-01-01
              • 1970-01-01
              • 2021-12-07
              • 2018-10-08
              • 2016-07-26
              相关资源
              最近更新 更多