如何使用时间选择器小部件使用 Flutter 显示开始和结束时间

How to use timepicker widget to show start and end time using Flutter

我正在创建一个页面来显示开始时间和结束时间,但是当我找不到更新各个字段中的时间的方法时。我只使用一个函数来构建时间选择器并显示时间。

这是我的时间选择器函数

Future<Null> selectedTime(BuildContext context, bool ifPickedTime) async{
_pickedTime = await showTimePicker(
    context: context,
    initialTime: _currentTime);
if (_pickedTime != null){
  setState(() {
    _currentTime = _pickedTime;
    print("The picked time is: $_pickedTime");
  });
 }
}

这是我的 Widget Builder

Widget _buildTimePick(String title, bool ifPickedTime){
return Row(
  children: [
    Container(
      width: 80,
      child: Text(
        title,
        style: AppStyles.textTitle,
      ),
    ),
    Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      decoration: BoxDecoration(
        border: Border.all(color: MyColors.borderColor),
        borderRadius: BorderRadius.circular(20),
      ),
      child: GestureDetector(
        child: Text(
          "${_currentTime.format(context)}",
          style: AppStyles.textBody,
        ),
        onTap: () {
          selectedTime(context, ifPickedTime);
        },
      ),
    ),
  ],
);
}

您可以使用 TextEditingController 更新 TextField。放入 setState 以便它可以在您选择日期时更新 TextField。 Exp:

final txtController = TextEditingController();    
final DateTime? picked = await showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime(2000),
            lastDate: DateTime(2025));
        if(picked != null && picked != now) {
          setState(() {
            txtController.text = DateFormat('dd-MM-yyyy').format(picked); //I'm using intl package, you can use toString()
          });
        }

根据提问,我感觉你想实现的是分别更新开始和结束时间。但是根据代码只有一个时间被更新,由两个开始和结束时间小部件共享,所以它显示相同的时间。

您可以创建 2 个变量,一个用于开始时间,一个用于结束时间。

TimeOfDay _startTime;
TimeOfDay _endTime;

然后通过传递要显示的时间使您的 _buildTimePick 函数更灵活一些。

Widget _buildTimePick(String title, bool ifPickedTime, TimeOfDay currentTime, Function(TimeOfDay) onTimePicked){
return Row(
  children: [
    Container(
      width: 80,
      child: Text(
        title,
        style: AppStyles.textTitle,
      ),
    ),
    Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      decoration: BoxDecoration(
        border: Border.all(color: MyColors.borderColor),
        borderRadius: BorderRadius.circular(20),
      ),
      child: GestureDetector(
        child: Text(
          currentTime.format(context),
          style: AppStyles.textBody,
        ),
        onTap: () {
          selectedTime(context, ifPickedTime,currentTime, onTimePicked);
        },
      ),
    ),
  ],
);
}

另外,selectedTime 函数应该更灵活,以便可以使用 通过创建回调来选择开始和结束时间。

Future selectedTime(BuildContext context, bool ifPickedTime, TimeOfDay initialTime, Function(TimeOfDay) onTimePicked) async{
var _pickedTime = await showTimePicker(
    context: context,
    initialTime: initialTime);
if (_pickedTime != null){
  onTimePicked(_pickedTime);
 }
}

因此,最终代码可能类似于:

import 'package:flutter/material.dart';

void main() => runApp(MainApp());

class MainApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MainApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(),
      body: Home(),
    ));
  }
}

class Home extends StatefulWidget {
  @override
  State<Home> createState() => HomeState();
}

class HomeState extends State<Home> {
  TimeOfDay startTime = TimeOfDay.now();
  TimeOfDay endTime = TimeOfDay.now();

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        _buildTimePick("Start", true, startTime, (x) {
          setState(() {
            startTime = x;
            print("The picked time is: $x");
          });
        }),
        const SizedBox(height: 10),
        _buildTimePick("End", true, endTime, (x) {
          setState(() {
            endTime = x;
            print("The picked time is: $x");
          });
        }),
      ],
    );
  }

  Future selectedTime(BuildContext context, bool ifPickedTime,
      TimeOfDay initialTime, Function(TimeOfDay) onTimePicked) async {
    var _pickedTime =
        await showTimePicker(context: context, initialTime: initialTime);
    if (_pickedTime != null) {
      onTimePicked(_pickedTime);
    }
  }

  Widget _buildTimePick(String title, bool ifPickedTime, TimeOfDay currentTime,
      Function(TimeOfDay) onTimePicked) {
    return Row(
      children: [
        SizedBox(
          width: 80,
          child: Text(
            title,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
          decoration: BoxDecoration(
            border: Border.all(),
            borderRadius: BorderRadius.circular(20),
          ),
          child: GestureDetector(
            child: Text(
              currentTime.format(context),
            ),
            onTap: () {
              selectedTime(context, ifPickedTime, currentTime, onTimePicked);
            },
          ),
        ),
      ],
    );
  }
}