I'm using firebase real-time database and I have a form where the user adds the information to the database using it, but I'm stuck with the DropdownButtonFormField, how can I store the value in my database when the form button is pressed?
I used to use the controller when it was TextFormField, but now, I don't know what to do
DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0)),
borderSide:
BorderSide(width: 2, color: appColor),
),
labelText: 'Location',
labelStyle: TextStyle(
fontSize: 20, color: Colors.black)),
isExpanded: true,
// Initial Value
value: selectedLocation,
icon: const Icon(
Icons.keyboard_arrow_down,
color: appColor,
),
// Array list of items
items: Locations.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newLocation) {
setState(() {
selectedLocation = newLocation!;
});
},
),
you get the selectedLocation value and pass that to firebase method. print selectedLocation in the onChange method then when ever you click item in dropdown, the selectedLocation will change.
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
await ref.set({
"selectedLocation": selectedLocation ,
});
Related
My application contains localizations (translation "en","ar"), in my translation JSON files there are cities that users will choose while registration process these cities appears in a DropDownButtonFormField widget as follows:
final provincesField = DropdownButtonFormField<String>(
value: dropDownValue,
onChanged: (String? newValue) {
setState(() {
dropDownValue = newValue!;
});
},
items: provinces.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: SizedBox(
width: 100.0,
child: Text(value, textAlign: TextAlign.center),
));
}).toList(),
elevation: 4,
decoration: InputDecoration(
prefixIcon: Icon(Icons.flag_circle),
labelText: AppLocalizations.of(context)!.chooseProvinence,
alignLabelWithHint: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
the cities are declared in this list:
List<String> provinces = [
'عمان',
'إربد',
'الزرقاء',
'المفرق',
'الطفيلة',
'عجلون',
'معان',
'الكرك',
'مادبا',
'العقبة',
'البلقاء',
'جرش'
];
String dropDownValue = 'عمان';
what am trying to achieve is that cities will appear to user based on the app language. I have tried to use AppLocalizations.of(context)!.city inside of the list but its not working so i believe there is some way to declare the list values based on localization, ill appreciate any help
Suppose below localizations data is your cities list
English:
"Dhaka" : "Dhaka",
"Chittagong" : "Chittagong",
"Cumilla" : "Cumilla",
"Rajshahi" : "Rajshahi",
"Bhola" : "Bhola",
Arabic:
"Dhaka" : "دكا",
"Chittagong" : "شيتاغونغ",
"Cumilla" : "كوميلا",
"Rajshahi" : "راجشاهي",
"Bhola" : "بولا",
initialize your the localization keys of your cities and dropDownValue
List<String> provinces = [
"Dhaka",
"Chittagong",
"Cumilla",
"Rajshahi",
"Bhola",
];
String dropDownValue = 'Dhaka';
here is the widget. I used getx localization. So I used 'tr' after the child text of DropdownMenuItem. I hope it's can help u.
Widget TestWidget() {
return DropdownButtonFormField<String>(
value: dropDownValue,
onChanged: (String? newValue) {
// To print the value with localization
print(newValue!.tr);
},
items: provinces.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(value: value, child: Text(value.tr));
}).toList(),
elevation: 4,
decoration: InputDecoration(
prefixIcon: Icon(Icons.flag_circle),
labelText: 'Select',
alignLabelWithHint: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
}
If you need to store the city in database or anywhere with localization then you can use it like [dropDownValue.tr]
Hi I get an error when user focus textfield, app crashes and returns to homepage (see clip here https://www.screencast.com/t/yiJkCBsibcoY)
I've had this error for a while now and cannot seem to fix it, sometimes it happens on other textfields. I cannot replicate the issue only sent from users. Anyone experience this with flutter?
Widget searchBox() {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
border: Border.all(color: Color(0xff0F004E), width: 1.0),
),
child: SimpleAutoCompleteTextField(
key: keyAuto,
controller: textController,
suggestions: suggestions,
textChanged: (text) => searchProduct = text,
textSubmitted: (text) {
loadingBarActive = true;
_sendAnalyticsEvent(text, 'serach_food_action');
searchProduct = text.replaceAll(new RegExp(r'[^\w\s]+'), '');
print('searchProduct RegX $searchProduct');
newSearch = true;
_filterCategories(searchProduct);
_filterRecipes(searchProduct);
// reset search values to intial
usdaItems.clear();
usda!.clear();
perPage = perPageIntial;
present.value = 0;
loadingBarActive = false;
selectApi = <int, Widget>{
0: allProductTab(),
1: allProductTab(),
2: allProductTab(),
3: allProductTab(),
};
setState(() {
_loadUSDAlist = usdaFoodProductList();
_loadOpenList = openFoodProductList();
});
},
style: TextStyle(
fontFamily: 'Nunito', fontSize: 20.0, color: Color(0xff0F004E)),
decoration: InputDecoration(
border: InputBorder.none,
// contentPadding: EdgeInsets.only(top: 14.0),
hintText: 'Search',
hintStyle: TextStyle(
fontFamily: 'Nunito', fontSize: 16.0, color: Color(0xff0F004E)),
prefixIcon: Icon(Icons.search, color: Color(0xff0F004E)),
suffixIcon: IconButton(
icon: Icon(Icons.close, color: Color(0xff0F004E)),
onPressed: () {
textController.clear();
})),
),
);
}
I had exactly the same issue and was literally going crazy trying to find the solution. For me the error originated in my usage of the GetX state management library. For me the issue was solved by replacing this:
Get.to(ReservationDetails(res: Reservation.empty()))
?.then(((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
})));
with:
Navigator.push(context,
MaterialPageRoute(
builder: ((context) =>
ReservationDetails(res: Reservation.empty()))))
.then((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
}));
I suggest you have a look at how you are opening the page you are experiencing this issue.
I am using getx obs with fluter and the below is json response.
[{"id":1,"designation":"Deputy General Manager"},{"id":2,"designation":"Executive Director, Technical Operations","designation_short_code":"ED, TO"},{"id":3,"designation":"Manager","designation_short_code":"M"},{"id":4,"designation":"Sr. Manager","designation_short_code":"Sr. M"}]
In controller I am using--
var listData = List<dynamic>.empty(growable: true).obs;
var designation = 1.obs;
void setDesignation(int value) {
designation.value = value;
}
I am getting the above json response based on api call under listData.
In UI I am using the below code..
Obx(() => DropdownButtonFormField<dynamic>(
decoration: InputDecoration(
hintText: 'Designation',
labelText: 'Select Designation',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
fillColor: Colors.white,
errorStyle: TextStyle(color: Colors.yellow),
),
hint: Text(
'Select Designation',
),
onChanged: (selectedValue) {
designation_controller
.setDesignation(selectedValue);
},
value:
designation_controller.designation.value.toInt(),
items: designation_controller.listData.map((map) {
return DropdownMenuItem(
child: Text(map['designation']),
value: map['id'],
);
}).toList(),
)),
My problem is whenever I select designation it is not updating though my api end point is hitting with 200 response.
Can anyone help me please.
Thanks in advnace.
I have fixed problem. My problem was in the below code
updateData(
controller.userData[0]['id'],
controller.designationEdittingTextController.text
)
I have changed controller.designationEdittingTextController.text to controller.designationEdit.value as below
updateData(
controller.userData[0]['id'],
controller.designationEdit.value
)
Thanks
I am developing e com application, when user click on quantity label want to show dialog box for select how many quantity he want to buy.
I tried to wrap number picker inside Alert dialog. It show alert dialog, but the problem is not updating value when scroll
I can I use Number Picker for that?
Use a drop button combo widget. The DropdownButtonFormField holds a collection of YourClassView type objects held in the list listStatusMenuItems. The _currentStatusComboView variable holds the selected value. It is assigned on the onChange event. I use a restful call to load the listStatusMenuItems.
List<DropdownMenuItem> listStatusMenuItems = <DropdownMenuItem>[];
StatusComboView _currentStatusComboView;
_loadStatusCombo() {
Provider.of<Api>(context, listen: false)
.getYourClassViews()
.then((listView) {
setState(() {
listStatusMenuItems =
listView?.map<DropdownMenuItem<YourClassView>>((item) {
return DropdownMenuItem<StatusComboView>(
value: item, child: Text(item.displayValue));
}).toList();
});
});
#override
void initState() {
super.initState();
_loadStatusCombo();
}
DropdownButtonFormField<YourClassView>(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(5.0),
),
),
filled: true,
hintStyle:
TextStyle(color: Colors.grey[800]),
hintText: "Select a Value",
fillColor: Colors.orange),
items: listStatusMenuItems,
isDense: true,
isExpanded: true,
value: this._currentStatusComboView,
validator: (value) =>
value == null ? 'field required' : null,
onChanged: (StatusComboView value) {
setState(() {
this._currentStatusComboView = value;
});
}),
I am trying to create a kind of forum using text fields. The thing is that when you fill in the blacks and press next and than you go back again, the text field will appear empty as if you have no value in it but its actually saved. I want it so that you can see what you entered inside even if you go forward and than back. I will attach some photos so you can understand better what i mean.
Here is the photo of the text field:
https://gyazo.com/9ceb0ef4f27db1be842cbdfac885fc01
In this photo i fill in the blanks:
https://gyazo.com/6365ab3fcc9d8167a1c9163563fbf3d7
Than i go forward:
https://gyazo.com/8490115e74b57e96cd1f3a9486db5fad
And when i go back again, the text field looks empty but the value is not empty, i want it so that i can still see the value inside:
https://gyazo.com/07eec4c58149641926d7f037bb0f949c
Here i will put the code of the TextFIeld:
Container(
margin: EdgeInsets.only(top: 20),
width: 360,
child:
Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus.context).save();
},
child: TextFormField(
decoration: new InputDecoration(
labelText: "Event Name",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
validator: (val) {
if (val.length == 0) {
return "Event Name cannot be empty";
} else {
return null;
}
},
onSaved: (String value) {
eventname = value;
},
style: new TextStyle(
fontFamily: "Poppins",
))))
add an initial value to your textformfield by loading the saved value