1

How do I pass down the data from the datepicker to the _addCashButton widget?

I was able to assign the date to newDateTime. I assigned it again to addDate to save to the database but it's coming up as null

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);
      },
    );
  }
}
4

1 回答 1

1

你在DateTime newDateTime;外面,你在里面使用相同的名字onDateTimeChanged: (DateTime newDateTime) {

照原样,当onDateTimeChanged发生时,它newDateTime不会更新DateTime newDateTime;.

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

this.newDateTime = newDateTime;

但是您应该以不同的方式重命名其中一个,这样您就不会像这样混淆它。

于 2019-10-24T22:58:11.760 回答