Dropdown with null

Custom dropdown with null value

import 'package:flutter/material.dart';
import 'package:survey_jalan_apps/theme/theme.dart';
class CustomDropDown extends StatelessWidget {
  final String? selected;
  final String? label;
  final List<String>? list;
  final Function(String?)? onChanged;

  const CustomDropDown({
    Key? key,
    this.selected,
    this.label,
    this.list,
    this.onChanged,
  }) : super(key: key);
  getSelectedValue(String? yourValue, List<String> dropDownItems){
    //add this line of code
    if(yourValue == null) return null;
    for(String value in dropDownItems){
      if(value == yourValue) return value;
    }
    return null;
  }
  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.all(4),
            width: double.infinity,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColorLight,
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(15),
                topLeft: Radius.circular(15),
              ),
            ),
            child: Text(
              label!,
              style: myTextTheme.headline6,
              textAlign: TextAlign.center,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: DropdownButton<String>(
              hint: Center(child: Text('---',textAlign: TextAlign.center)),
              isExpanded: true,
              isDense: true,
              underline: Text(''),
              value: getSelectedValue(selected,list!),
              onChanged: onChanged,
              items: list?.map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Center(child: Text(value,textAlign: TextAlign.center,)),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}

Last updated