Need for looping into DropdownSearch in Flutter - flutter

Please I need help for looping years in this widget DropdownSearch.
I'm using this script, but return with wrong Values.
DropdownSearch(
onChanged: (value) {
controller.tahunC.text = value.toString();
print(controller.tahunC.text);
},
showClearButton: true,
dropdownSearchDecoration: const InputDecoration(
suffixIcon: Icon(Icons.image),
labelText: "Tahun",
hintText: 'Tahun',
),
items: List<String>.generate(
(DateTime.now().year).toInt() - 2021,
(int index) => '${index + 1}').map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
),

Related

How to enable and disable a textfield by checking and unchecking a Radio button in flutter

i want to enable and disable a textfield when i click on a radio button in flutter.
so when the user enabales the radiobutton the text field is enable and vise versa.
`
ListTile(
title: const Text('Per Kilometer Policy'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.unchecked,
groupValue: _character,
fillColor: MaterialStateColor.resolveWith(
(states) => Colors.black),
onChanged: (SingingCharacter? isKiloChecked) {
setState(() {
_character = isKiloChecked;
});
},
),
TextFormField(
enabled: _kilometerButtonDisable,
onSaved: (Value) => print(kiloMeter),
decoration: InputDecoration(
hintStyle: TextStyle(
fontFamily: "Proxima Nova",
fontWeight: FontWeight.w300,
),
border: InputBorder.none,
labelStyle: TextStyle(
color: Color(0xffFAFAFA),
),
),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r"[0-9]+|\s"))
],
controller: kiloMeter,
validator: (value) {
if (value != null && value.isEmpty || value != 1000) {
return 'Please enter your Kilometer';
}
return null;
},
),
`
return Column(
children: <Widget>[
Radio(
value: 1,
groupValue: _radioValue,
onChanged: (value) {
setState(() {
_radioValue = value;
});
},
),
TextField(
enabled: _radioValue == 1 ? true : false,
),
],
);
you can do as follows
TextFormField(
enabled: _character==valueToEnable,
...
)
Where in this expression _character==valueToEnable you can replace the value or the values to enable the checkbox (null, list of values, etc)
You can wrap your TextFormField inside AbsorbPointer and handle absorb property like:
bool _disable = false; // set this to false initially
AbsorbPointer(
absorbing: _disable, // true makes TextFormField disabled and vice-versa
child: TextFormField(),
)
for further assistance check out :
checkout this

from dropdownmenu to dropdownsearch in flutter

