如何将flutter datepicker值放到文本域中?

sycxhyv7  于 2023-01-18  发布在  Flutter
关注(0)|答案(4)|浏览(145)

如何获得flutter日期选择器值的文本字段?当我点击文本字段,它是弹出日期选择器后,选择日期。我想在文本字段中的日期
也是。
我想自定义日期选择器的颜色

onTap: () {
       FocusScope.of(context).requestFocus(new FocusNode());
       showDatePicker(
       context: context,
       initialDate: DateTime.now(),
       firstDate: DateTime(2019, 1),
       lastDate: DateTime(2021,12),
        );
       },
ijnw1ujt

ijnw1ujt1#

我修复你的代码如下(你可以选择日期从DatePicker,你可以自定义主题的DatePicker):

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

class TestPickerWidget extends StatefulWidget {
  @override
  _TestPickerWidgetState createState() => _TestPickerWidgetState();
}

class _TestPickerWidgetState extends State<TestPickerWidget> {
  DateTime _selectedDate;
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextField(
          focusNode: AlwaysDisabledFocusNode(),
          controller: _textEditingController,
          onTap: () {
            _selectDate(context);
          },
        ),
      ),
    );
  }

  _selectDate(BuildContext context) async {
    DateTime newSelectedDate = await showDatePicker(
        context: context,
        initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
        firstDate: DateTime(2000),
        lastDate: DateTime(2040),
        builder: (BuildContext context, Widget child) {
          return Theme(
            data: ThemeData.dark().copyWith(
              colorScheme: ColorScheme.dark(
                primary: Colors.deepPurple,
                onPrimary: Colors.white,
                surface: Colors.blueGrey,
                onSurface: Colors.yellow,
              ),
              dialogBackgroundColor: Colors.blue[500],
            ),
            child: child,
          );
        });

    if (newSelectedDate != null) {
      _selectedDate = newSelectedDate;
      _textEditingController
        ..text = DateFormat.yMMMd().format(_selectedDate)
        ..selection = TextSelection.fromPosition(TextPosition(
            offset: _textEditingController.text.length,
            affinity: TextAffinity.upstream));
    }
  }
}

class AlwaysDisabledFocusNode extends FocusNode {
  @override
  bool get hasFocus => false;
}

并且您还必须在pubspec.yaml中添加Intl依赖项:

dev_dependencies:
  flutter_test:
    sdk: flutter
  intl: ^0.16.1

最后在main中调用TestPickerWidget进行测试。

wfsdck30

wfsdck302#

试试这个。首先,你需要定义一个文本编辑控制器。然后你可以访问那个控制器来设置所选的日期。
这是可自定义的日期选择器。

showDatePicker(
  context: context,
  initialDate: DateTime.now(),
  firstDate: DateTime(2019, 1),
  lastDate: DateTime(2021,12),
  builder: (context,picker){
    return Theme(
    //TODO: change colors
    data: ThemeData.dark().copyWith(
      colorScheme: ColorScheme.dark(
        primary: Colors.deepPurple,
        onPrimary: Colors.white,
        surface: Colors.pink,
        onSurface: Colors.yellow,
      ),
      dialogBackgroundColor:Colors.green[900],
     ),
     child: picker!,);
   })
   .then((selectedDate) {
     //TODO: handle selected date
     if(selectedDate!=null){
       _controller.text = selectedDate.toString();
     }
 });

You can try this live preview .

mutmk8jj

mutmk8jj3#

你可以这样使用

showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(2019, 1),
                lastDate: DateTime(2021, 12),
              ).then((pickedDate) {
                //do whatever you want
              });
qzlgjiam

qzlgjiam4#

像这样从showDatePicker得到时间

  • 首先,设置DateTime? _dateTime;
  • 接下来像这样调用showDatePicker
showDatePicker(
              builder: (context, child) {
                return Theme(
                  data: Theme.of(context).copyWith(
                    colorScheme: ColorScheme.light(
                      primary: darkblueColor, // header background color
                      onPrimary: whiteColor, // header text color
                      onSurface: darkblueColor, // body text color
                    ),
                    textButtonTheme: TextButtonThemeData(
                      style: TextButton.styleFrom(
                        primary: darkblueColor, // button text color
                      ),
                    ),
                  ),
                  child: child!,
                );
              },
              context: context,
              initialDate: DateTime(2006), //current showing date
              firstDate: DateTime(1943), // start date
              lastDate: DateTime(2006), // ending year
            ).then((date) {
              if (date == null) {
                print("not selected");
              } else {
                setState(() {
                  _dateTime = date; // this will update _dateTime
                });
              }
            });
  • 现在,您可以在TextField中使用_dateTime。

此外,
要将所选日期与当前日期进行比较吗?

  • 设置上面的值为date(在第三行)。下面的函数将帮助你。
readTimestamp() {
  var now = DateTime.now();
  var date = yourTime; // <-- add it to this
  String formattedDate = DateFormat.yMMMEd().format(date.toDate());
  var diff = now.difference(date.toDate()); 
  var time = '';

  if (diff.inDays <= 1) {
    time = "Today";
  }
  if (diff.inDays == 2) {
    time = "Yesterday";
  }
  if (diff.inDays > 2 && diff.inDays / 7 <= 1) {
    time = "This week";
  }
  if (diff.inDays / 7 > 1 && diff.inDays / 7 <= 2) {
    time = "Last Week";
  }
  if (diff.inDays / 7 > 2 && diff.inDays / 7 <= 3) {
    time = "3 Weeks ago";
  }
  if (diff.inDays / 7 > 3) {
    time = formattedDate;
  }
  return time;
}

相关问题