获取选定的时间 – TimePickerDialog in Flutter

huangapple go评论65阅读模式
英文:

flutter TimePickerDialog get selected Time -

问题

如何在Flutter中获取TimePickerDialog的选定时间?
我不想使用showDialog,因为我想在TimePickerDialog下方添加一些其他按钮。如果无法使用TimePickerDialog,那么应该如何做呢?在本地工作区中使用Timepickerdialog的源代码并在那里更新吗?
我像这样使用它:

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      actions: <Widget>[
        SizedBox(
          child: TimePickerDialog(
            initialTime: TimeOfDay.fromDateTime(DateTime.now()),
            cancelText: "",
            confirmText: "", 
          ),
        ),
        TextButton(
          child: Text('Cancel'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: Text('OK'),
          onPressed: () {
            // 执行一个操作
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
);

获取选定的时间 – TimePickerDialog in Flutter

英文:

how can I get the selected time of TimePickerDialog in Flutter?
I dont want to use showDialog because I want to add some other buttons below the TimePickerDialog. When it is not possible to use the TimePickerDialog then what would be the way to do it? Use the sourcecode of Timepickerdialog in my local workspace and update it there?
I am using it like this:

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      actions: &lt;Widget&gt;[
        SizedBox(
          child: TimePickerDialog(
            initialTime: TimeOfDay.fromDateTime(DateTime.now()),
            cancelText: &quot;&quot;,
            confirmText: &quot;&quot;, 
          ),
        ),
        TextButton(
          child: Text(&#39;Cancel&#39;),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: Text(&#39;OK&#39;),
          onPressed: () {
            // Perform an action
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
);

获取选定的时间 – TimePickerDialog in Flutter

答案1

得分: 1

根据官方文档此处showDialog 返回的值是用户点击“确定”按钮时选定的 TimeOfDay,如果用户点击“取消”按钮则返回 null。

因此,您需要使用 await 关键字来调用 showDialog

final selectedTime = await showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      actions: <Widget>[
        SizedBox(
          child: TimePickerDialog(
            initialTime: TimeOfDay.fromDateTime(DateTime.now()),
            cancelText: "",
            confirmText: "", 
          ),
        ),
        TextButton(
          child: Text('取消'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: Text('确定'),
          onPressed: () {
            // 执行操作
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
);

英文:

According to the official docs here, the value returned by showDialog is the selected TimeOfDay if the user taps the "OK" button, or null if the user taps the "CANCEL" button.

So you need to call the showDialog with the await keyword.

final selectedTime = await showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      actions: &lt;Widget&gt;[
        SizedBox(
          child: TimePickerDialog(
            initialTime: TimeOfDay.fromDateTime(DateTime.now()),
            cancelText: &quot;&quot;,
            confirmText: &quot;&quot;, 
          ),
        ),
        TextButton(
          child: Text(&#39;Cancel&#39;),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: Text(&#39;OK&#39;),
          onPressed: () {
            // Perform an action
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
);

答案2

得分: 1

以下是您要翻译的部分:

"解决这个问题很简单,我们只需要在timer_picker.dart文件中进行一些更改。

通过将鼠标悬停在TimePickerDialog小部件上并按住CTRL键并单击它来打开timer_picker.dart文件,这将打开timer_picker。在该文件中滚动到第2415行。然后只需复制粘贴我下面添加的代码。保存文件后,热重新启动应用程序。

注意:与timerPicker小部件相关的任何UI或功能更改都需要在timer_picker.dart文件中更改

完整代码:-

UI代码:-

import 'package:flutter/material.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 Box(),
    );
  }
}

class Box extends StatefulWidget {
  const Box({super.key});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  var timeVal = TimeOfDay.fromDateTime(DateTime.now());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: GestureDetector(
      onTap: () async {
        timeVal = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return TimePickerDialog(
              initialTime: timeVal,
              cancelText: "",
              confirmText: "",
            );
          },
        );
        setState(() {});
      },
      child: Text(
        "Time: - ${timeVal.format(context)}",
        style: const TextStyle(fontSize: 25),
      ),
    ))));
  }
}

timer_picker.dart代码:-

return AlertDialog(
  actions: <Widget>[
    SizedBox(
        height: 500,
        width: 500,
        child: WillPopScope(
            onWillPop: () {
              _handleOk();
              return Future.value(false);
            },
            child: Dialog(
              shape: shape,
              elevation: pickerTheme.elevation ?? defaultTheme.elevation,
              backgroundColor: pickerTheme.backgroundColor ??
                  defaultTheme.backgroundColor,
              insetPadding: EdgeInsets.symmetric(
                horizontal: 16,
                vertical: (_entryMode.value == TimePickerEntryMode.input ||
                        _entryMode.value == TimePickerEntryMode.inputOnly)
                    ? 0
                    : 24,
              ),
              child: Padding(
                padding: pickerTheme.padding ?? defaultTheme.padding,
                child: LayoutBuilder(builder:
                    (BuildContext context, BoxConstraints constraints) {
                  final Size constrainedSize =
                      constraints.constrain(dialogSize);
                  final Size allowedSize = Size(
                    constrainedSize.width < minDialogSize.width
                        ? minDialogSize.width
                        : constrainedSize.width,
                    constrainedSize.height < minDialogSize.height
                        ? minDialogSize.height
                        : constrainedSize.height,
                  );
                  return SingleChildScrollView(
                    restorationId: 'time_picker_scroll_view_horizontal',
                    scrollDirection: Axis.horizontal,
                    child: SingleChildScrollView(
                      restorationId: 'time_picker_scroll_view_vertical',
                      child: AnimatedContainer(
                        width: allowedSize.width,
                        height: allowedSize.height,
                        duration: _kDialogSizeAnimationDuration,
                        curve: Curves.easeIn,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Expanded(
                              child: Form(
                                key: _formKey,
                                autovalidateMode: _autovalidateMode.value,
                                child: _TimePicker(
                                  time: widget.initialTime,
                                  onTimeChanged: _handleTimeChanged,
                                  helpText: widget.helpText,
                                  cancelText: widget.cancelText,
                                  confirmText: widget.confirmText,
                                  errorInvalidText: widget.errorInvalidText,
                                  hourLabelText: widget.hourLabelText,
                                  minuteLabelText: widget.minuteLabelText,
                                  restorationId: 'time_picker',
                                  entryMode: _entryMode.value,
                                  orientation: widget.orientation,
                                  onEntryModeChanged:
                                      _handleEntryModeChanged,
                                ),
                              ),
                            ),
                            actions,
                          ],
                        ),
                      ),
                    ),
                  );
                }),
              ),
            ))),
    TextButton(
      child: const Text('Cancel'),
      onPressed: () {
        _handleOk();
      },
    ),
  ],
);

输出:-

<img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNnNla3YyZ2Vxb2lvaXNmaWs0bWUwNnh1d2FnaXVybnNkN2JpeWlmbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/YZfa1Ns6BZyMdstZKv/giphy.gif">
英文:

The solution to the question is straightforward, we just have to make changes inside the timer_picker.dart file.

Open timer_picker.dart file by hovering over the TimePickerDialog widget and hold CTRL and left-click on it, this will open timer_picker. In this file scroll to line no 2415. Then just copy paste the code which I have added below. Hot restart the app after saving the file

Note : - Any UI or function changes related to timerPicker Widget need to be changed inside the timer_picker.dart file.

Complete Code : -

UI Code : -

import &#39;package:flutter/material.dart&#39;;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Flutter Demo&#39;,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Box(),
);
}
}
class Box extends StatefulWidget {
const Box({super.key});
@override
State&lt;Box&gt; createState() =&gt; _BoxState();
}
class _BoxState extends State&lt;Box&gt; {
var timeVal = TimeOfDay.fromDateTime(DateTime.now());
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () async {
timeVal = await showDialog(
context: context,
builder: (BuildContext context) {
return TimePickerDialog(
initialTime: timeVal,
cancelText: &quot;&quot;,
confirmText: &quot;&quot;,
);
},
);
setState(() {});
},
child: Text(
&quot;Time : - ${timeVal.format(context)}&quot;,
style: const TextStyle(fontSize: 25),
),
)));
}
}

