在小部件中获取时间选择器的值

时间:2020-03-11 16:54:23

标签: flutter dart

我试图获取从用户选择的DateTime并将其保存在对象中。

这是在以下构造中实现的:

return Scaffold(
      appBar: AppBar(
        title: Text('Add/Edit Shift'),
      ),
      body: Container(
        color: Colors.white,
        margin: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
//              crossAxisAlignment: CrossAxisAlignment.center,
//              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  height: 40.0,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  child: Text(
                    'Scheduling Date: ${_dateformat.format(widget.shiftDate)}',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 19.0,
                      color: Colors.teal,
                    ),
                  ),
                ),
                // fixme: how to get the clicked value from the user?
                //  the value has to get saved within an object that will be returned
                MyTimePicker(_startOfShift),
                MyTimePicker(_endOfShift),
                RaisedButton(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Text(
                    "Submit",
                    style: TextStyle(
                        color: Colors.teal,
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold),
                  ),
                  onPressed: () {
                    // todo: return the shift to the calendar
//                    print(MyTimePicker(_startOfShift).chosenTime);
                    Navigator.pop(
                      context,
                    );
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );

这是它的样子:

enter image description here

MyTimePickerClass 被创建为单独的Dart文件。在 MyTimePicker 类中,我构造了一个标有开始结束的RaisedButton,用户可以在其中选择所需的时间。

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

class MyTimePicker extends StatefulWidget {
  String typeOfShift;
  MyTimePicker(this.typeOfShift);

  @override
  _MyTimePickerState createState() => _MyTimePickerState();
}

class _MyTimePickerState extends State<MyTimePicker> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
      elevation: 4.0,
      onPressed: () {
        DateTime test = _MyDatePicker(context);
        widget.typeOfShift = test.toString();
        setState(() {});
      },
      child: Container(
        alignment: Alignment.center,
        height: 50.0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.access_time,
                        size: 18.0,
                        color: Colors.teal,
                      ),
                      Text(
                        " ${widget.typeOfShift}",
                        style: TextStyle(
                            color: Colors.teal,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0),
                      ),
                    ],
                  ),
                )
              ],
            ),
            Text(
              "  Change",
              style: TextStyle(
                  color: Colors.teal,
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0),
            ),
          ],
        ),
      ),
      color: Colors.white,
    );
  }

  DateTime _MyDatePicker(BuildContext context) {
    DateTime _myDateTime;
    DatePicker.showTimePicker(context,
        showSecondsColumn: false,
        theme: DatePickerTheme(
          containerHeight: 210.0,
        ),
        showTitleActions: true, onConfirm: (time) {
//      _chosenTime = time;
      _myDateTime = time;
      print('confirm $time');
//      widget.typeOfShift = '${time.hour} : ${time.minute}';
      setState(() {});
    }, currentTime: DateTime.now(), locale: LocaleType.de);
    return _myDateTime;
  }
}

enter image description here enter image description here

然后将时间显示在UI中。这次我该如何访问?

1 个答案:

答案 0 :(得分:1)

您可以在下面复制粘贴运行完整代码
您可以定义两个MyTimePicker并使用它
onPressed时,您可以使用startPicker.typeOfShift来获取String

MyTimePicker startPicker = MyTimePicker("Start");
MyTimePicker endPicker = MyTimePicker("End");

...
startPicker,
endPicker,
RaisedButton(
...
onPressed: () {
                    print(startPicker.typeOfShift);
                    print(endPicker.typeOfShift);

输出

I/flutter (31204): 1 : 23
I/flutter (31204): 1 : 25

工作演示

enter image description here

完整代码

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

class MyTimePicker extends StatefulWidget {
  String typeOfShift;
  MyTimePicker(this.typeOfShift);

  @override
  _MyTimePickerState createState() => _MyTimePickerState();
}

class _MyTimePickerState extends State<MyTimePicker> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
      elevation: 4.0,
      onPressed: () {
        DateTime test = _MyDatePicker(context);
        widget.typeOfShift = test.toString();
        setState(() {});
      },
      child: Container(
        alignment: Alignment.center,
        height: 50.0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.access_time,
                        size: 18.0,
                        color: Colors.teal,
                      ),
                      Text(
                        " ${widget.typeOfShift}",
                        style: TextStyle(
                            color: Colors.teal,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0),
                      ),
                    ],
                  ),
                )
              ],
            ),
            Text(
              "  Change",
              style: TextStyle(
                  color: Colors.teal,
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0),
            ),
          ],
        ),
      ),
      color: Colors.white,
    );
  }

  DateTime _MyDatePicker(BuildContext context) {
    DateTime _myDateTime;
    DatePicker.showTimePicker(context,
        showSecondsColumn: false,
        theme: DatePickerTheme(
          containerHeight: 210.0,
        ),
        showTitleActions: true, onConfirm: (time) {
//      _chosenTime = time;
      _myDateTime = time;
      print('confirm $time');
      widget.typeOfShift = '${time.hour} : ${time.minute}';
      setState(() {});
    }, currentTime: DateTime.now(), locale: LocaleType.de);
    return _myDateTime;
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  MyTimePicker startPicker = MyTimePicker("Start");
  MyTimePicker endPicker = MyTimePicker("End");
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add/Edit Shift'),
      ),
      body: Container(
        color: Colors.white,
        margin: EdgeInsets.all(16.0),
        child: Form(
          //key: _formKey,
          child: SingleChildScrollView(
            child: Column(
//              crossAxisAlignment: CrossAxisAlignment.center,
//              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  height: 40.0,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  child: Text(
                    'Scheduling Date: ',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 19.0,
                      color: Colors.teal,
                    ),
                  ),
                ),
                // fixme: how to get the clicked value from the user?
                //  the value has to get saved within an object that will be returned
                startPicker,
                endPicker,
                RaisedButton(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Text(
                    "Submit",
                    style: TextStyle(
                        color: Colors.teal,
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold),
                  ),
                  onPressed: () {
                    print(startPicker.typeOfShift);
                    print(endPicker.typeOfShift);
                    // todo: return the shift to the calendar
//                    print(MyTimePicker(_startOfShift).chosenTime);
                    Navigator.pop(
                      context,
                    );
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
相关问题