This is my code and I tried to print the value in my console to figure if it is work and it's correctly printed but it dose not show in the text Filed. When I chose the hint text disappear but no thing show also I changed the Icon (arrow) size but when I click on any part of it, no response until I click in the corner
String _medicationDesc;
List<DropdownMenuItem> getDropDownItem() {
List<DropdownMenuItem> dropDownItems = [];
for (String dose in medcationDose) {
var newItem = DropdownMenuItem(
child: Text(
dose,
style: textStyle1,
),
value: dose,
);
dropDownItems.add(newItem);
}
return dropDownItems;
}
List<String> medcationDose = [
'مرة واحدة في اليوم',
'مرتان في اليوم',
'ثلاث مرات في اليوم',
'اربعة مرات في اليوم',
'وقت الحاجة'
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: nave),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.fromLTRB(0.0, 30, 0, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
SizedBox(
height: 50,
width: 350,
child: DropdownButtonFormField(
value: _medicationDose,
items: getDropDownItem(),
iconSize: 50,
iconEnabledColor: white,
onChanged: (value) {
setState(() {
_medicationDose = value;
});
},
decoration: InputDecoration(
hintText: 'الجرعة',
),
),
try this
List<String> languageList = ['EN', 'ES', 'FR'];
var selectedValue;
DropdownButtonHideUnderline(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent))),
dropdownColor: CustomColors.black,
value:
selectedValue == null ? languageList[0] : selectedValue,
style: robotoStyle(
color: CustomColors.white,
fontSize: 10),
icon: Icon(
Icons.keyboard_arrow_down,
color: CustomColors.white,
),
isExpanded: true,
items: languageList.map((item) {
return DropdownMenuItem<String>(
value: item,
child: new Text(item,
style: robotoStyle(
color: CustomColors.white,
fontSize: 10)),
);
}).toList(),
onChanged: (value) {
selectedValue = value;
S.load(Locale(selectedValue));
print(selectedValue);
},
),
)
i made a class for you, you can call it anywhere may be it will help you
class DropDownClass extends StatelessWidget {
var values;
var hint;
List list = new List();
Color underLineColor;
Color dropDownColor;
Color textColor;
DropDownClass({this.values,
this.list,this.hint,this.underLineColor,this.dropDownColor,this.textColor});
#override
Widget build(BuildContext context) {
return DropdownButtonHideUnderline(
child: DropdownButtonFormField<String>(
value: values,
dropdownColor: dropDownColor??Colors.white,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: underLineColor??Colors.grey[800],
width: 1.0,
),
)
),
style: TextStyle(
color: textColor??Colors.black,
fontWeight: FontWeight.w400,
fontSize: 15),
isExpanded: true,
icon: Icon(
Icons.keyboard_arrow_down,
color: Colors.white,
),
hint: Text(hint,
style: TextStyle(
color:Colors.white,
fontWeight: FontWeight.w400,
fontSize:15)),
items: list.map((item) {
return DropdownMenuItem<String>(
value: item,
child: new Text(item,
style: TextStyle(
color:Colors.black,
fontWeight: FontWeight.w400,
fontSize:15)),
);
}).toList(),
onChanged: (value) {
values = value;
print(values);
},
),
);
}
}
Related
I have a page with a DropdownButton.
The hint is 'Select your choice'.
When an item is selected in the DropdownButton when I click on a button I want the DropdownButton to go back to the beginning and show 'Select your choice' again.
child: DropdownButton<String> (
hint: Text(
'Select your choice',
style: TextStyle(
color: Colors.white,
fontFamily: 'Quicksand',
),
),
borderRadius: BorderRadius.circular(10),
dropdownColor: Color.fromRGBO(84, 84, 84, 10),
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.white,
),
iconSize: 40,
isExpanded: true,
underline: SizedBox(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontFamily: 'Quicksand',
),
items: [
DropdownMenuItem(
child: Text(listaMedidas[0]),
value: listaMedidas[0],
),
DropdownMenuItem(
child: Text(listaMedidas[1]),
value: listaMedidas[1],
),
DropdownMenuItem(
child: Text(listaMedidas[2]),
value: listaMedidas[2],
),
DropdownMenuItem(
child: Text(listaMedidas[3]),
value: listaMedidas[3],
),
],
onChanged: (value) => setState(() {
escolha = value;
limpar();
textoObservacao(value);
}),
value: escolha,
),
You can set null value to the DropdownButton, it will show the hint text.
class DropDownButtonTest extends StatefulWidget {
const DropDownButtonTest({Key? key}) : super(key: key);
#override
State<DropDownButtonTest> createState() => _DropDownButtonTestState();
}
class _DropDownButtonTestState extends State<DropDownButtonTest> {
List<String> listaMedidas = ["A", "B"];
String? escolha;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
DropdownButton<String>(
hint: Text(
'Select your choice',
style: TextStyle(
color: Colors.white,
fontFamily: 'Quicksand',
),
),
borderRadius: BorderRadius.circular(10),
dropdownColor: Color.fromRGBO(84, 84, 84, 10),
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.white,
),
iconSize: 40,
isExpanded: true,
underline: SizedBox(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontFamily: 'Quicksand',
),
items: [
for (int i = 0; i < listaMedidas.length; i++)
DropdownMenuItem(
child: Text(listaMedidas[i]),
value: listaMedidas[i],
),
],
onChanged: (value) => setState(() { escolha = value;}),
value: escolha,
),
ElevatedButton(
onPressed: () {
setState(() {
escolha = null;
});
},
child: Text("Reset"),
),
],
),
);
}
}
I am design a screen in which I need to opening a drop down list when user click on textfield till now I am using CupertinoActionSheetAction sheet which is correctly working now I need to replace it with DropdownButton but when I am doing it is not displaying on screen I don't know why.
Here is my code focus on line number 136 (function for CupertinoActionSheetAction is working code) and line 138 where (function for drop not working code) according to me may be it due to build context but I m not sure how to use 'build context' in this context can any one help me out to fix that.
Thanks in advance, And any suggestion for making my code more reusable will be helpful as well :)
import 'dart:ffi';
import 'package:fleet_management/AppContants/Contants.dart';
import 'package:fleet_management/Controllers/NewFuelExpenseController.dart';
import 'package:fleet_management/Models/NewFuelExpenseModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AddFuelView extends StatefulWidget {
const AddFuelView({Key? key}) : super(key: key);
#override
_AddFuelView createState() {
return _AddFuelView();
}
}
// MyTripHistoryView
class _AddFuelView extends State<AddFuelView> {
NewFuelExpenseModel fuelExpense =
NewFuelExpenseController().getNewFuelExpense();
DateTime _selectedDate = DateTime.now();
String dropdownvalue = 'Item 1';
// List of items in our dropdown menu
var items = [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
];
TextStyle _titleTextStyle = const TextStyle();
TextStyle _valueTextStyle = const TextStyle();
final GlobalKey newFuelExpenseFormField = GlobalKey<FormState>();
final TextEditingController _dateEditingController = TextEditingController();
final TextEditingController _priceTextEditingController =
TextEditingController();
final TextEditingController _gallonsTextEditingController =
TextEditingController();
final TextEditingController _totalTextEditingController =
TextEditingController();
final TextEditingController _odometerTextEditingController =
TextEditingController();
final TextEditingController _fuelTypeTextEditingController =
TextEditingController();
final TextEditingController _vendorTextEditingController =
TextEditingController();
#override
void initState() {
super.initState();
_titleTextStyle =
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600);
_valueTextStyle = const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black38);
_dateEditingController.text =
"${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
}
#override
Widget build(BuildContext context) {
var scaffold = Scaffold(
appBar: AppBar(
title: Text(StringsConstants.newFuelExpense),
backgroundColor: AppColorsConstants.primaryColor,
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () {
print("SAVE Button Clicked");
},
child: Text("Save", style: _titleTextStyle),
),
],
),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: newFuelExpenseFormField,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
showDateRow(context),
addTextFieldInput(
StringsConstants.priceGallon,
"\u{20B9}0.00",
false,
_priceTextEditingController,
TextInputType.datetime,
null,
null),
addTextFieldInput(
StringsConstants.gallons,
"",
false,
_gallonsTextEditingController,
TextInputType.number,
null,
null),
addTextFieldInput(
StringsConstants.total,
"\u{20B9}0.00",
false,
_totalTextEditingController,
TextInputType.number,
null,
null),
addTextFieldInput(
StringsConstants.odometer,
"",
false,
_odometerTextEditingController,
TextInputType.number,
null,
null),
// show action sheet
addTextFieldInput(
StringsConstants.fuelType,
"",
true,
_fuelTypeTextEditingController,
TextInputType.none,
null, () {
// Working. - >>>> HERE <<<<<
showActionSheet(context);
// Not Working >>>> HERE <<<<< Uncomment following function before
// showDropDown();
}),
addTextFieldInput(
StringsConstants.vendor,
"",
false,
_vendorTextEditingController,
TextInputType.text,
null,
null),
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
print("Submit button pressed!");
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24),
primary: AppColorsConstants.primaryColor,
textStyle:
const TextStyle(fontWeight: FontWeight.bold),
),
child: Text(StringsConstants.submit)),
ElevatedButton(
onPressed: () {
print("Cancel button pressed!");
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24),
primary: AppColorsConstants.primaryColor,
textStyle:
const TextStyle(fontWeight: FontWeight.bold),
),
child: Text(StringsConstants.cancel))
],
)
],
),
),
),
),
),
);
return scaffold;
}
void showDropDown() {
DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
);
}
Future<dynamic> showActionSheet(BuildContext context) {
return showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => CupertinoActionSheet(
title: const Text('Choose Options'),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Oil'),
onPressed: () {
_fuelTypeTextEditingController.text = "Oil";
Navigator.pop(context, 'Oil');
},
),
CupertinoActionSheetAction(
child: const Text('Petrol'),
onPressed: () {
_fuelTypeTextEditingController.text = "Petrol";
Navigator.pop(context, 'Petrol');
},
),
CupertinoActionSheetAction(
child: const Text('diesel'),
onPressed: () {
_fuelTypeTextEditingController.text = "diesel";
Navigator.pop(context, 'diesel');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)),
);
}
Container addTextFieldInput(
String title,
String initialValue,
bool isEditable,
TextEditingController textfieldController,
TextInputType keyboardType,
FormFieldValidator<String>? validator,
GestureTapCallback? tabCallback,
) {
return Container(
padding: const EdgeInsets.fromLTRB(0, 16, 0, 8),
child: SizedBox(
child: TextFormField(
onTap: tabCallback,
keyboardType: keyboardType,
cursorHeight: 16,
cursorWidth: 1.4,
readOnly: isEditable,
controller: textfieldController,
validator: validator,
decoration: InputDecoration(
isDense: true,
floatingLabelStyle:
TextStyle(color: AppColorsConstants.primaryColor),
labelText: title,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: AppColorsConstants.primaryColor, width: 1.5),
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black38, width: 1.5),
),
border: const OutlineInputBorder()),
style: const TextStyle(fontSize: 18),
cursorColor: Colors.black38,
showCursor: true,
autofocus: true,
),
),
);
}
Container showDateRow(BuildContext context) {
return Container(
child: TextFormField(
onTap: () => {_selectDate(context)},
cursorHeight: 16,
cursorWidth: 1.4,
readOnly: true,
enableInteractiveSelection: false,
controller: _dateEditingController,
decoration: InputDecoration(
isDense: true,
labelStyle: const TextStyle(color: Colors.orangeAccent),
labelText: StringsConstants.date,
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.orangeAccent, width: 1.5),
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black38, width: 1.5),
),
border: const OutlineInputBorder()),
style: const TextStyle(fontSize: 18),
cursorColor: Colors.black38,
showCursor: true,
autofocus: true,
),
);
}
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(1990),
lastDate: DateTime.now());
if (picked != null && picked != _selectedDate) {
setState(() {
_selectedDate = picked;
this._dateEditingController.text =
"${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
});
}
}
}
For DropDown in flutter you need
an initail value,
a list to be shown just
String selectedvalue='myvalue';
/// be sure you add the variable value in the 0 index of you list other wise it will thrown error or exception..
List<String> myList=[
'myvalue',/// the value is same as variable value
'othe value', ....
];
DropDownButton(
onChanged: (resultValue){
/// you can get selected value from here
},
items: myList.map((e){
retrun DropdownMenuItem(
value: e,
child: Text(e));
}).toList(),
value: selectedvalue,
),
You can use DropdownButtonFormField in place of TextFormField and can make some style related changes per your requirement.
class MyWidget extends StatelessWidget {
String selectedValue = "USA";
List<DropdownMenuItem<String>> get dropdownItems{
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(child: Text("USA"),value: "USA"),
DropdownMenuItem(child: Text("Canada"),value: "Canada"),
DropdownMenuItem(child: Text("Brazil"),value: "Brazil"),
DropdownMenuItem(child: Text("England"),value: "England"),
];
return menuItems;
}
#override
Widget build(BuildContext context) {
return DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(20),
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(20),
),
filled: true,
fillColor: Colors.blueAccent,
),
dropdownColor: Colors.blueAccent,
value: selectedValue,
onChanged: (String? newValue) {
selectedValue = newValue!;
},
items: dropdownItems);
}
}
I created dropdown in TextFormField in flutter, i successfully loaded list (bankDataList) into dropdown which is dynamic list. Data is showing into dropdown list. But i have a problem to assign
"value : _bankChoose" into DropDownButton , it is not updating into TextFormField. I am using icon and text, please see screenshot.
String _bankChoose;
List<BankListDataModel> bankDataList;
Container(
margin: EdgeInsets.only(left: 15, top: 10, right: 15),
child: FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
contentPadding:
EdgeInsets.fromLTRB(12, 10, 20, 20),
// labelText: "hi",
// labelStyle: textStyle,
// labelText: _dropdownValue == null
// ? 'Where are you from'
// : 'From',
errorText: _errorBank,
errorStyle: TextStyle(
color: Colors.redAccent, fontSize: 16.0),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.0))),
child: DropdownButtonHideUnderline(
child: DropdownButton<BankListDataModel>(
style: TextStyle(
fontSize: 16,
color: text_gray_color,
fontFamily: "verdana_regular",
),
hint: Text(
"Select Bank",
style: TextStyle(
color: text_gray_color,
fontSize: 16,
fontFamily: "verdana_regular",
),
),
value: _bankChoose,
isExpanded: true,
isDense: true,
onChanged: (BankListDataModel newValue) {
setState(() {
_bankChoose = newValue.bank_name;
});
},
items: bankDataList
.map<DropdownMenuItem<BankListDataModel>>(
(BankListDataModel valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
new CircleAvatar(
backgroundImage: new NetworkImage(
valueItem.bank_logo),
),
// Icon(valueItem.bank_logo),
SizedBox(
width: 15,
),
Text(valueItem.bank_name),
],
),
);
}).toList(),
),
),
);
},
),
),
You want to choose drop down item of type BankListDataModel, then your _bankChoose variable should be of type BankListDataModel.
Try this one,
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//String _bankChoose;
BankListDataModel _bankChoose;
List<BankListDataModel> bankDataList=[
BankListDataModel("SBI","https://www.kindpng.com/picc/m/83-837808_sbi-logo-state-bank-of-india-group-png.png"),
BankListDataModel("HDFC","https://www.pngix.com/pngfile/big/12-123534_download-hdfc-bank-hd-png-download.png"),
BankListDataModel("ICICI","https://www.searchpng.com/wp-content/uploads/2019/01/ICICI-Bank-PNG-Icon-715x715.png"),
//BankListDataModel("Canara","https://bankforms.org/wp-content/uploads/2019/10/Canara-Bank.png")
];
#override
void initState() {
super.initState();
_bankChoose = bankDataList[0];
}
void _onDropDownItemSelected(BankListDataModel newSelectedBank) {
setState(() {
_bankChoose = newSelectedBank;
});
}
#override
Widget build(BuildContext context) {
return
Scaffold(
body: Form(
child: Center(
child: Container(
margin: EdgeInsets.only(left: 15, top: 10, right: 15),
child: FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
contentPadding:
EdgeInsets.fromLTRB(12, 10, 20, 20),
// labelText: "hi",
// labelStyle: textStyle,
// labelText: _dropdownValue == null
// ? 'Where are you from'
// : 'From',
errorText: "Wrong Choice",
errorStyle: TextStyle(
color: Colors.redAccent, fontSize: 16.0),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.0))),
child: DropdownButtonHideUnderline(
child: DropdownButton<BankListDataModel>(
style: TextStyle(
fontSize: 16,
color: Colors.grey,
fontFamily: "verdana_regular",
),
hint: Text(
"Select Bank",
style: TextStyle(
color: Colors.grey,
fontSize: 16,
fontFamily: "verdana_regular",
),
),
items: bankDataList
.map<DropdownMenuItem<BankListDataModel>>(
(BankListDataModel value) {
return DropdownMenuItem(
value: value,
child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
new CircleAvatar(
backgroundImage: new NetworkImage(
value.bank_logo),
),
// Icon(valueItem.bank_logo),
SizedBox(
width: 15,
),
Text(value.bank_name),
],
),
);
}).toList(),
isExpanded: true,
isDense: true,
onChanged: (BankListDataModel newSelectedBank) {
_onDropDownItemSelected(newSelectedBank);
},
value: _bankChoose,
),
),
);
},
),
),
),
),
);
}
}
class BankListDataModel{
String bank_name;
String bank_logo;
BankListDataModel(this.bank_name,this.bank_logo);
}
sorry for formatting of images.
One way would be to use a TextEditingController and assign is to your TextField with controller: textEditingController for example
final textEditingController = TextEditingController();
DropdownButton(
hint: Text('Select Priority Level', style: GoogleFonts.dosis() ,),
dropdownColor: Colors.blueGrey,
value: selectedValue,
onChanged: (newValue){
setState(() {
selectedValue = newValue;
priority = selectedValue;
});
},
items: listPriority.map((valueItem){
return DropdownMenuItem<String>(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
)
The value selected is stored however when I select an item it does not show in the drop-down field. How can I fix this?
Here is sample code i did
initialize variable
int _selectedjobcategory;
Code
Flexible(
flex: 0,
child: Padding(
padding: EdgeInsets.only(left: 10, right: 10, top: 15),
child: Container(
width: double.infinity,
height: 60,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Colors.blueGrey)),
child: DropdownButtonFormField(
isExpanded: true,
itemHeight: 50,
icon: Icon(Icons.arrow_drop_down),
iconSize: 40,
// underline: SizedBox(),
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Select Enquiry Type",
style: TextStyle(fontSize: 15, color: Colors.black),
),
),
value: _selectedjobcategory,
onChanged: (newValues) {
setState(() {
_selectedjobcategory = newValues;
});
},
items: jobcategory.map((jobs) {
return DropdownMenuItem(
child: Padding(
padding: const EdgeInsets.all(8.0),
child:
Text(jobs.name, style: TextStyle(fontSize: 15)),
),
value: jobs.id,
);
}).toList(),
),
),
),
),
here's a custom class of dropdown you can call it anywhere
import 'package:flutter/material.dart';
// ignore: must_be_immutable
class DropDownClass extends StatelessWidget {
var _hint;
var _val;
List _list = new List();
bool _border;
Color _underLineColor, _dropDownColor;
List get list => _list;
dynamic Function(dynamic) _listener;
DropDownClass({List list,
var hint,
Color underLineColor,
Color dropDownColor,
Color textColor,
double fontSize,
bool icon,
var val,
int type,
bool border = true,
dynamic Function(dynamic) listener,})
: _list = list,
_hint = hint,
_underLineColor = underLineColor,
_dropDownColor = dropDownColor,
_val = val,
_border = border,
_listener = listener;
#override
Widget build(BuildContext context) {
return DropdownButtonHideUnderline(
child: DropdownButtonFormField<String>(
value: _val,
dropdownColor: _dropDownColor ?? Colors.white,
decoration:_border == true? InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: _underLineColor ?? Theme
.of(context)
.hintColor,
width: 1.0,
),
)
):InputDecoration(
border: InputBorder.none,
fillColor: Colors.grey[400],
filled: true),
isExpanded: true,
hint: Text(_hint),
items: list.map((item) {
return DropdownMenuItem<String>(
value: item,
child: new Text(item,),
);
}).toList(),
onChanged: (value) {
_val = value;
if (_listener != null) _listener.call(value);
// return val;
},
),
);
}
}
I'm trying to make a custom function which returns a dropdown menu. The function takes 3 arguments: menuTitle, selectedValue and list of Strings.
List<String> cities= ['Rome', 'London', 'Paris'];
String selectedCity;
String title='Select a city';
Widget _buildDropdown(
String menuTitle, String selectedItem, List<String> list) {
return Container(
width: MediaQuery.of(context).size.width * 0.8,
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]),
borderRadius: BorderRadius.circular(10.0)),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
isExpanded: true,
hint: Text(
menuTitle.toUpperCase(),
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[500],
fontWeight: FontWeight.bold,
)),
),
value: selectedItem,
items: list.map((String val) {
return DropdownMenuItem(
value: val,
child: Text(
val.toUpperCase(),
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[500],
)),
),
);
}).toList(),
onChanged: (String value) {
setState(() {
selectedItem = value;
});
},
),
),
),
);
}
Dropdown menu shows all options available, but after choosing one, I can only see the hint text and not the selected value. I would appreciate any help.
For your dropdown to reflect on your selectedValue, it should be a part of the state. So follow as shown in the code below. I have tested this code and its working for me.
class _MyAppState extends State<MyApp> {
List<String> cities= ['Rome', 'London', 'Paris'];
//Initialize your selectedItem to selectedCity
//default selectedCity
String selectedCity='Rome';
String title='Select a city';
#override
Widget build(BuildContext context) {
Color color=Colors.blueAccent;
int x=color.value;
return MaterialApp(
home: Scaffold(
body: Column(
children: <Widget>[_buildDropdown("Title","",cities)],
),
),
);
}
Widget _buildDropdown(
String menuTitle, String selectedItem, List<String> list) {
return Container(
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]),
borderRadius: BorderRadius.circular(10.0)),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
isExpanded: true,
hint: Text(
menuTitle.toUpperCase(),
),
value: selectedCity,
items: list.map((String val) {
return DropdownMenuItem(
value: val,
child: Text(
val.toUpperCase(),
),
);
}).toList(),
onChanged: (String value) {
setState(() {
selectedCity = value;
});
},
),
),
),
);
}
}