How to add String to Dropdownbutton - flutter

I have map<dynamic, String> with units and names.
Map timeUnits = <dynamic, String>{
TimeUnit.second: 'second',
TimeUnit.minute: 'minute',
TimeUnit.hour: 'hour',
TimeUnit.day: 'day',
TimeUnit.week: 'week',
TimeUnit.month: 'month',
TimeUnit.calendarYear: 'year',
};
How to add String to Dropdownbutton? Dropdownbutton shows this problem "The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'List'."
Dropdownbutton code:
child: DropdownButton(
isExpanded: true,
underline: Container(),
value: currentUnits[widget.convertorType],
icon: Padding(
padding: const EdgeInsets.only(right: 8.0, bottom: 6),
child: Image.asset("assets/icons/down-arrow2.png"),
),
iconSize: 35,
elevation: 20,
style: TextStyle(
fontSize: 18,
color: Color.fromRGBO(114,137,218, 1)
),
items: widget.items
.map(
(e) => DropdownMenuItem(
child: e == TimeUnit.calendarYear
? Text("year")
: e.toString().length == 3
? Text(e)
: Text(e.toString().split(".")[1]),
value: e,
),
)
.toList(),
onChanged: (newValue) {
setState(() {
updateCurrentUnit(widget.convertorType, newValue);
widget.calculate();
});
},
),

As per my understanding, it is due to the (items: widget.item) error
so change it to (items: widget.items.entries) and e to e.key or e.value
DropdownButton(
isExpanded: true,
underline: Container(),
value: currentUnits[widget.convertorType],
icon: Padding(
padding: const EdgeInsets.only(right: 8.0, bottom: 6),
child: Image.asset("assets/icons/down-arrow2.png"),
),
iconSize: 35,
elevation: 20,
style: TextStyle(
fontSize: 18,
color: Color.fromRGBO(114,137,218, 1)
),
items: widget.items.entries
.map(
(e) => DropdownMenuItem(
child: e.key == TimeUnit.calendarYear
? Text("year")
: e.toString().length == 3
? Text(e.key)
: Text(e.value),
value: e,
),
)
.toList(),
onChanged: (newValue) {
setState(() {
updateCurrentUnit(widget.convertorType, newValue);
widget.calculate();
});
},
)

first, you have to convert your Map to a list then create a list of dropDownMenuItem and then send it over to dropdown widget
for example in the code below provinces is a list and provincesItems is a List of dropdownMenueItem, i fill provincesItems with items I desire from provinces list and then send it over to dropDown Widget
for (int i = 0; i < provinces.length; i++) {
provincesItems.add(DropdownMenuItem(
value: i,
child: Column(
children: [
Text(
provinces[i].persianName,
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.normal),
),
],
),
));
}

Related

flutter: Right overflowed by pixels

Here is my code:
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[900],
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(false),
),
),
backgroundColor: Colors.grey[900],
body: Visibility(
visible: questionLoaded,
child: Builder(builder: (context) {
return Wrap(
spacing: 8.0,
runSpacing: 4.0,
direction: Axis.horizontal,
children: [
Container(
width: double.infinity,
child: Text(
question!.question,
textAlign: TextAlign.center,
style: GoogleFonts.mukta(
textStyle: TextStyle(
color: Colors.amber,
fontSize: 24,
shadows: const [
Shadow(
color: Colors.white,
offset: Offset.zero,
blurRadius: 15)
]),
),
),
),
if (question?.answer1 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer1)!,
value: "1",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer2 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer2)!,
value: "2",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer3 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer3)!,
value: "3",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer4 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer4)!,
value: "4",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
],
);
})),
);
This produces the following issue:
Any idea why and how can I fix it ?
Wrap your Text widget Flexible or Expanded widget.
Expnaded( child: Text( question!.question,....
If your text is wrapped in column then column should be wrapped expanded widget.
Expanded(
child: Column(
children: [
Text(
'datadatadatadatadatadata',
overflow: TextOverflow.ellipsis,
)
],
),
),
But if your text is wrapped in a row then your text should be wrapped expanded widget.
Row(
children: [
Expanded(
child: Text(
'datadatadatadatadatadata',
overflow: TextOverflow.ellipsis,
),
)
],
),

how to use dropdownbutton with same value?

There are few same values in the dropdown button , when i tap on that it show the error ,is there any way to use the use the dropdown with same values .I have tried using the
value :
DropdownButtonHideUnderline(
child: DropdownButton2(
iconEnabledColor: primaryColor,
selectedItemHighlightColor: primaryColor,
hint: Text(
'User type',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
),
),
items: _user_type
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
buttonHeight: 40,
// buttonWidth: doubl,
itemHeight: 40,
),
still getting the error
Value of every DropdownMenuItem should be unique. In order to make use of list which have repetitive values, you should have a unique identifier for each.
You can create a model:
class Model {
int id;
String value;
Model(this.id, this.value);
}
You can create list with repetitive values:
List<Model> list = [
Model(0, "a"),
Model(1, "a"),
Model(2, "b"),
Model(3, "b"),
Model(4, "c"),
Model(5, "c"),
];
…and you can use the list like this in your DropdownButton:
DropdownButton(
value: _selectedValue,
items: list
.map((value) => DropdownMenuItem(
value: value.id, child: Text(value.value)))
.toList(),
onChanged: (value) {
_selectedValue = value as int;
setState(() {});
},
)
Why don't you try adding a .toSet() before the .map().
The .toSet() should filter your list to unique values.
DropdownButtonHideUnderline(
child: DropdownButton2(
iconEnabledColor: primaryColor,
selectedItemHighlightColor: primaryColor,
hint: Text(
'User type',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
),
),
items: _user_type
.toSet()
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
buttonHeight: 40,
// buttonWidth: doubl,
itemHeight: 40,
),
Try below code, I have used dropdown_button2 package
Declare your variables and dropdown data
String selectedValue;
List<String> items = [
'User 1',
'User 2',
'User 3',
'User 4',
'User 5',
'User 6',
];
Your Widget:
DropdownButtonHideUnderline(
child: DropdownButton2(
isExpanded: true,
hint: Text(
'User type',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
),
),
items: items
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
color: Colors.black,
),
overflow: TextOverflow.ellipsis,
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
buttonHeight: 50,
buttonWidth: 160,
buttonPadding: EdgeInsets.all(8),
buttonDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: Colors.black26,
),
),
itemHeight: 40,
),
),
Your Dropdown button result->
Your Dropdown data result->
You can refer my answer here, here, here also for same using dropdown_below package

Multiple select options in flutter

I want to create a choice chip list of options and select multiple choices in that. I also want to change the colour when the options are selected. the options are dynamic.
I tried using the below function but the onselectionchanged displays null error and the color doesn't change when tapped. Any suggestions please??
_buildChoiceList() {
List<Widget> choices = [];
options.forEach((item) {
choices.add(Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
selected: selectedOptions.contains(item),
backgroundColor: Color(0xffff08222),
onSelected: (selected) {
setState(() {
selectedOptions.contains(item)
? selectedOptions.remove(item)
: selectedOptions.add(item);
widget.onSelectionChanged(selectedOptions);
});
},
),
));
});
return choices;
}
List<String> hobbyList = [
'Shopping',
'Comedy',
'Brunch',
'Music',
'Road Trips',
'Tea',
'Trivia',
'Comedy',
'Clubbing',
'Drinking',
'Wine',
'Hiking',
'Yoga',
'Volleyball',
'Craft Beer',
'Dogs',
'Cats',
'Activism',
'Vlogging',
'Museum',
'Dancing',
'Running',
'Singing',
'Make-Up',
'Concert',
'Cafe',
'Theater',
'Baking',
'Gardening',
'Cooking',
'Video Games',
'Camping'
];
List<String>? selectedHobby = [];
Wrap(children: hobbyList.map(
(hobby) {
bool isSelected = false;
if (selectedHobby!.contains(hobby)) {
isSelected = true;
}
return GestureDetector(
onTap: () {
if (!selectedHobby!.contains(hobby)) {
if (selectedHobby!.length < 5) {
selectedHobby!.add(hobby);
setState(() {});
print(selectedHobby);
}
} else {
selectedHobby!
.removeWhere((element) => element == hobby);
setState(() {});
print(selectedHobby);
}
},
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 5, vertical: 4),
child: Container(
padding: EdgeInsets.symmetric(
vertical: 5, horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: isSelected
? kActiveColor
: Colors.grey,
width: 2)),
child: Text(
hobby,
style: TextStyle(
color:
isSelected ? kActiveColor : Colors.grey,
fontSize: 14),
),
)),
);
},
).toList(),
),
use this plugin here
this is the sample code from a project
Expanded(
child: MultiSelectDialogField(
initialValue:
profileImage['height'] ?? [],
searchable: true,
listType: MultiSelectListType.CHIP,
buttonText: heightList.isEmpty
? Text(
"No Hieght",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
)
: Text(
"Height",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
title: Text('Height'),
items: HeightList().height.map((e) => MultiSelectItem(e, e))
.toList(),
decoration: BoxDecoration(color:Colors.white.withOpacity(0.2),
borderRadius:BorderRadius.circular(10),),
buttonIcon: Icon(Icons.arrow_drop_down_outlined,
color:Colors.white.withOpacity(0.7),),
onConfirm: (values) {
heightList = values;
setState(() {
heightLenght = heightList.length;
});
},
chipDisplay: MultiSelectChipDisplay( onTap: (value) {
setState(() {
heightList.remove(value);
});
},
),
)),

Radio Button while using in List builder

I faced problem of separating value of radio button . As I use multiple radio buttons in multiple list that i get from APi. so every time , when i select one radio button ,it selects all radio button of this type in all list. for example: radio 1 = check , radio 2 = unchecked in list 1 and list 2. i select radio 1 of list 1 but both radio 1 of list 1 and list 2 selected.
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:http/http.dart' as http;
import 'package:progress_dialog/progress_dialog.dart';
import 'package:project40/Constants/APIConstants.dart';
import 'package:project40/Constants/styleConstant.dart';
import 'package:project40/screens/home_screen.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:project40/api/add_filter_api.dart';
import 'package:project40/provider/add_post_provider.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:project40/Constants/globals.dart' as globals;
class FilterScreen extends StatefulWidget {
#override
_FilterScreenState createState() => _FilterScreenState();
}
class _FilterScreenState extends State<FilterScreen> {
var jsonData;
//String filterVariable;
int school_everyone = 0;
bool all_Feed = true;
AddPostProvider _addPostProvider;
int length = 0;
int v = 0;
Future mySchools() async {
print("test");
//loading dialog appears
ProgressDialog pr;
pr = new ProgressDialog(context, showLogs: true);
pr.style(
progressWidget: Container(
width: 50,
child: Lottie.asset("assets/json/360-loader.json"),
),
message: 'Please wait...');
pr.show();
//api link
String url = baseURL + mySchoolURL;
//getting user token
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("token");
print(token);
//create post request
http.Response response = await http.get(url, headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer $token',
}).catchError((e) => print(e));
print('successs');
pr.hide();
if (response == null) {
//appear dialog if any error will be occured
Alert(
context: context,
title: "",
type: AlertType.none,
desc: "Something went wrong. Please try again",
buttons: [
DialogButton(
child: Text(
"OK",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
pr.hide();
},
width: 120,
)
],
).show();
} else {
jsonData = jsonDecode(response.body);
if (jsonData["status_code"] == 200) {
print(jsonData);
// if (all_Feed == true) {
// filterVariable = "All School";
// }
// print(filterVariable);
pr.hide();
//store the no of institutions
length = jsonData["data"].length;
setState(() {});
} else {
pr.hide();
//if error occured
Alert(
context: context,
type: AlertType.none,
title: "",
desc: jsonData["message"],
buttons: [
DialogButton(
child: Text(
"OK",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
pr.hide();
},
width: 120,
)
],
).show();
}
}
return jsonDecode(response.body);
}
#override
void initState() {
super.initState();
mySchools();
if (all_Feed == true) {
school_everyone = 0;
}
if (school_everyone == 1) {
all_Feed = false;
}
// if (all_Feed == false) {
// setState(() {
// selectedRadio(2);
// });
// }
// if (school_everyone == 1) {
// setState(() {
// all_school = 0;
// });
// }
}
void selectedRadio(int value) {
setState(() {
all_Feed = false;
school_everyone = value;
});
}
#override
Widget build(BuildContext context) {
_addPostProvider = Provider.of<AddPostProvider>(context, listen: false);
return Material(
child: Scaffold(
backgroundColor: Colors.grey,
body: Stack(
//alignment: AlignmentDirectional.topCenter,
children: [
Container(
padding: EdgeInsets.only(top: 5),
decoration: BoxDecoration(
//borderRadius: BorderRadius.circular(50),
),
child: Padding(
padding: const EdgeInsets.only(top: 45),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
),
color: Colors.white,
),
child: Column(
children: [
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(Icons.arrow_back),
),
onTap: () {
Navigator.pop(context);
},
),
Text(
"Feed Filter",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: "Roboto",
fontSize: 20,
fontWeight: FontWeight.bold),
),
Container(width: 32.0),
],
),
Divider(
thickness: 1,
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: GestureDetector(
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()));
},
child: allFilter(
Checkbox(
value: all_Feed,
activeColor: Colors.black,
onChanged: (value) {
setState(() {
all_Feed = value;
if (all_Feed == true) {
school_everyone = 0;
} else {
school_everyone = 1;
}
});
}),
Text(
"All school",
style: DayMoodRobotoStyle.heading5c,
)),
),
),
Expanded(
child: ListView.builder(
itemCount: length,
itemBuilder: (context, index) {
return SingleChildScrollView(
child: Container(
child: schoolUseage(
jsonData["data"][index]["institution"]
["name"] ??
"",
jsonData["data"][index]["institution"]
["none"] ??
"",
jsonData["data"][index]["institution"]
["_id"] ??
"",
jsonData["data"][index]["year"]["year"] ??
"",
jsonData["data"][index]["year"]["_id"] ??
"",
jsonData["data"][index]["program"] == null
? ""
: jsonData["data"][index]["program"]
["title"],
jsonData["data"][index]["program"] == null
? ""
: jsonData["data"][index]["program"]
["_id"],
index),
),
);
}),
),
InkWell(
onTap: () async {
// var response =
// await GetFilterPostAPI().getFilterPostApi(
// ids: globals.filterVariable,
// );
// print('add filter response$response');
// if (response['status_code'] == 200) {
// _addPostProvider.addPostProgress = false;
Navigator.pop(context);
Fluttertoast.showToast(
msg: 'Filter Add Successfully..');
// _addPostProvider.addPostProgress = false;
// } else {
// Fluttertoast.showToast(msg: response['message']);
// _addPostProvider.addPostProgress = false;
// }
},
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child: Container(
alignment: Alignment.center,
width: double.infinity,
height: 55.0,
margin: EdgeInsets.symmetric(
horizontal: 20,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28.0),
color: const Color(0xff0188ba),
boxShadow: [
BoxShadow(
color: const Color(0x333F51B5).withOpacity(0.2),
offset: Offset(0, 20),
blurRadius: 20,
),
],
),
child: Text(
'Filter',
style: DayMoodRobotoStyle.heading5,
textAlign: TextAlign.center,
),
),
),
SizedBox(
height: 20,
),
],
),
),
),
),
],
),
),
);
}
Widget schoolInfo(Radio icon, Expanded schoolname) {
return Row(
children: [icon, schoolname],
);
}
Widget allFilter(Checkbox icon, Text schoolname) {
return Row(
children: [icon, schoolname],
);
}
Widget schoolUseage(
String schooolName,
String school_id,
String _id,
String classOf,
String classof_id,
String department,
String department_id,
int index) {
String s1 = index.toString();
String s2 = school_everyone.toString();
String s = s1 + s2;
v = int.parse(s);
return Column(
children: [
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Text(
schooolName,
style: TextStyle(
color: all_Feed == true ? Colors.grey : Colors.blue,
fontSize: 17,
fontFamily: "Ubuntu",
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: all_Feed == true
? IgnorePointer(
ignoring: true,
child: schoolInfo(
Radio(
activeColor: Colors.black,
value: null,
groupValue: index,
onChanged: (value) {
selectedRadio(value);
globals.filterVariable =
"all_" + school_id + "program_" + _id;
}),
Expanded(
child: Text(
"Everyone",
style: TextStyle(
fontFamily: 'Ubuntu',
fontSize: 15,
color: Colors.grey,
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
),
)),
)
: schoolInfo(
Radio(
activeColor: Colors.black,
value: 1,
groupValue: v,
onChanged: (value) {
setState(() {
// String s1 = index.toString();
// String s2 = value.toString();
// String s = s1 + s2;
// v = int.parse(s);
selectedRadio(value);
globals.filterVariable = "all_$_id";
});
}),
Expanded(
child: Text(
"Everyone",
style: DayMoodRobotoStyle.heading5c,
),
)),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: all_Feed == true
? IgnorePointer(
child: schoolInfo(
Radio(
activeColor: Colors.black,
value: 2,
groupValue: school_everyone,
onChanged: (value) {
selectedRadio(value);
}),
Expanded(
child: Text(
"None",
style: TextStyle(
fontFamily: 'Ubuntu',
fontSize: 15,
color: Colors.grey,
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
),
)),
)
: schoolInfo(
Radio(
activeColor: Colors.black,
value: 2,
groupValue: v,
onChanged: (value) {
setState(() {
// String s1 = index.toString();
// String s2 = value.toString();
// String s = s1 + s2;
// v = int.parse(s);
selectedRadio(value);
globals.filterVariable = "none_" + _id;
});
}),
Expanded(
child: Text(
"None",
style: DayMoodRobotoStyle.heading5c,
),
)),
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: all_Feed == true
? IgnorePointer(
child: schoolInfo(
Radio(
activeColor: Colors.black,
value: 2,
groupValue: school_everyone,
onChanged: (value) {
selectedRadio(value);
}),
Expanded(
child: Text(
department + " Only",
style: TextStyle(
fontFamily: 'Ubuntu',
fontSize: 15,
color: Colors.grey,
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
maxLines: 2,
),
),
),
)
: schoolInfo(
Radio(
activeColor: Colors.black,
value: 3,
groupValue: v,
onChanged: (value) {
setState(() {
// String s1 = index.toString();
// String s2 = value.toString();
// String s = s2 + s1;
// v = int.parse(s);
selectedRadio(value);
globals.filterVariable = "program_" + _id;
});
}),
Expanded(
child: Text(
department + " Only",
style: DayMoodRobotoStyle.heading5c,
maxLines: 2,
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: all_Feed == true
? IgnorePointer(
child: schoolInfo(
Radio(
activeColor: Colors.black,
value: classof_id,
groupValue: school_id,
onChanged: (value) {
selectedRadio(value);
}),
Expanded(
child: Text(
"Class of " + classOf + " Only",
style: TextStyle(
fontFamily: 'Ubuntu',
fontSize: 15,
color: Colors.grey,
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
),
)),
)
: schoolInfo(
Radio(
activeColor: Colors.black,
value: 4,
groupValue: v,
onChanged: (value) {
setState(() {
// String s1 = index.toString();
// String s2 = value.toString();
// String s = s2 + s1;
// v = int.parse(s);
selectedRadio(value);
globals.filterVariable = "year_" + _id;
//classOf + "_" + school_id;
});
}),
Expanded(
child: Text(
"Class of " + classOf + " Only",
style: DayMoodRobotoStyle.heading5c,
),
)),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: all_Feed == true
? IgnorePointer(
child: schoolInfo(
Radio(
activeColor: Colors.black,
value: all_Feed == true ? 0 : department_id,
groupValue: school_id,
onChanged: (value) {
selectedRadio(value);
}),
Expanded(
child: Text(
department + " - " + classOf,
style: TextStyle(
fontFamily: 'Ubuntu',
fontSize: 15,
color: Colors.grey,
letterSpacing: 0.17,
fontWeight: FontWeight.w700),
),
)),
)
: schoolInfo(
Radio(
activeColor: Colors.black,
value: 5,
groupValue: v,
onChanged: (value) {
setState(() {
// String s1 = index.toString();
// String s2 = value.toString();
// String s = s2 + s1;
// v = int.parse(s);
selectedRadio(value);
globals.filterVariable = "programyear_" + _id;
// department + classOf + "_" + school_id;
});
}),
Expanded(
child: Text(
department + " - " + classOf,
style: DayMoodRobotoStyle.heading5c,
),
)),
),
SizedBox(
height: 20,
),
],
);
}
}
Here is the minimum implementation of 2Radio button groups.
class _TestState extends State<Test> {
int group1Value;
int group2Value;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Radio"),
),
body: Column(
children: [
//Let suppose this is group 1
Row(
children: [
Radio(
value: 0,
groupValue: group1Value,
onChanged: (value) {
setState(() {
group1Value = value;
});
},
),
Expanded(child: Text("Radio1")),
],
),
Row(
children: [
Radio(
value: 1,
groupValue: group1Value,
onChanged: (value) {
setState(() {
group1Value = value;
});
},
),
Expanded(child: Text("Radio2")),
],
),
Row(
children: [
Radio(
value: 2,
groupValue: group1Value,
onChanged: (value) {
setState(() {
group1Value = value;
});
},
),
Expanded(child: Text("Radio3")),
],
),
SizedBox(height: 20),
Text(
"Second Group",
style: Theme.of(context).textTheme.subtitle1.copyWith(
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 20),
//suppose this is group 2
Row(
children: [
Radio(
value: 0,
groupValue: group2Value,
onChanged: (value) {
setState(() {
group2Value = value;
});
},
),
Expanded(child: Text("Radio1")),
],
),
Row(
children: [
Radio(
value: 1,
groupValue: group2Value,
onChanged: (value) {
setState(() {
group2Value = value;
});
},
),
Expanded(child: Text("Radio2")),
],
),
Row(
children: [
Radio(
value: 2,
groupValue: group2Value,
onChanged: (value) {
setState(() {
group2Value = value;
});
},
),
Expanded(child: Text("Radio3")),
],
),
],
),
);
}
}
Here are the results

Error while displaying value in drop down menu

I have implemented a dropdownmenu in which we have select university. Based on the university you get the option,for eg: if University of Mumbai is being selected only Computer Engineering is shown for selecting the department,while for University of Pune all the departments are shown.
Dropdownmenu works properly but the value selected in the menu is not displayed.
When i implement the parameter value i get the below error:
There should be exactly one item with [DropdownButton]'s value: .
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 827 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
This is the code i implemented:
var _universities = ["Savitribai Phule Pune University" , "University of Mumbai" , "other"];
List<DropdownMenuItem<String>> menuitems = List();
final sppu = {
"1" : "Computer Engineering",
"2" : "Electronics & Telecommunications",
"3" : "Information Technology",
"4" : "Mechanical Engineering"
};
final uom = {
"1" : "Computer Engineering",
};
final other = {
"1" : "Inactive",
};
void populatesppu(){
for(String key in sppu.keys){
menuitems.add(DropdownMenuItem<String>(
value: sppu[key],
child: Center(
child: Text(
sppu[key],
),
),
));
}
}
void populateuom(){
for(String key in uom.keys){
menuitems.add(DropdownMenuItem<String>(
value: uom[key],
child: Center(
child: Text(
uom[key],
),
),
));
}
}
void populateother(){
for(String key in other.keys){
menuitems.add(DropdownMenuItem<String>(
value: other[key],
child: Center(
child: Text(
other[key],
),
),
));
}
}
void valuechanged(_value){
if(_value == "Savitribai Phule Pune University"){
menuitems = [];
populatesppu();
}else if(_value == "University Of Mumbai"){
menuitems = [];
populateuom();
}else if(_value == "Other"){
menuitems = [];
populateother();
}
setState(() {
value = _value;
_currentval = _value;
disabledropdown = false;
});
}
void secondvaluechanged(_value){
setState(() {
value = _value;
_currentval2 =_value;
});
}
Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: bgColor,
),
padding: EdgeInsets.only(left: 20,top: 20,right: 20),
child: Form(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("University Details",
style: TextStyle(color: Colors.white,fontSize: 22,fontWeight: FontWeight.bold),),
SizedBox(height: 10,),
Padding(
padding: EdgeInsets.all(5.0),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: EdgeInsets.only(left: 12.0,right: 12.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.white,width: 2.0),
borderRadius: BorderRadius.circular(12.0),
),
child: DropdownButton<String>(
items:[
DropdownMenuItem<String>(
value: "Savitribai Phule Pune University",
child: Center(
child: Text("Savitribai Phule Pune University"),
),
),
DropdownMenuItem<String>(
value: "University Of Mumbai",
child: Center(
child: Text("University Of Mumbai"),
),
),
DropdownMenuItem<String>(
value: "Other",
child: Center(
child: Text("Other"),
),
)
],
onChanged: (_value) => valuechanged(_value),
hint:Text("SELECT UNIVERSITY",
style: TextStyle(color: Colors.white),),
elevation: 5,
icon: Icon(Icons.arrow_drop_down,color: Colors.black,),
iconSize: 36,
isExpanded: true,
style: TextStyle(color: Colors.black,fontSize: 20),
//value: _currentval,
//value: value,
),
),
),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: EdgeInsets.only(left: 12.0,right: 12.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.white,width: 2.0),
borderRadius: BorderRadius.circular(12.0),
),
child: DropdownButton<String>(
items:
menuitems,
onChanged: disabledropdown ? null : (_value) => secondvaluechanged(_value),
hint: Text(
"SELECT DEPARTMENT",
style: TextStyle(color: Colors.white)),
disabledHint: Text(
"First Select Any University",
style: TextStyle(color: Colors.white),
),
elevation: 5,
icon: Icon(Icons.arrow_drop_down,color: Colors.black,),
iconSize: 36,
isExpanded: true,
style: TextStyle(color: Colors.black,fontSize: 18),
//value: _currentval2,
//value: value,
),
),
),
),
SizedBox(height: 4,),
Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
padding: EdgeInsets.only(left: 12.0,right: 12.0),
child: TextFormField(
decoration: InputDecoration(
labelText: "College/Organization(in short)",
labelStyle: TextStyle(color: Colors.white,fontSize: 19),
),
style: TextStyle(color: Colors.white,fontSize: 23),
onChanged: (val) {
setState(() {
name=val;
});
},
),
),
),
SizedBox(height: 10,),
RaisedButton(
textColor: Colors.deepPurple,
onPressed: ()async {},
color: Colors.white,
child: Text("ADD",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 17,
fontWeight: FontWeight.bold),
),
),
//Text("$value",),
],
),
)
),
SizedBox(height: 20,),
]
,),
I hope this will help, when _changeDept() is called, don't forget to update department to default value Select or something. In your case, you should change in valuechanged(). In case you don't want to use Select as default value, _selectedDeptVal = _getDeptItem(_selectedUniVal).first
class _MyHomePageState extends State<MyHomePage> {
final _universities = const [
"Savitribai Phule Pune University",
"University of Mumbai",
"other",
];
final sppu = const {
"1": "Computer Engineering",
"2": "Electronics & Telecommunications",
"3": "Information Technology",
"4": "Mechanical Engineering"
};
final uom = const {
"1": "Computer Engineering",
};
final other = const {
"1": "Inactive",
};
var _selectedUniVal;
var _selectedDeptVal = 'Select';
List<String> _deptItem = ['Select'];
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
children: <Widget>[
DropdownButton(
value: _selectedUniVal,
onChanged: (val) => _changeDept(currentUni: val),
items: _universities.map(
(item) {
return DropdownMenuItem(
child: Text('$item'),
value: item,
);
},
).toList(),
),
DropdownButton(
value: _selectedDeptVal,
onChanged: (val) => setState(() => _selectedDeptVal = val),
items: _deptItem.map(
(item) {
return DropdownMenuItem(
child: Text('$item'),
value: item,
);
},
).toList(),
),
],
),
),
),
);
}
void _changeDept({String currentUni}) {
setState(
() {
// update current university
_selectedUniVal = currentUni;
// reset dept val
_selectedDeptVal = 'Select';
// update corresponding department
// clear list
_deptItem = ['Select'];
_deptItem.addAll(_getDeptItem(_selectedUniVal));
},
);
}
List<String> _getDeptItem(String currentUni) {
switch (currentUni) {
case 'Savitribai Phule Pune University':
return sppu.values.toList();
break;
case 'University of Mumbai':
return uom.values.toList();
break;
case 'other':
default:
return other.values.toList();
}
}
}
[Edited]
When [Pune and Mechanical Engineering] is selected state, even you change to [Mumbai], department value is still holding [Mechanical Engineering]. Actually, [Mechanical Engineering] isn't in the uom. That's the problem. So, you have to update _selectedDeptVal.