Creating a custom Flutter DropDown button as a separate widget - flutter

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,
),

Related

Adding values from multiple textFields

I have a list of tiles created with the 'tolist' method, each has a textField and controller.I want to get the sum of the values of all textFields into a variable and display as text.``
here is my code: `
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> myList = [
'Materials',
'Labour',
'Plant and Equipment',
'Subcontractor'
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: SingleChildScrollView(
child: Column(
children: [
ExpansionTile(
maintainState: true,
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text('Test Code'),
Text('sum of all here',//sum of all values from each textfield here
style: TextStyle(fontSize: 16),),
],
),
children: myList.map((cost) {
return MyListTile(cost);
}).toList(),
),
],
),
));
}
}
and MyListTile code :``
class MyListTile extends StatefulWidget {
String title;
MyListTile(this.title) : super();
#override
State<MyListTile> createState() => _MyListTileState();
}
class _MyListTileState extends State<MyListTile> {
final TextEditingController _myController = TextEditingController();
double materialCost = 0.0;
#override
Widget build(BuildContext context) {
return ListTile(
subtitle: Row(
children: [
Container(
margin: const EdgeInsets.only(top: 5, bottom: 5, right: 0, left: 0),
child: SizedBox(
height: 35,
width: 150,
child: TextField(
textAlignVertical: TextAlignVertical.center,
controller: _myController,
showCursor: true,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 10),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15)),
disabledBorder: const OutlineInputBorder(),
filled: true,
labelText: 'Cost sum',
labelStyle: TextStyle(color: Colors.grey[500]),
hintText: 'Enter Cost',
hintStyle: TextStyle(color: Colors.grey[500]),
suffixIcon: InkWell(
child: const Icon(
Icons.clear,
),
onTap: () {
_myController.clear();
},
),
// isCollapsed: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15))),
),
),
),
Container(
margin: const EdgeInsets.all(3),
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
border: Border.all(color: Colors.white10, width: 1),
borderRadius: BorderRadius.circular(12)),
child: InkWell(
onTap: () {
setState(() {
materialCost = double.parse(_myController.text);
});
},
child: const Icon(
Icons.done,
),
),
)
],
),
trailing: Column(
children: [
Container(
margin: const EdgeInsets.all(3),
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: Text(
materialCost.toString(),
style: const TextStyle(
// color: mainColorShade,
fontSize: 14,
fontWeight: FontWeight.bold),
),
)
],
),
title: Text(
widget.title,
),
);
;
}
}
I have tried to find a solution from allover the internet and I can not get any
example
create textControllers for each of your textfields and pass it to your textfield inside your listTile:
class MyHomePage extends StatefulWidget {
...
}
class _MyHomePageState extends State<MyHomePage> {
List<String> myList = [
'Materials',
'Labour',
'Plant and Equipment',
'Subcontractor'
];
// look here: list of controllers for your need change it for your liking
List<TextEditingController> controllers = [
TextEditingController(),
TextEditingController(),
TextEditingController(),
TextEditingController(),
];
// look here: local state to store your sum of textfields
String sum = "";
#override
void initState() {
super.initState();
// look here: this will change sum value whenever either of the textfield's value changed
for (var i = 0; i < myList.length; i++) {
controllers[i].addListener(() {
setState(() {
sum = getSum(controllers);
});
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: SingleChildScrollView(
child: Column(
children: [
ExpansionTile(
maintainState: true,
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Test Code'),
// look here: this is your sum text
Text(sum,style: TextStyle(fontSize: 16),),
],
),
children: [
// look here: pass the controllers to your mylistTile widgets
for (var i = 0; i < myList.length; i++)
MyListTile(
title: cost,
controller: controllers[i],
),
],
),
],
),
));
}
// if you want to change the sum result, change it here
String getSum(List<TextEditingController> controllers) {
return controllers.map((e) => "${e.text} ").toString();
}
}
Don't forget to do this in your MyListTile widget, otherwise you can't pass the controllers
class MyListTile extends StatefulWidget {
MyListTile({
required this.title,
required this.controller
}) : super();
final String title;
final TextEditingController controller;
#override
State<MyListTile> createState() => _MyListTileState();
}
Use widget.controller in your MyListTile instead of _myController
class _MyListTileState extends State<MyListTile> {
final TextEditingController _myController = TextEditingController();
double materialCost = 0.0;
#override
Widget build(BuildContext context) {
return ListTile(
subtitle: Row(
children: [
Container(
margin: const EdgeInsets.only(top: 5, bottom: 5, right: 0, left: 0),
child: SizedBox(
height: 35,
width: 150,
child: TextField(
textAlignVertical: TextAlignVertical.center,
// look here:
controller: widget.controller,
...
// rest of your code here

How Can I Make This Dropdown Button Widget Reusable Iin Flutter?

I have the DropDownButton widget below, The widget works well as intended. However, I want to reuse this widget within the app, and simply pass options to it.
As an example, I want to call the same widget, but pass a different Title to the "brand" title, which is in the Row, then change the values in the dropdown as well.
How can I do that?
Below is the code:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'FLUTTER DROPDOWN BUTTON',
home: MainPage(),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final brand = [
'ACER',
'APPLE',
'ASUS',
'DELL',
'HP',
'LENOVO',
'MICROSOFT',
'TOSHIBA',
];
String? value;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Dropdown Menu',
),
centerTitle: true,
),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Padding(
padding: EdgeInsets.only(
left: 30.0,
bottom: 5.0,
),
child: Text(
"Brand",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
],
),
Container(
margin: const EdgeInsets.only(
left: 16.0,
right: 16.0,
),
padding: const EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 4.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
16,
),
border: Border.all(
color: Colors.blue,
width: 3.0,
),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: value,
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.blue,
),
iconSize: 40.0,
isExpanded: true,
items: brand.map(buildMenuItem).toList(),
onChanged: (value) => setState(
() => this.value = value,
),
),
),
),
],
),
);
}
DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
value: item,
child: Text(
item,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
);
}
VsCode have support this method can help Extract an Widget to reuseable. Of course you if you want some more functional, you need to add your constructor property for your ow.
Follow below instruction.
Left your cursor on the Widget you want extract, click on the light bub
Select Extract Widget
Type the name for new Widget, then enter.
Create a class and return your dropdown Widget from it's build method.
import 'package:digital_show_room/utils/app_colors.dart';
import 'package:digital_show_room/utils/app_styles.dart';
import 'package:flutter/material.dart';
class AppDropDownButton<T> extends StatefulWidget {
final List<DropdownMenuItem<T>> dropdownMenuItemList;
final ValueChanged<T> onChanged;
final T value;
final bool isEnabled;
final bool isBorder;
final double radius;
final TextStyle? textStyle;
final Color? color;
final Widget? icon;
const AppDropDownButton({
Key? key,
required this.dropdownMenuItemList,
required this.onChanged,
required this.value,
this.isEnabled = true,
this.isBorder = false,
this.radius = 10.0,
this.textStyle,
this.color,
this.icon,
}) : super(key: key);
#override
_AppDropDownButtonState createState() => _AppDropDownButtonState();
}
class _AppDropDownButtonState extends State<AppDropDownButton> {
#override
Widget build(BuildContext context) {
return IgnorePointer(
ignoring: !widget.isEnabled,
child: Container(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(widget.radius)),
border: widget.isBorder
? Border.all(
color: AppColors.darkGrey,
width: 0,
)
: Border(),
color: widget.isEnabled
? (widget.color ?? AppColors.indigoLight)
: AppColors.lightGrey),
child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,
itemHeight: 50.0,
style: (widget.textStyle ?? AppStyles.subTitle16Style).copyWith(
color:
widget.isEnabled ? AppColors.darkBlue : AppColors.darkGrey),
items: widget.dropdownMenuItemList,
onChanged: widget.onChanged,
value: widget.value,
dropdownColor: AppColors.white,
iconEnabledColor: AppColors.grey,
icon: widget.icon ?? Icon(Icons.arrow_drop_down),
),
),
),
);
}
}

Combine two similar classes into one class in 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 :)

Flutter : Persist Data

I am building an online shop. I have a counter[-]0[+] next to every product on the home page. I am able to add and remove products to the cart but when I switch to a different screen, my counter on the home page is reset back to 0. I would like to keep that data persistent. what would be the best way to achieve this?
cart_counter.dart
import 'package:flutter/material.dart';
import '../providers/cart.dart';
import 'package:provider/provider.dart';
import '../providers/products.dart';
class CartCounter extends StatefulWidget {
const CartCounter({Key? key}) : super(key: key);
#override
_CartCounterState createState() => _CartCounterState();
}
class _CartCounterState extends State<CartCounter> {
int numOfItems = 0;
#override
Widget build(BuildContext context) {
final product = Provider.of<Product>(context, listen: false);
final cart = Provider.of<Cart>(context, listen: false);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CounterButton(
icon: Icons.remove,
onPress: () {
if (numOfItems > 0) {
setState(() {
numOfItems--;
});
cart.removeSingleItem(product.id);
}
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 13.0),
child: Text(
numOfItems.toString(),
style: const TextStyle(
fontSize: 20.0,
),
),
),
CounterButton(
icon: Icons.add,
onPress: () {
setState(() {
numOfItems++;
cart.addItem(
product.id,
product.price,
product.title,
);
});
},
),
],
);
}
}
class CounterButton extends StatelessWidget {
final IconData icon;
final void Function() onPress;
const CounterButton({
Key? key,
required this.icon,
required this.onPress,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return SizedBox(
width: 60.0,
height: 45.0,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
elevation: 2,
backgroundColor: Theme.of(context).primaryColor,
primary: Theme.of(context).primaryColor,
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
onPressed: onPress,
child: Icon(
icon,
color: Colors.white,
size: 30.0,
),
),
);
}
}
product_item.dart
import 'package:flutter/material.dart';
import 'cart_counter.dart';
class ProductItem extends StatelessWidget {
final String id;
final String title;
final double price;
final String image;
const ProductItem(this.id, this.title, this.price, this.image, {Key? key})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: Card(
elevation: 2.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Column(
children: [
Row(
children: [
Container(
height: 50,
width: 70.0,
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
bottomRight: Radius.circular(20.0),
),
color: Theme.of(context).primaryColor,
),
child: Center(
child: Text(
title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
color: Colors.white,
),
),
),
),
],
),
Image.asset(image),
const SizedBox(
height: 10.0,
),
Text(
price.toStringAsFixed(2),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
const SizedBox(
height: 10.0,
),
const CartCounter(),
const SizedBox(
height: 20.0,
),
],
),
),
);
}
}
Use Shared Preferences or Secure Storage to store the values.
See this answer to a similar question.

Flutter DropDownButton Popup 200px below Button

I'm using a DropDownButton with a custom style inside a ListView. My problem is: the PopupMenu opens about 200-300px below the Button so it looks like the Button below that has opened:
I wrapped the Dropdown in a custom style, but i already tried removing that and that did nothing. I've also tried to use just a normal Dropdownbutton, but that had the same effect.
the corresponding build:
#override
Widget build(BuildContext context) {
homeModel = Provider.of<HomeModel>(context);
model = Provider.of<TransferModel>(context);
navigator = Navigator.of(context);
var items = model.items.entries.toList();
return Container(
color: Colors.white,
child: ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: model.items.entries.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.only(left: 30, right: 30, top: 10),
child: CustomDropDown(
errorText: "",
hint: items[index].value["label"],
items: items[index]
.value["items"]
.asMap()
.map((int i, str) => MapEntry(
i,
DropdownMenuItem(
value: i,
child: Text(str is Map
? str["displayName"].toString()
: str.toString()),
)))
.values
.toList()
.cast<DropdownMenuItem<int>>(),
value: items[index].value["selected"],
onChanged: (position) =>
model.selectItem(items[index].key, position),
),
);
},
),
);
}
CustomDropDown:
class CustomDropDown extends StatelessWidget {
final int value;
final String hint;
final String errorText;
final List<DropdownMenuItem> items;
final Function onChanged;
const CustomDropDown(
{Key key,
this.value,
this.hint,
this.items,
this.onChanged,
this.errorText})
: super(key: key);
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[100], borderRadius: BorderRadius.circular(30)),
child: Padding(
padding:
const EdgeInsets.only(left: 30, right: 30, top: 10, bottom: 5),
child: DropdownButton<int>(
value: value,
hint: Text(
hint,
style: TextStyle(fontSize: 20),
overflow: TextOverflow.ellipsis,
),
style: Theme.of(context).textTheme.title,
items: items,
onChanged: (item) {
onChanged(item);
},
isExpanded: true,
underline: Container(),
icon: Icon(Icons.keyboard_arrow_down),
),
),
),
if (errorText != null)
Padding(
padding: EdgeInsets.only(left: 30, top: 10),
child: Text(errorText, style: TextStyle(fontSize: 12, color: Colors.red[800]),),
)
],
);
}
}
edit: I've just noticed, that the popup always opens in the screen center. But I still have no idea why that is.
edit 2: thanks to #João Soares I've now narrowed down the issue: I surround the Widget with the ListView with an AnimatedContainer for opening and closing the menu. The padding of this container seems to be the culprit, but i have no idea how i can fix this, since i need that Container: (the Child is the ListView Widget)
class ContentSheet extends StatelessWidget {
final Widget child;
final bool isMenuVisible;
const ContentSheet({Key key, this.child, this.isMenuVisible}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 50),
child: AnimatedContainer(
duration: Duration(milliseconds: 450),
curve: Curves.elasticOut,
padding: EdgeInsets.only(top: isMenuVisible ? 400 : 100),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
color: Colors.white,
),
child: child
),
),
),
);
}
}
I've tried your CustomDropDown widget with the code below and it works as expected, without the dropdown showing lower in the view. Something else in your code may be affecting its position.
class DropdownIssue extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _DropdownIssueState();
}
}
class _DropdownIssueState extends State<DropdownIssue> {
int currentValue = 0;
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.grey,
child: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CustomDropDown(
hint: 'hint',
errorText: '',
value: currentValue,
items: [
DropdownMenuItem(
value: 0,
child: Text('test 0'),
),
DropdownMenuItem(
value: 1,
child: Text('test 1'),
),
DropdownMenuItem(
value: 2,
child: Text('test 2'),
),
].cast<DropdownMenuItem<int>>(),
onChanged: (value) {
setState(() {
currentValue = value;
});
print('changed to $value');
}
),
],
),
)
),
);
}
}