Need to pass dropdown selected value from OrderListScreen to firebase collection order. Dont know the proper
way of passing this field value to be reflect in firebase. Code for dropdown is ok
need to get that selected value to be able to pass it to orderStatus field. Please help.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
class OrderListScreen extends StatefulWidget {
const OrderListScreen({Key? key}) : super(key: key);
#override
State<OrderListScreen> createState() => _OrderListScreenState();
}
class _OrderListScreenState extends State<OrderListScreen> {
String? newvalue;
#override
Widget build(BuildContext context) {
String dropdownvalue = 'Pending';
return Material(
child: Container(
child: Column(
children: <Widget>[
Text(" Please select the order status from the dropdown Below:",
style: TextStyle(backgroundColor: Colors.orange)),
Container(
child: Material(
child: DropdownButton<String>(
value: newvalue,
items: <String>[
'Pending',
'Confirmed',
'Dispatched',
'Received'
].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newvalue) {
setState(() {
this.newvalue = newvalue;
});
},
),
)),
],
),
),
);
}
}
This question has already been answered in this thread
on select something from dropdown the value will be stored in dropdownValue
then to store to firebase
FirebaseFirestore.instance
.collection("collection")
.doc(result.user.uid)
.set({
'Name': _Name.text,
'myDropdownValue":dropdownValue
});
Related
I'm new to Flutter and I'm working on a localization feature using the easy_localizations package. I created a dropdown that shows languages you can switch to and it works perfectly fine when the dropdown is directly on the page. But since it will be on every page, I want to have the dropdown as a custom widget instead, and then just import it on the pages, like this:
const Padding(
padding: xPadding25,
child: DropDown(),
),
However, that does not work. I'm still able to click on the dropdown and choose a language, but it doesn't translate the pages anymore. I think it has to do something with the context it's translating, but I don't know how to make it so that it will take context of the pages and not its own if it makes sense.
Here's the code for the DropDown widget:
class DropDown extends StatefulWidget {
const DropDown({Key? key}) : super(key: key);
#override
State<DropDown> createState() => _DropDownState();
}
String dropdownValue = 'English';
class _DropDownState extends State<DropDown> {
#override
Widget build(BuildContext context) {
return (DropdownButton<String>(
icon: const Icon(
Icons.language,
color: scTealColor,
),
value: dropdownValue,
elevation: 16,
style: smBodyStyle,
underline: Container(
height: 2,
color: scTealColor,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue ?? "";
if (dropdownValue == 'French') {
context.setLocale(const Locale('fr'));
} else {
context.setLocale(const Locale('en'));
}
});
},
items: <String>['English', 'French']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
));
}
}
Any ideas on how to implement it so that the translation works when imported to pages as a custom widget? Thanks!
Have you tried to pass context into your dropdown class ? for i.e.,
const Padding(
padding: xPadding25,
child: DropDown(context),
),
I am getting this error in the console when I am trying to use flutter DropdownButton Widget.
package:flutter/src/material/dropdown.dart': Failed assertion: line 1252 pos 12: 'widget.items!.where((DropdownMenuItem item) => item.value == widget.value).length == 1': is not true.
There is a long traceback...
Here I am adding small code sample that will reproduce this error... Anyone can simply copy paste in main.dart file
// flutter import
import 'package:flutter/material.dart';
void main() {
runApp(const BugReportApp());
}
class BugReportApp extends StatefulWidget {
const BugReportApp({Key? key}) : super(key: key);
#override
State<BugReportApp> createState() => _BugReportAppState();
}
class _BugReportAppState extends State<BugReportApp> {
final TextEditingController _dropdownController = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bug Report',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Flex(direction: Axis.vertical, children:[
DropdownButton<String>(
value: _dropdownController.text == ""
? null
: _dropdownController.text,
items: ["hello, world", "how are you", "goodbye"]
.map((_value) => DropdownMenuItem<String>(
child: Text(
_value,
)))
.toList(),
onChanged: (_value) {
setState(() {
_dropdownController.text = _value ?? _dropdownController.text;
});
},
),
],),
);
}
}
I was expecting dropown to work normally but, I don't know why it didn't.
You are missing value on DropdownMenuItem.
.map((_value) => DropdownMenuItem<String>(
value: _value, // this
child: Text(
_value,
)))
Also make sure to use Scaffold on home.
Try this code, also added some explanation in the code:
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _dropdownController = TextEditingController();
String? dropDownValue = 'hello, world'; // add one value as the defaul one which must exists in the dropdown value
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
Flex(direction: Axis.vertical, children:[
DropdownButton<String>(
value: dropDownValue, // this place should not have a controller but a variable
onChanged: (_value) {
setState(() {
dropDownValue = _value;
});
},
items: ["hello, world", "how are you", "goodbye"]
.map<DropdownMenuItem<String>>((String _value) => DropdownMenuItem<String>(
value: _value, // add this property an pass the _value to it
child: Text(_value,)
)).toList(),
),
])
],
),
);
}
}
please add the VALUE field in both DropdownMenuItem and DropdownButton to prevent error
I have a list of reasons stored in my form controller using GetX
class formController extends GetxController {
String rejectreason1 = "Overheat";
List reasons = [
"Broken",
"Missing",
"Wet Wiring",
"Overheat",
"Orange",
"Obergene"
];
Widget Class:
class ReasonForm extends StatelessWidget {
formController formC = Get.put(formController());
ReasonForm(this.index, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// TODO: implement build
return Form(
// key: formKey1,
child: Column(children: [
DropdownButtonFormField<String>(
decoration: const InputDecoration(icon: Icon(Icons.event)),
value: "Overheat",
icon: const Icon(Icons.arrow_downward),
style: const TextStyle(color: Colors.deepPurple),
items: formC.reasons.map((value) {
return DropdownMenuItem(
value: value.toString(),
child: Text(value),
);
}).toList(),
onChanged: (value) {
formC.rejectreason1 = value!;
print("Selected ${value}");
},
),
]),
);
}
}
and in the dropdown list with it being mapped when onChanged is called all the values can be stored and printed out but for some reason the item "Overheat" doesn't work. Other words such as "Others" also doesn't work either, but all the rest like orange, missing and others can be selected and printed out in the console.
I think its because you put value: "Overheat", so you can't change it because onTap function change formC.rejectreason1 but you dont put that value on your dropdown. Try to change it to value: formC.rejectreason1
I have this widget:
DropdownButton<String>(
value: rentPeriod,
items: rentPeriods.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(translate("expense.$value")),
);
}).toList(),
onChanged: (value) async {
setState(() {
rentPeriod = value;
});
},
),
How can I disable, let's say, the first option of the list?
i dont think there is any straight forward way of disabling a DropdownMenuItem
but you can have a list of the DropdownMenuItems you want to disable and then when you run setState you can check if that DropdownMenuItem is contained in that list and if it is then do nothing, also check by the DropdownMenuItem text if its contained in that list and if it is then change the color to be greyed out.
Like this
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
var rentPeriods = <String>['one', 'two'];
final disabledItems = ['one'];
var rentPeriod;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: rentPeriod,
items: rentPeriods.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
translate("expense.$value"),
style: TextStyle(
color: disabledItems.contains(value) ? Colors.grey : null,
),
),
);
}).toList(),
onChanged: (value) async {
if (!disabledItems.contains(value)) {
setState(() {
rentPeriod = value;
});
}
},
);
}
}
You can create your own disable customization, changing the color and the callback of onChangedfunction in the DropdownButton, like this example:
https://dartpad.dev/587b44d2f1b06e056197fcf705021699?null_safety=true
for an authentication I would like to recover the base_url of the company chosen from a drop-down list, but I can't do it, being a beginner a little help will be welcome.
here is the code of the dropdownlist:
class DropDown extends StatefulWidget {
DropDown({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<DropDown> {
String _mySelection;
String _myBaseUrl;
List<Map> _myJson = [{"id":2,"society":"test","baseUrl":"url.com"},{"id":1,"society":"planeef","baseUrl":"url.com"}];
#override
Widget build(BuildContext context) {
return Container(
child: new DropdownButton<String>(
isDense: true,
hint: new Text("Select"),
value: _mySelection,
onChanged: (String newValue) {
setState(() {
_mySelection = newValue;
});
},
items: _myJson.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: new Text(
map["society"],
),
);
}).toList(),
),
);
}
}
Check the code below. You can use singleWhere function to retrieve the element from the id value you are getting from the dropdown and then read baseUrl from the element.
The singleWhere function matches and returns a single element from the list based on the condition we provide.
Note -
The singleWhere function throws an error by default if there are duplicates or no element is found. You might need to also pass the orElse parameter to singleWhere or add some error handling in that case.
More about that can be found here.
class _MyHomePageState extends State<MyHomePage> {
String _mySelection;
List<Map> _myJson = [{"id":2,"society":"test","baseUrl":"url.com"},{"id":1,"society":"planeef","baseUrl":"url.com"}];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: new DropdownButton<String>(
isDense: true,
hint: new Text("Select"),
value: _mySelection,
onChanged: (String newValue) {
Map<dynamic,dynamic> _myElement = _myJson.singleWhere((test) => test["id"] == int.parse(newValue));
print(_myElement["baseUrl"]);
//Add the above two lines
setState(() {
_mySelection = newValue;
});
},
items: _myJson.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: new Text(
map["society"],
),
);
}).toList(),
),
)
);
}
}