将Cupertino Datepicker传递给另一个小部件

时间:2019-10-24 22:18:14

标签: flutter cupertinopicker

如何将数据从日期选择器传递到_addCashButton小部件?

我能够将日期分配给newDateTime。我再次将其分配给addDate以保存到数据库,但是它显示为空

class AddCashTab extends StatefulWidget {
  const AddCashTab({
    Key key,
  }) : super(key: key);
  @override
  _AddCashTabState createState() => _AddCashTabState();
}

class _AddCashTabState extends State<AddCashTab> {
  DateTime newDateTime;
  DateTime date = DateTime.now();

  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _addDateButton(context),
          _addCashButton(context),
        ],
      ),
    );
  }

  Widget _addDateButton(BuildContext context) {
    return GestureDetector(
      onTap: () {
        showCupertinoModalPopup<void>(
          context: context,
          builder: (BuildContext context) {
            return _buildBottomPicker(
              CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date,
                initialDateTime: date,
                onDateTimeChanged: (DateTime newDateTime) {
                  setState(() {
                    date = newDateTime;
                    print(newDateTime);
                  });
                },
              ),
            );
          },
        );
      },
      child: _buildMenu(
        <Widget>[
          // CupertinoButton.filled(
          //   child: Text('Select Date'),
          // ),
          const Text('Select Date'),
          Text(
            DateFormat.yMMMMd().format(date),
            style: const TextStyle(color: CupertinoColors.inactiveGray),
          ),
        ],
      ),
    );
  }

  Widget _addCashButton(BuildContext context) {
    return CupertinoButton.filled(
      child: Text('Add Cash'),
      onPressed: () {
        final database = Provider.of<AppDatabase>(context);
        final task = AddCashFlow(
          addName: controller.text,
          addDate: newDateTime,
        );
        database.insertAddCash(task);
      },
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您外面有DateTime newDateTime;,并且在onDateTimeChanged: (DateTime newDateTime) {中使用了相同的名称

按原样,当onDateTimeChanged发生时,其newDateTime不会更新DateTime newDateTime;

一个快速的更改是将其添加到onDateTimeChanged

this.newDateTime = newDateTime;

但是您应该以不同的方式重命名其中之一,以免引起混淆。