time_picker.dart Code : -

return AlertDialog(
actions: &lt;Widget&gt;[
SizedBox(
height: 500,
width: 500,
child: WillPopScope(
onWillPop: () {
_handleOk();
return Future.value(false);
},
child: Dialog(
shape: shape,
elevation: pickerTheme.elevation ?? defaultTheme.elevation,
backgroundColor: pickerTheme.backgroundColor ??
defaultTheme.backgroundColor,
insetPadding: EdgeInsets.symmetric(
horizontal: 16,
vertical: (_entryMode.value == TimePickerEntryMode.input ||
_entryMode.value == TimePickerEntryMode.inputOnly)
? 0
: 24,
),
child: Padding(
padding: pickerTheme.padding ?? defaultTheme.padding,
child: LayoutBuilder(builder:
(BuildContext context, BoxConstraints constraints) {
final Size constrainedSize =
constraints.constrain(dialogSize);
final Size allowedSize = Size(
constrainedSize.width &lt; minDialogSize.width
? minDialogSize.width
: constrainedSize.width,
constrainedSize.height &lt; minDialogSize.height
? minDialogSize.height
: constrainedSize.height,
);
return SingleChildScrollView(
restorationId: &#39;time_picker_scroll_view_horizontal&#39;,
scrollDirection: Axis.horizontal,
child: SingleChildScrollView(
restorationId: &#39;time_picker_scroll_view_vertical&#39;,
child: AnimatedContainer(
width: allowedSize.width,
height: allowedSize.height,
duration: _kDialogSizeAnimationDuration,
curve: Curves.easeIn,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: &lt;Widget&gt;[
Expanded(
child: Form(
key: _formKey,
autovalidateMode: _autovalidateMode.value,
child: _TimePicker(
time: widget.initialTime,
onTimeChanged: _handleTimeChanged,
helpText: widget.helpText,
cancelText: widget.cancelText,
confirmText: widget.confirmText,
errorInvalidText: widget.errorInvalidText,
hourLabelText: widget.hourLabelText,
minuteLabelText: widget.minuteLabelText,
restorationId: &#39;time_picker&#39;,
entryMode: _entryMode.value,
orientation: widget.orientation,
onEntryModeChanged:
_handleEntryModeChanged,
),
),
),
actions,
],
),
),
),
);
}),
),
))),
TextButton(
child: const Text(&#39;Cancel&#39;),
onPressed: () {
_handleOk();
},
),
],
);
}
}

Output : -

<img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNnNla3YyZ2Vxb2lvaXNmaWs0bWUwNnh1d2FnaXVybnNkN2JpeWlmbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/YZfa1Ns6BZyMdstZKv/giphy.gif">

huangapple
  • 本文由 发表于 2023年6月15日 14:20:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定