I was using normal dropdown menu in my project with small amount of data fetched from my api, but now i have menu which could reach hundred of values and make it hard to select an item.
That's why i wanted to use DropDownSearch but instead i get an error
Normal dropdown code which works very fine
DropdownButton(
showSearchBox: true,
showSelectedItem: true,
items: data3.map((item) {
return new DropdownMenuItem(
child: Text(item['first_name']+" "+ item['last_name']),
value: item['emp_code'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection3 = newVal.toString();
});
},
value: _mySelection3,
),
data3 = [{emp_code: 111, first_name: adnen, last_name: hamouda}, {emp_code: 666, first_name: ahmed, last_name: ahmed 99}....
this is the result: normal dropdown
But when i tried to convert it to dropDownSearch i got this result: search dropdown
I want to show the first_name and last_name like the normal dropdown but save the value of their 'emp_code' which i will be using in another api later. How can i fix it ?
DropdownSearch(
mode: Mode.DIALOG,
showSearchBox: true,
items: data3.map((item) {
return new DropdownMenuItem(
child: Text(item['first_name']+" "+ item['last_name']),
value: item['emp_code'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
print(data3);
_mySelection3 = newVal.toString();
});
},
selectedItem: _mySelection3,
),
Here is the way I found to use searchable dropdown lists.
I tried dropdown_search package at first, but it seems the documentation and examples related with the latest version (5.0.2) are depreciated.
Later on, I moved to dropdown_button2 and I am happy the way the DropdownButtonFormField2 was implemented, because it is very similar which I have done to the flutter DropdownButtonFormField implementation, so far.
Have a look at the Flutter bundled DropdownButtonFormField example:
return DropdownButtonFormField<SetorTemp>(
decoration: const InputDecoration(
labelText: 'Setor institucional'),
isExpanded: true,
icon: const Icon(Icons.arrow_downward),
items: snapshot.data!
.map((SetorTemp rtItem) =>
DropdownMenuItem<SetorTemp>(
value: rtItem,
child: Text(
'${rtItem.nome} (${rtItem.sigla})',
softWrap: true,
),
))
.toList(),
hint: Text(
'${selectedSetorTemp.nome} (${selectedSetorTemp.sigla})'),
onChanged: (SetorTemp? newValue) {
setState(() {
// do your logic here!
selectedSetorTemp = newValue;
});
},
);
And the DropdownButtonFormField2 using dropdown_button2 package
return DropdownButtonFormField2<SetorTemp>(
decoration: const InputDecoration(
labelText: 'Setor institucional'),
isExpanded: true,
icon: const Icon(Icons.arrow_downward),
items: snapshot.data!
.map((SetorTemp rtItem) =>
DropdownMenuItem<SetorTemp>(
value: rtItem,
child: Text(
'${rtItem.nome} (${rtItem.sigla})',
softWrap: true,
),
))
.toList(),
hint: Text(
'${selectedSetorTemp.nome} (${selectedSetorTemp.sigla})'),
onChanged: (SetorTemp? newValue) {
setState(() {
// Do your logic here!
selectedSetorTemp = newValue;
});
},
// Search implementation using dropdown_button2 package
searchController: searchContentSetor,
searchInnerWidget: Padding(
padding: const EdgeInsets.only(
top: 8,
bottom: 4,
right: 8,
left: 8,
),
child: TextFormField(
controller: searchContentSetor,
decoration: InputDecoration(
isDense: false,
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 8,
),
labelText: 'Setor institucional',
hintText: 'Parte do nome do setor...',
counterText: '',
hintStyle: const TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
searchMatchFn: (rtItem, searchValue) {
return (rtItem.value.nome
.toLowerCase()
.contains(searchValue.toLowerCase()));
},
//This to clear the search value when you close the menu
onMenuStateChange: (isOpen) {
if (!isOpen) {
searchContentSetor.clear();
}
},
);
They are similar at first:
However, after clicking they will show their differences from the initial implementation:
To the dropdown_button2 package:
The selectedSetorTemp variable is of the type SetorTemp and the model I have used is:
class SetorTemp {
final int id;
final String? nome;
final String? sigla;
SetorTemp({required this.id, this.nome, this.sigla});
factory SetorTemp.fromJson(Map<String, dynamic> json) {
return SetorTemp(
id: json['id'] as int,
nome: json['nome'] as String,
sigla: json['sigla'] as String,
);
}
Map<String, dynamic> toJson() => {
'nome': nome,
'sigla': sigla,
};
}

TextFormField input text overflow with DropdownButtonFormField, Flutter

I have layout issues because the text from the dropdown menu that you choose can't fit inside the TextFormField and I can't seem to fix this issue. I have tried adding the overflow: TextOverflow.ellipsis property but that only changes for the dropdown labels, still when I choose one, they can't fit inside the TextFormField.
When you press the dropdown button, it shows like this:
and with the TextOverflow.elipsis property:
which is fine, but I still have the layout issue because of the chosen text that is now displayed inside the textformfield:
How can I add the same property to the TextFormField, or any sort of solution to this issue?
The code:
Row(
children: [
Expanded(
child: DropdownButtonFormField<String>(
decoration:
kTextFieldDecoration.copyWith(
hintText: 'Legal status',
labelText: 'Legal status',
),
value: _legalStatus,
items: [
'Sole proprietorship',
'Partnerships',
'Limited Liability Company (LLC)',
'Corporation',
'Small Business Corporation (S-Corporation)'
]
.map((label) => DropdownMenuItem(
child: Text(
label.toString(),
),
value: label,
))
.toList(),
onChanged: (value) {
setState(() {
_legalStatus = value;
print(value);
});
},
validator: (thisValue) {
if (thisValue == null) {
return 'Please choose your legal status';
}
return null;
},
),
),
SizedBox(
width: 16.0,
),
Container(
width: 120.0,
child: DropdownButtonFormField<String>(
decoration:
kTextFieldDecoration.copyWith(
hintText: 'Year established',
labelText: 'Year established',
),
value: _yearEstablished,
items: items // a list of numbers that are Strings
.map((label) => DropdownMenuItem(
child:
Text(label.toString()),
value: label,
))
.toList(),
onChanged: (value) {
setState(() {
_yearEstablished = value;
print(value);
});
},
validator: (thisValue) {
if (thisValue == null) {
return 'Please choose your company year of establishment';
}
return null;
},
),
),
],
),
Thanks in advance for your help!
You need to use isExpanded property of DropDownFormField to solve this error.
Row(
children: [
Expanded(
child: DropdownButtonFormField<String>(
isExpanded: true,
decoration:
kTextFieldDecoration.copyWith(
hintText: 'Legal status',
labelText: 'Legal status',
),
value: _legalStatus,
items: [
'Sole proprietorship',
'Partnerships',
'Limited Liability Company (LLC)',
'Corporation',
'Small Business Corporation (S-Corporation)'
]
.map((label) => DropdownMenuItem(
child: Text(
label.toString(),
),
value: label,
))
.toList(),
onChanged: (value) {
setState(() {
_legalStatus = value;
print(value);
});
},
validator: (thisValue) {
if (thisValue == null) {
return 'Please choose your legal status';
}
return null;
},
),
),
SizedBox(
width: 16.0,
),
Container(
width: 120.0,
child: DropdownButtonFormField<String>(
decoration:
kTextFieldDecoration.copyWith(
hintText: 'Year established',
labelText: 'Year established',
),
value: _yearEstablished,
items: items // a list of numbers that are Strings
.map((label) => DropdownMenuItem(
child:
Text(label.toString()),
value: label,
))
.toList(),
onChanged: (value) {
setState(() {
_yearEstablished = value;
print(value);
});
},
validator: (thisValue) {
if (thisValue == null) {
return 'Please choose your company year of establishment';
}
return null;
},
),
),
],
),
You need to use selectedItemBuilder parameter which will control how the selected item will be displayed on the button. Then, TextOverflow.ellipsis will work with you as expected. Here's how to use it:
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return Text(item, overflow: TextOverflow.ellipsis,);
}).toList();
},

How to add autofill dropdown in flutter?

I've made a dropdown of cities and city list is coming from API. When user clicks on GPS button, it will auto fill the dropdown field. How should I auto fill the city name in dropdown? I tried by using dropdown inside textfield
TextFormField(
controller: city,
decoration:InputDecoration(
border:InputBorder.none,
prefix: DropdownButtonFormField<String>(
decoration: InputDecoration.collapsed(
hintText: 'select',
hintStyle: TextStyle(fontSize: 12,color: Colors.grey.shade600),
),
value:type,
validator: (value) => value == null? 'please select': null,
onChanged: (String newValue) {
setState(() {
type = newValue;
});
},
items: List?.map((item){
return DropdownMenuItem(
onTap: (){
selectedCity=item['city'];
// print(selectedCity);
},
value: item['id'].toString(),
child: Padding(
padding: const EdgeInsets.only(left:15.0,top: 13.0),
child: Text(item['city'],style: TextStyle(fontSize: 12,color: Colors.grey.shade600),),
),
);
})?.toList()??[]
),
),
),
You can use ready-made auto-complete packages.
Some examples:
https://pub.dev/packages/autocomplete_textfield
https://pub.dev/packages/dropdownfield

DropdownButtonFormField with validation is untappable if field is invalid

I'm having the following code statement.
Container(
height: 50,
padding: const EdgeInsets.only(left: 16, right: 16),
child: DropdownButtonFormField(
isExpanded: true,
validator: (value) => value == 0 ? errorMessage : null,
items: items
.map((e) => DropdownMenuItem(
child: Text(e,
overflow: TextOverflow.visible,
style: Style.poppinsRegularTextStyleWith(
fontSize: 14, color: color12)),
value: items.indexOf(e)))
.toList(),
value: selectedIndex,
onChanged: (value) {
setState(() {
selectedIndex = value;
if (onChanged != null) {
onChanged(items[value]);
}
});
},
),
)
After submitting the form the dropdown that has error message becomes unresponsive to tap, what i'm doing wrong?
How should i change the validator or what other fix is there for this
Can you replace the code with it
DropdownButtonFormField(
isExpanded: true,
validator: (value) => value == 0 ? errorMessage : null,
items: items.map((e) {
return DropdownMenuItem(
value: e,
child: Text(e),
);
}).toList(),
onChanged: (value) => setState(() {
if (onChanged != null) {
onChanged(items[value]);
}
})),
I am using DropdownButtonFormField in my code and it works perfect it is like;
DropdownButtonFormField(
value: _currentSugars ?? userData.sugars,
items: sugars.map((sugar) {
return DropdownMenuItem(
value: sugar,
child: Text('$sugar sugars'),
);
}).toList(),
onChanged: (val) => setState(() => _currentSugars = val),
),
The issue was the extra height on the container, making the dropdown and error message, this was causing some overlap and the tappable area wasn't there anymore.
**height: 50, <= Issue was here**
padding: const EdgeInsets.only(left: 16, right: 16),
child: DropdownButtonFormField(
isExpanded: true,
validator: (value) => value == 0 ? errorMessage : null,
items: items
.map((e) => DropdownMenuItem(
child: Text(e,
overflow: TextOverflow.visible,
style: Style.poppinsRegularTextStyleWith(
fontSize: 14, color: color12)),
value: items.indexOf(e)))
.toList(),
value: selectedIndex,
onChanged: (value) {
setState(() {
selectedIndex = value;
if (onChanged != null) {
onChanged(items[value]);
}
});
},
),
)```