简体   繁体   English

如何在flutter中使用showTimePicker作为Widget?

[英]How to use showTimePicker as Widget in flutter?

I want the user to pick the date and time, for that there is date time picker dialogue.我希望用户选择日期和时间,因为有日期时间选择器对话框。

But, is there a way that, I could show the date-time persistently on some flutter widget and use like any other widget?但是,有没有一种方法可以让我在某些颤动小部件上持续显示日期时间并像任何其他小部件一样使用?

Container(
   child: showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
          builder: (BuildContext context, Widget child) {
            return Theme(
              data: ThemeData.dark(),
              child: child,
            );
          },
        );
}

but I cannot use showTimePicker as Widget.但我不能使用showTimePicker作为 Widget。

How to use showTimePicker() as widget?如何使用showTimePicker()作为小部件? so that other widgets can be built on top of it.以便其他小部件可以构建在它之上。

I ran into the problem just like you some time ago and I copied the source code and made my custom widget.前段时间我和你一样遇到了这个问题,我复制了源代码并制作了我的自定义小部件。 Now, it can be used like any widget.现在,它可以像任何小部件一样使用。 If you want to adopt this, I want to mention a couple of things.如果你想采用这一点,我想提几点。

  1. I am not sure if this works well with localization, I did not test that.我不确定这是否适用于本地化,我没有测试过。
  2. I am not sure if this works on other themes than the light theme, I only tested on the light theme.我不确定这是否适用于轻主题以外的其他主题,我只在轻主题上进行了测试。

You can find the code here.你可以在这里找到代码。 https://gist.github.com/mithunadhikari40/b55b9990ebc15d0d8bf70fd3f87709b0 https://gist.github.com/mithunadhikari40/b55b9990ebc15d0d8bf70fd3f87709b0

Usage: Copy the code from the above link, create a dart file, paste the code and use it like this:使用方法:从上面的链接复制代码,创建一个dart文件,粘贴代码并像这样使用它:

                     SizedBox(
                        child: TimePickerDialog(
                        initialTime: TimeOfDay.fromDateTime(DateTime.now()),
                        onTimeChange: (TimeOfDay time) {
                          print(
                              "What we get the value of the time is now $time");
                        },
                      ),
                    ),

You have to open showTimePicker on click of any widget.您必须在单击任何小部件时打开showTimePicker So you can simply put your code of showTimePicker inside onTap property of the GestureDetector as shown below.因此,您可以简单地将showTimePicker的代码放在GestureDetector onTap 属性中,如下所示。

GestureDetector(
    onTap: () async {
        TimeOfDay picked = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.now(),
        builder: (BuildContext context, Widget child) {
           return MediaQuery(
           data: MediaQuery.of(context)
           .copyWith(alwaysUse24HourFormat: true),
           child: child,
           );
        },);
     },
     child: Text("SetTime",textAlign: TextAlign.center,));

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

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