如何在flutter中显示日期时间选择器中时间?

fafcakar  于 2023-02-13  发布在  Flutter
关注(0)|答案(2)|浏览(206)

假设您有一个API,该API键值为

“时间”:“22:05”

我想在字段中显示此时间,当我按下字段时,日期时间选择器弹出时间值,我将时间更改为22:4022:05将替换为22:40
我已经试过了。

time = TimeOfDay.now();

final String hour = time.hour.toString().padLeft(2, '0');
final String minute = time.minute.toString().padLeft(2, '0');

 GestureDetector(
          onTap: () async {
            TimeOfDay? pickTime = await showTimePicker(
              context: context,
              initialTime: time,
            );
            if (pickTime != null) {
              setState(() => time = pickTime);
            }

它总是显示我当前的系统时间

jmo0nnb3

jmo0nnb31#

下面是一个工作示例:

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

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

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  TimeOfDay? selectedTime;
  @override
  Widget build(BuildContext context) {
    return 
      GestureDetector(
        onTap : () async {
          TimeOfDay? newTime = await showTimePicker(
            initialTime: TimeOfDay.now(),
            context: context,
          );
          setState((){
            selectedTime = newTime;
          });
        },
        child: Text(
        selectedTime.toString(),
        style: Theme.of(context).textTheme.headline4,
      ),
    );
  }
}
7z5jn7bk

7z5jn7bk2#

这是我常用的方法。使用TextFormfied。所以如果需要的话,你也可以使用验证器。

TextFormField(
  readOnly: true,
  decoration: kInputDecor,
  controller: _ctrl,
  onTap: () async {
    final selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (selectedTime != null) {
      final String hour =
          selectedTime.hour.toString().padLeft(2, '0');
      final String minute =
          selectedTime.minute.toString().padLeft(2, '0');

//                   _ctrl.text = selectedTime.format(context);
      _ctrl.text = '${hour} :$minute';
    }
  },
),

结果:

演示:https://dartpad.dev/?id=be4ccb0cad0930c9797bb4c2b63cd70e

相关问题