简体   繁体   中英

How to add a clickable button to a DropdownMenuItem as a child in flutter?

I am trying to add a DateTimePicker to a dropdown menu so the user can select a particular date through it. How to Display a DateTimePicker after a dropDropdownMenuItem is clicked ? I've included the code below.

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

class CustomDropDown extends StatefulWidget {
  DateTime selectedEndDate = new DateTime.now();

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

class _CustomDropDownState extends State<CustomDropDown> {
  var _value = '1';

  DateTime selectedDate = DateTime.now();

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
        widget.selectedEndDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton(
      items: [
        DropdownMenuItem(
          value: "1",
          child: InkWell(
            child: Text(
              'Forever',
              style: TextStyle(color: Colors.teal, fontSize: 23),
            ),
            onTap: () => (widget.selectedEndDate = DateTime(2100)),
          ),
        ),
        DropdownMenuItem(
          value: "2",
          child: InkWell(
            onTap: () => _selectDate(context),
            child: Text(
              'Select end date: ${selectedDate.day}/${selectedDate.month}/${selectedDate.year}',
              style: TextStyle(color: Colors.teal, fontSize: 23),
            ),
          ),
        ),
      ],
      onChanged: (val) => setState(() {
        _value = val;
      }),
      value: _value,
      style: TextStyle(color: Colors.teal, fontSize: 23),
      isExpanded: true,
    ));
  }
}

You can check the value you select in onChange():

onChanged: (val) => 
   setState(() {
   if (val == "2") {
     //Display select date
   }
   _value = val;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM