Combine two similar classes into one class in flutter - flutter

I have two dropdownbutton, they differ in that one has checkboxes and the other doesn't. The code is similar and I think it would be better to put everything in one class. I tried to do this, the dropdownbutton with the checkbox did not work correctly for me. Can you tell me if these 2 codes can be placed in one class? And how to do it right?
code_1
class DropdownWidget extends StatefulWidget {
List<String> items;
SvgPicture? icon;
double width;
bool isCheckbox;
DropdownWidget(
{Key? key,
required this.items,
required this.icon,
required this.width,
this.isCheckbox = false})
: super(key: key);
#override
State<DropdownWidget> createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String? selectedValue;
bool isChecked = false;
#override
void initState() {
super.initState();
if (widget.items.isNotEmpty) {
selectedValue = widget.items[1];
}
}
#override
Widget build(BuildContext context) {
return SizedBox(
width: widget.width,
child: DropdownButtonHideUnderline(
child: DropdownButton2(
items: widget.items
.map(
(item) => DropdownMenuItem<String>(
value: item,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: constants.Colors.white.withOpacity(0.1),
width: 1,
),
),
),
child: Center(
child: Row(
children: [
if (item == selectedValue)
const SizedBox(
width: 0,
),
Expanded(
child: Text(
item,
style: constants.Styles.smallTextStyleWhite,
),
),
if (item == selectedValue)
const Icon(
Icons.check,
color: constants.Colors.purpleMain,
),
],
),
),
),
),
)
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
icon: SvgPicture.asset(constants.Assets.arrowDropdown),
iconSize: 21,
buttonHeight: 27,
itemHeight: 47,
dropdownMaxHeight: 191,
dropdownWidth: 140,
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: constants.Colors.purpleMain,
),
color: constants.Colors.greyDark,
),
selectedItemBuilder: (context) {
return widget.items.map(
(item) {
return Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
Text(
item,
style: constants.Styles.bigBookTextStyleWhite,
),
],
);
},
).toList();
},
),
),
);
}
}
code_2
class CheckboxDropdown extends StatefulWidget {
List<String> items;
SvgPicture? icon;
double width;
CheckboxDropdown({
Key? key,
required this.items,
this.icon,
required this.width,
}) : super(key: key);
#override
State<CheckboxDropdown> createState() => _CheckboxDropdown();
}
class _CheckboxDropdown extends State<CheckboxDropdown> {
String? selectedValue;
bool selected = false;
final List _selectedTitles = [];
final List _selectedTitlesIndex = [];
final GFCheckboxType type = GFCheckboxType.basic;
#override
void initState() {
super.initState();
if (widget.items.isNotEmpty) {
_selectedTitles.add(widget.items[1]);
}
}
void _onItemSelect(bool selected, int index) {
if (selected == true) {
setState(() {
_selectedTitles.add(widget.items[index]);
_selectedTitlesIndex.add(index);
});
} else {
setState(() {
_selectedTitles.remove(widget.items[index]);
_selectedTitlesIndex.remove(index);
});
}
}
#override
Widget build(BuildContext context) {
return SizedBox(
width: widget.width,
child: DropdownButtonHideUnderline(
child: DropdownButton2(
items: List.generate(
widget.items.length,
(index) => DropdownMenuItem<String>(
value: widget.items[index],
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.white.withOpacity(0.1),
width: 1,
),
),
),
child: StatefulBuilder(
builder: (context, setStateSB) => GFCheckboxListTile(
value: _selectedTitles.contains(widget.items[index]),
onChanged: (bool selected) {
_onItemSelect(selected, index);
setStateSB(() {});
},
selected: selected,
title: Text(
widget.items[index],
style: constants.Styles.smallTextStyleWhite,
),
padding: const EdgeInsets.only(top: 12, bottom: 13),
margin: const EdgeInsets.only(right: 0, left: 0),
size: 22,
activeBgColor: constants.Colors.greyCheckbox,
activeBorderColor: constants.Colors.greyXMiddle,
inactiveBgColor: constants.Colors.greyCheckbox,
activeIcon: SvgPicture.asset(constants.Assets.checkboxIcon),
inactiveBorderColor: constants.Colors.greyXMiddle,
type: type,
),
),
),
),
),
hint: Row(
children: [
SvgPicture.asset(constants.Assets.carDropdown),
const SizedBox(width: 8),
_selectedTitles.length > 1
? const Text('Selecte EV',
style: constants.Styles.xSmallLtStdTextStyleWhite)
: Text(_selectedTitles.join().toString(),
style: constants.Styles.bigBookTextStyleWhite),
],
),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
icon: SvgPicture.asset(constants.Assets.arrowDropdown),
iconSize: 21,
buttonHeight: 27,
itemHeight: 47,
dropdownMaxHeight: 185,
dropdownWidth: 140,
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: constants.Colors.purpleMain,
),
color: constants.Colors.greyDark),
selectedItemBuilder: (context) {
return widget.items.map(
(item) {
return Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
Text(
item,
style: constants.Styles.bigBookTextStyleWhite,
),
],
);
},
).toList();
},
),
),
);
}
}

Create a class such as MultiDropDownBox and pass a required bool in constructor such as isCheckBox . Return the required widget as per bool value.
Example code snippet
class MultiDropdownBox extends StatefulWidget {
final bool isCheckbox;
MultiDropdownBox(
{Key? key,
required this.isCheckBox,
})
: super(key: key);
#override
State<MultiDropdownBox> createState() => _MultiDropdownBoxState();
}
class _MultiDropdownBoxState extends State<MultiDropdownBox> {
bool isChecked = widget.isChecked;
#override
Widget build(BuildContext context) {
if(isChecked){return CheckboxDropdown()};
else{return DropdownWidget()}
}
Upvote if it helped :)

Related

How can I pass a List to another class

I have a list in this file called check_symptoms.dart which the list is called _chosenItems
i want it to pass it to another file which is a stateful widget
here's my code for Check_symptoms.dart
import 'package:diagnose_app/results.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
class SymptomsChecker extends StatefulWidget {
const SymptomsChecker({Key? key}) : super(key: key);
#override
State<SymptomsChecker> createState() => _SymptomsCheckerState();
}
class _SymptomsCheckerState extends State<SymptomsChecker> {
List _items = [];
List _itemsForDisplay = [];
List _chosenItems = [];
int maxheight = 0;
ScrollController _scrollController = ScrollController();
Future<void> readJson() async {
final String response =
await rootBundle.loadString('assets/data/Symptoms.json');
final data = await json.decode(response);
setState(() {
_items = data["Symptoms"];
_itemsForDisplay = _items;
});
}
#override
void initState() {
// TODO: implement initState
readJson();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 105, 120, 255),
body: Padding(
padding: const EdgeInsets.all(5),
child: Column(
children: [
// Display the data loaded from sample.json
// _ListChosenItem(23),
SizedBox(
height: 25,
),
_searchBar(),
Divider(
height: 1,
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return _ListItem(index);
},
itemCount: _itemsForDisplay.length,
),
),
Divider(
height: 2,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: LimitedBox(
maxHeight: 200,
child: Scrollbar(
controller: _scrollController,
child: SingleChildScrollView(
//scrollDirection: Axis.horizontal,
child: Wrap(
children: _chosenItems.map((item) {
//print(_chosenItems);
return chosenItems(item);
}).toList(),
),
),
),
),
),
Divider(
color: Colors.black,
height: 10,
thickness: 1,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
height: 50,
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
// sending chosenItems to results.dart
builder: (context) => Results(list: _chosenItems)));
},
child: Text(
"Find Results",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
),
style: ElevatedButton.styleFrom(),
),
),
),
SizedBox(
height: 5,
),
],
),
),
);
}
Padding chosenItems(item) {
return Padding(
padding: const EdgeInsets.all(3.0),
child: Builder(builder: (context) {
return ElevatedButton.icon(
onPressed: () {
setState(() {
_itemsForDisplay.add(item);
//_items.add(item);
_chosenItems.remove(item);
});
},
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
textStyle:
const TextStyle(fontSize: 15, fontWeight: FontWeight.w400)),
label: Text(item),
icon: Icon(
Icons.remove_circle,
color: Color.fromARGB(255, 255, 217, 216),
),
);
}),
);
}
_searchBar() {
return Padding(
padding: const EdgeInsets.all(8),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
filled: true,
fillColor: Color.fromARGB(255, 244, 244, 244),
hintText: 'Search Symptoms'),
style: TextStyle(color: Color.fromARGB(255, 22, 25, 52)),
maxLines: 1,
onChanged: (text) {
text = text.toLowerCase();
setState(() {
_itemsForDisplay = _items.where((item) {
var itemEntity = item.toLowerCase();
return itemEntity.contains(text);
}).toList();
});
},
),
);
}
_ListItem(index) {
return Wrap(
children: [
ElevatedButton(
onPressed: () {
setState(() {
_chosenItems.add(_itemsForDisplay[index]);
_itemsForDisplay.removeAt((index));
//_items.removeAt((index));
});
},
style: ElevatedButton.styleFrom(
textStyle:
const TextStyle(fontSize: 18, fontWeight: FontWeight.w500)),
child: Text(_itemsForDisplay[index]),
),
],
);
}
_ListChosenItem(index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
children: [
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20)),
child: Text(_chosenItems[index]),
),
],
),
);
}
}
here's the way I'm receiving the list in results.dart
import 'package:flutter/material.dart';
class Results extends StatefulWidget {
final List list;
const Results({required this.list});
#override
State<Results> createState() => _ResultsState(list);
}
class _ResultsState extends State<Results> {
#override
Widget build(BuildContext context) {
print(list);
return Scaffold();
}
}
this line of code of results.dart
State<Results> createState() => _ResultsState(list);
is says:
List list Type: List
package:diagnose_app/results.dart
Don't put any logic in createState.dartno_logic_in_create_state Too
many positional arguments: 0 expected, but 1 found. Try removing the
extra arguments.
Am I passing the list in a wrong way? thanks for helping in advance.
First of all, an instance of State can access the members of its parent StatefulWidget via the widget property.
So your particular problem can be solved simply by accessing widget.list, you don't need to pass the list explicitly to _ResultsState:
import 'package:flutter/material.dart';
class Results extends StatefulWidget {
final List list;
const Results({required this.list});
#override
State<Results> createState() => _ResultsState();
}
class _ResultsState extends State<Results> {
#override
Widget build(BuildContext context) {
print(widget.list);
return Scaffold();
}
}
But further, if you do want to explicitly pass a value to a class constructor, you'll need to add the field as a member to the class and define the constructor that takes that value.

Set default value for dropdown button2 in flutter

Need help with dropdownbutton. I need to set a default value for my dropdown_button2. So that when the page opens, already 1 value is selected, which I can change in the future. Can you please tell me how to implement this function? Previously, I tried options that are already on the Internet, but for some reason it was not possible to implement with my code, perhaps
I made a mistake somewhere. Thanks in advance.
code
class DropdownWidget extends StatefulWidget {
List<String> items;
SvgPicture? icon;
double width;
DropdownWidget(
{Key? key, required this.items, required this.icon, required this.width})
: super(key: key);
#override
State<DropdownWidget> createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String? selectedValue;
#override
Widget build(BuildContext context) {
return Container(
width: widget.width,
decoration: BoxDecoration(
border: Border(
bottom: selectedValue != null
? const BorderSide(
color: constants.Colors.white,
)
: BorderSide.none,
),
),
child: DropdownButtonHideUnderline(
child: DropdownButton2(
underline: DropdownButtonHideUnderline(child: Container()),
hint: Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
const Text(
'Select',
style: constants.Styles.bigBookTextStyleWhite,
),
],
),
items: widget.items
.map((item) => DropdownMenuItem<String>(
value: item,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: constants.Colors.white.withOpacity(0.1),
width: 1,
),
),
),
child: Center(
child: Row(
children: [
if (item == selectedValue)
const SizedBox(
width: 0,
),
Expanded(
child: Text(
item,
style: constants.Styles.smallTextStyleWhite,
),
),
if (item == selectedValue)
const Icon(
Icons.check,
color: constants.Colors.purpleMain,
),
],
),
),
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
icon: SvgPicture.asset(constants.Assets.arrowDropdown),
iconSize: 21,
buttonHeight: 27,
itemHeight: 47,
dropdownMaxHeight: 191,
dropdownWidth: 140,
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: constants.Colors.purpleMain,
),
color: constants.Colors.greyDark,
),
selectedItemBuilder: (context) {
return widget.items.map(
(item) {
return Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
Text(
item,
style: constants.Styles.bigBookTextStyleWhite,
),
],
);
},
).toList();
},
),
),
);
}
}
Add the initState method and set your selectedValue there. Here's your code with the initState added so the dropdown defaults to items[0] but you should update it as it fits your use case.
class DropdownWidget extends StatefulWidget {
List<String> items;
SvgPicture? icon;
double width;
DropdownWidget(
{Key? key, required this.items, required this.icon, required this.width})
: super(key: key);
#override
State<DropdownWidget> createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String? selectedValue;
// Add the initState method to your widget
#override
void initState() {
super.initState();
// Set your "default" value here. This example sets it to items[0]
if (widget.items.isNotEmpty) {
selectedValue = widget.items.first;
}
}
#override
Widget build(BuildContext context) {
return Container(
width: widget.width,
decoration: BoxDecoration(
border: Border(
bottom: selectedValue != null
? const BorderSide(
color: constants.Colors.white,
)
: BorderSide.none,
),
),
child: DropdownButtonHideUnderline(
child: DropdownButton2(
underline: DropdownButtonHideUnderline(child: Container()),
hint: Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
const Text(
'Select',
style: constants.Styles.bigBookTextStyleWhite,
),
],
),
items: widget.items
.map((item) => DropdownMenuItem<String>(
value: item,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: constants.Colors.white.withOpacity(0.1),
width: 1,
),
),
),
child: Center(
child: Row(
children: [
if (item == selectedValue)
const SizedBox(
width: 0,
),
Expanded(
child: Text(
item,
style: constants.Styles.smallTextStyleWhite,
),
),
if (item == selectedValue)
const Icon(
Icons.check,
color: constants.Colors.purpleMain,
),
],
),
),
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
icon: SvgPicture.asset(constants.Assets.arrowDropdown),
iconSize: 21,
buttonHeight: 27,
itemHeight: 47,
dropdownMaxHeight: 191,
dropdownWidth: 140,
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: constants.Colors.purpleMain,
),
color: constants.Colors.greyDark,
),
selectedItemBuilder: (context) {
return widget.items.map(
(item) {
return Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
Text(
item,
style: constants.Styles.bigBookTextStyleWhite,
),
],
);
},
).toList();
},
),
),
);
}
}
Docs on initState

How to get the index of each element in a list flutter?

I ran into a problem. I have a Checkbox in the value method, I need to specify _isChecked[index]. But I have an error on the word index. I understand why the error is because I don't get the index of each element, I don't have these given. Do I need to iterate through all the elements of the list to solve? Or how can I get all index elements?
code
class DropdownWidget extends StatefulWidget {
List<String> items;
SvgPicture? icon;
double width;
DropdownWidget({
Key? key,
required this.items,
required this.icon,
required this.width,
}) : super(key: key);
#override
State<DropdownWidget> createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String? selectedValue;
bool isChecked = false;
List<bool> _isChecked = [];
#override
void initState() {
super.initState();
if (widget.items.isNotEmpty) {
selectedValue = widget.items[1];
}
_isChecked = List<bool>.filled(widget.items.length, false);
}
#override
Widget build(BuildContext context) {
return SizedBox(
width: widget.width,
child: DropdownButtonHideUnderline(
child: DropdownButton2(
items: widget.items
.map((item) => DropdownMenuItem<String>(
value: item,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: constants.Colors.white.withOpacity(0.1),
width: 1,
),
),
),
child: Center(
child: Row(
children: [
if (item == selectedValue)
const SizedBox(
width: 0,
),
Expanded(
child: Text(
item,
style: constants.Styles.smallTextStyleWhite,
),
),
Checkbox(
value: _isChecked[index],
onChanged: (val) {
setState(() {
_isChecked[index] = val!;
});
},
)
],
),
),
),
))
.toList(),
value: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value as String;
});
},
icon: SvgPicture.asset(constants.Assets.arrowDropdown),
iconSize: 21,
buttonHeight: 27,
itemHeight: 47,
dropdownMaxHeight: 191,
dropdownWidth: 140,
dropdownDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: constants.Colors.purpleMain,
),
color: constants.Colors.greyDark,
),
selectedItemBuilder: (context) {
return widget.items.map(
(item) {
return Row(
children: [
widget.icon ?? const SizedBox(),
const SizedBox(width: 8),
Text(
item,
style: constants.Styles.bigBookTextStyleWhite,
),
],
);
},
).toList();
},
),
),
);
}
}
List
final List<String> carList = const [
"All EV's",
'Main EV',
'<EV2>',
];
you can convert the list to a map and iterate on its keys, which will be the indices of the elements
widget.items.asMap().keys.map((index) {
return Container(
child: widget.items[index];
);
}).toList(),

Creating a custom Flutter DropDown button as a separate widget

I am working on a Flutter project, which has multiple dropdown buttons on different pages. I have created a custom dropdown button and it's working fine. But when I try to make it a separate widget (to use in other pages) in a file having some errors. below is the code I tried.
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List<Activities> _activities = [
Activities(id: 1, icon: Icons.place, title: 'Travel'),
Activities(id: 2, icon: Icons.food_bank, title: 'Eat'),
];
List<DropdownMenuItem<Activities>> activityListDropDownItems = [];
Activities selectedActivity;
int selectedActivityId = 0;
String selectedActivityTitle = '';
IconData selectedActivityIcon = Icons.addchart;
List<DropdownMenuItem<Activities>> buildActivityList(List activities) {
List<DropdownMenuItem<Activities>> items = [];
for (Activities activity in activities) {
items.add(
DropdownMenuItem(
value: activity,
child: Row(
children: [
Text(
'${activity.title}',
style: TextStyle(
color: Colors.red,
),
),
],
),
),
);
}
return items;
}
onChangeActivityListDropDownItem(Activities selected) {
setState(() {
selectedActivity = selected;
selectedActivityId = selected.id;
selectedActivityTitle = selected.title;
selectedActivityIcon = selected.icon;
});
}
#override
void initState() {
activityListDropDownItems = buildActivityList(_activities);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Custom DropDown'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$selectedActivityTitle'),
SizedBox(height: 10.0),
Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.grey,
width: 0.3,
),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
child: Row(
children: [
SizedBox(width: 10.0),
Icon(
selectedActivityIcon,
color: Colors.red.withOpacity(0.7),
),
SizedBox(width: 10.0),
Expanded(
child: DropdownButton(
hint: Text(
'Activity',
style: TextStyle(),
),
isExpanded: true,
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
underline: Container(),
),
)
],
),
),
SizedBox(height: 20.0),
//MyDropDown(
// value: selectedActivity,
// items: activityListDropDownItems,
// onChanged: onChangeActivityListDropDownItem,
//),
],
),
),
);
}
}
class MyDropDown extends StatelessWidget {
final List<DropdownMenuItem> items;
final IconData icon;
final dynamic value;
final String hintText;
final ValueChanged onChanged;
const MyDropDown(
{Key key,
#required this.items,
this.icon,
this.value,
this.hintText,
this.onChanged})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.grey,
width: 0.3,
),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
child: Row(
children: [
SizedBox(width: 10.0),
Icon(
icon,
color: Colors.red.withOpacity(0.7),
),
SizedBox(width: 10.0),
Expanded(
child: DropdownButton(
hint: Text(
hintText,
style: TextStyle(),
),
isExpanded: true,
value: value,
items: items,
onChanged: onChanged,
underline: Container(),
),
)
],
),
);
}
}
class Activities {
final int id;
final IconData icon;
final String title;
Activities({#required this.id, #required this.icon, #required this.title});
}
when I use the MyDropDown shown an error. How to pass value and onChanged to DropdownButton?
MyDropDown(
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
),
Your value expects a datetype dynamic while your passing Activities
class MyDropDown<T> extends StatelessWidget {
final T value;
const MyDropDown({Key key, this.value}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container();
}
}
Declare Object type
MyDropDown<Activies>(
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
),

Dropdown Button wont change

Hi i got stuck while write flutter code on dropdown button, where after user choosed from the list the hint wont changed to what the user choose. Can anyone help ?
So here is my code:
DropdownButton(items: [
DropdownMenuItem(value: "1", child: Text('+')),
DropdownMenuItem(value: "2", child: Text('-')),
DropdownMenuItem(value: "3", child: Text('X')),
DropdownMenuItem(value: "4", child: Text('/'))
].toList(), onChanged: (value){
setState(() {
_value = value;
});
},hint: Text('Operation'),)
I have just created an example below just check it and let me know if it works :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String selectedOperator;
var listOfOperators = [
Operators(type: "+ Addition", value: 1),
Operators(type: "- Substraction", value: 2),
Operators(type: "* Multiplication", value: 3),
Operators(type: "/ Division", value: 4),
];
#override
void initState() {
super.initState();
print(listOfOperators.length);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red, style: BorderStyle.solid, width: 0.80),
),
child: DropdownButton(
value: selectedOperator,
isExpanded: true,
icon: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (newValue) {
setState(() {
print(newValue);
selectedOperator = newValue;
});
print(selectedOperator);
},
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Select'),
),
items: listOfOperators.map((data) {
return DropdownMenuItem(
value: data.value.toString(),
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
data.type,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
),
),
),
);
}
}
class Operators {
String type;
int value;
Operators({this.type, this.value});
}
Here you go with running example:
String dropdownValue = 'Lahore';
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(
color: Colors.deepPurple
),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['Lahore', 'Islamabad', 'Faisalabad', 'Attabad']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
);
}