Using Localization inside a list - Flutter - flutter

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]

Related

Flutter Checkbox value storage in Firebase

My setup is simple: i am making a landing page using Flutter web: users input their email add and tick a Checkbox if say they are over 18.
For the life of me I can not find a way to store both email add and the boolean value of the checkbox in the SAME RECORD in Firebase?
the UI and Firebase all setup and working ok, here the code snippets:
`child: TextFormField(
controller: _emailController,
// The validator receives the text that the user has entered.
validator: (val) => !EmailValidator.validate(val!, true)
? 'Please enter a valid email.'
: null,
onSaved: (email2save) => this.email2save = email2save,
decoration: InputDecoration(
icon: Icon(
Icons.email_outlined,
color: Color(0xFF0000CC),
),
hintText: "Please enter your email",
border: InputBorder.none),
),
.......
Column(
children: [
Text('Please tick here'),
MyStatefulWidget(),
Text(' if over 18'),
],
),
.......
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool isChecked = false;
#override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Color(0xFF0000CC);
}
return Colors.black;
}
return Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
}
Hi I don't see any Firebase in the code you've provided above but it is actually pretty easy to add two or even many things at once to Cloud Firestore:
var collection = FirebaseFirestore.instance
.collection(collection_name)
.doc(document_name);
collection
.set({
'email': 'email2save',
'check': 'isChecked'
})
You can do this anywhere in your class and it will work like magic.

How to save DropdownButtonFormField value to Firebase real-time database?

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

How to hide a widget if a DropdownMenuItem is not selected in flutter

I'm trying to hide a widget that follows after dropdownMenu only if no value has been selected.
Here is my dropdown menu
Container(
child: DropdownButtonFormField(
decoration: InputDecoration(
filled: true,
hintStyle: TextStyle(color: Colors.white),
fillColor: Color.fromARGB(0, 0, 0, 0)
),
value: dropDownValue,
onChanged: (String? Value) {
setState(() {
dropDownValue = Value!;
});
},
items: terms
.map((cityTitle) => DropdownMenuItem(
value: cityTitle, child: Text("$cityTitle")))
.toList(),
),
And this is how i've tried , but this doesn't work
dropDownValue == "" ?
Container(
margin: EdgeInsets.all(20),
child: Text(''),
): Container(
margin: EdgeInsets.all(20),
child: Text('testing app'),
)
So, i want if no value has been selected an empty container to be displayed else the text " testing app" should be shown
You need to declare the value outside the build function.
Try to avoid "" or ? in if. Maybe try using something like string.isEmpty.
You widget if is that when dropDownValue is "" then no text should be shown. When dropDownValue != "" then "testing app" should be show.
Make sure to to define a init value of the string outside the build function under the extends State like
String dropDownValue = ""
i got it , all that time i initialized the dropDownValue instead of living it empty.

Cannot update DropdownButtonFormField field value in flutter with getx obs

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

How To Create Number Picker as a alert dialog in flutter?

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