How can I clear dropdown selection? - flutter

I'm using the dropdown_button2 package on the project that I'm currently working on. Everything works fine but I need to clear the selection with a cancel button and I can't reach the selected value.
Here is my code:
final TextEditingController _searchController = TextEditingController();
bool _doctorSelection = false;
DropdownButtonHideUnderline(
child: DropdownButtonFormField2<String>(
items: _doctorList
.map((item) => DropdownMenuItem(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
searchController: _searchController,
searchInnerWidget: TextFormField(
controller: _searchController,
textAlignVertical: TextAlignVertical.center,
decoration: const InputDecoration(
hintText: 'Doktor Adı',
hintStyle: TextStyle(
fontSize: 14,
),
suffixIcon: Icon(Icons.search),
contentPadding: EdgeInsets.only(left: 15),
),
),
searchMatchFn: (a, searchValue) {
return a.value
.toString()
.toLowerCase()
.contains(searchValue.toLowerCase());
},
onChanged: (value) {
setState(() {
_doctorSelection = true;
});
},
onMenuStateChange: (isOpen) {
if (!isOpen) {
_searchController.clear();
}
},
decoration: const InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
border: InputBorder.none,
icon: Padding(
padding: EdgeInsets.only(left: 15.0),
child: Icon(
Icons.person,
),
),
),
buttonPadding: const EdgeInsets.only(
right: 15,
),
buttonHeight: 45,
isExpanded: true,
dropdownMaxHeight: 240,
dropdownWidth: screenWidth,
dropdownDecoration: BoxDecoration(
border: Border.all(
color: Colors.grey.shade400,
),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
),
),
scrollbarAlwaysShow: true,
alignment: Alignment.centerLeft,
hint: const Text(
"Doktor Ara",
style: TextStyle(fontSize: 14, color: Colors.grey),
),
icon: _doctorSelection
? GestureDetector(
onTap: () {
setState(() {
_doctorSelection = false;
});
},
child: const Icon(
Icons.cancel,
color: Colors.red,
),
)
: Icon(
Icons.keyboard_arrow_down,
color: Colors.blueGrey[400],
),
),
)
What I want to achieve is to clear the selection with the cancel button and show the hint text again.
I tried to clear _searchController but nothing happened. My guess is, I should manipulate the value in DropdownMenuItem widget but I don't know how.

Related

flutter UI problem: text feild not scrolling behind stepper

Here when I am scrolling then my text fields which is in grey[200], scroll overe stepper little bit, as you can see in image. so How to fix it?
Here when I am scrolling then my text fields which is in grey[200], scroll overe stepper little bit, as you can see in image. so How to fix it?
This is my stepper code
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../constants/constants.dart';
class BecomeHH extends StatefulWidget {
const BecomeHH({Key? key}) : super(key: key);
#override
_BecomeHHState createState() => _BecomeHHState();
}
class _BecomeHHState extends State<BecomeHH> {
int _activeStepIndex = 0;
TextEditingController nameController = TextEditingController();
TextEditingController cityController = TextEditingController();
TextEditingController countryController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
List<Step> stepList() => [
Step(
isActive: _activeStepIndex >= 0,
state:
_activeStepIndex >= 0 ? StepState.complete : StepState.disabled,
title: const Text('Step One'),
content: ClipRRect(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Name",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
SizedBox(
height: 3.7,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: TextFormField(
controller: nameController,
textAlign: TextAlign.left,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
fillColor: Colors.white,
hintText: 'Enter Your Name',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide.none,
),
filled: false,
contentPadding: EdgeInsets.only(
left: 16,
),
),
),
),
SizedBox(
height: 16,
),
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"City",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
SizedBox(
height: 3.7,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: TextFormField(
controller: cityController,
textAlign: TextAlign.left,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
fillColor: Colors.white,
hintText: 'Enter Your City',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide.none,
),
filled: false,
contentPadding: EdgeInsets.only(
left: 16,
),
),
),
),
SizedBox(
height: 16,
),
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Country",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
SizedBox(
height: 3.7,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: TextFormField(
controller: countryController,
textAlign: TextAlign.left,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
fillColor: Colors.white,
hintText: 'Enter Your Country',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide.none,
),
filled: false,
contentPadding: EdgeInsets.only(
left: 16,
),
),
),
),
SizedBox(
height: 16,
),
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Email",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
SizedBox(
height: 3.7,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: TextFormField(
controller: emailController,
textAlign: TextAlign.left,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
fillColor: Colors.white,
hintText: 'Enter Your Email',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide.none,
),
filled: false,
contentPadding: EdgeInsets.only(
left: 16,
),
),
),
),
SizedBox(
height: 16,
),
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Phone",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
SizedBox(
height: 3.7,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: TextFormField(
controller: phoneController,
textAlign: TextAlign.left,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
fillColor: Colors.white,
hintText: 'Enter Your Phone Number',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide.none,
),
filled: false,
contentPadding: EdgeInsets.only(
left: 16,
),
),
),
),
SizedBox(
height: 16,
),
],
),
),
),
Step(
isActive: _activeStepIndex >= 0,
state:
_activeStepIndex >= 1 ? StepState.complete : StepState.disabled,
title: const Text('Step Two'),
content: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Video",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
],
),
)),
Step(
isActive: _activeStepIndex >= 0,
state:
_activeStepIndex >= 2 ? StepState.complete : StepState.disabled,
title: const Text('Step Three'),
content: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
"Focus Area",
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.grey,
),
),
),
],
)))
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(elevation: 0,
backgroundColor: Colors.white38,
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
onPressed: () {
Navigator.pop(context);
},
),
),
body: SafeArea(
child: Theme(
data: ThemeData(
colorScheme: Theme.of(context).colorScheme.copyWith(primary: selectBlueColor),
),
child: Stepper(
type: StepperType.horizontal,
currentStep: _activeStepIndex,
steps: stepList(),
onStepContinue: () {
if (_activeStepIndex < (stepList().length - 1)) {
setState(() {
_activeStepIndex += 1;
});
} else {
print('Submited');
}
},
onStepCancel: () {
if (_activeStepIndex == 0) {
return;
}
setState(() {
_activeStepIndex -= 1;
});
},
onStepTapped: (int index) {
setState(() {
_activeStepIndex = index;
});
},
controlsBuilder: (BuildContext context, ControlsDetails details) {
final isLastStep = _activeStepIndex == stepList().length - 1;
return Container(
child: Row(
children: [
Expanded(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(const Color(0xFF158998)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.teal, width: 0.0),
),
),
),
onPressed: details.onStepContinue,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: (isLastStep)
? const Text('Submit')
: const Text('Next'),
),
),
),
const SizedBox(
width: 10,
),
if (_activeStepIndex > 0)
Expanded(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(const Color(0xFF158998)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.teal, width: 0.0),
),
),
),
onPressed: details.onStepCancel,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: const Text('Back'),
),
),
),
],
),
);
},
),
),
),
);
}
}
Simply add this line in your Stepper widget.
physics: ScrollPhysics(),

How to write a code for update logged in user data into firebase using flutter

I'm a newbie for flutter and currently learning it by developing a small system for my university project. Below are my user register and profile view which I referenced from YouTube. But I do not know how to write a code for edit and delete the logged in user data (the personal information such as name and address)...
class RegMuser extends StatefulWidget {
const RegMuser({Key? key}) : super(key: key);
#override
_RegMuserState createState() => _RegMuserState();
}
class _RegMuserState extends State<RegMuser> {
bool hidePassword = true;
final formkey = GlobalKey<FormState>();
final nameEC = new TextEditingController();
final emailEC = new TextEditingController();
final nricEC = new TextEditingController();
final passwordEC = new TextEditingController();
final confirmPasswordEC = new TextEditingController();
final _auth = FirebaseAuth.instance;
#override
Widget build(BuildContext context) {
final nameField = TextFormField(
autofocus: false,
controller: nameEC,
keyboardType: TextInputType.name,
validator: (value) {
RegExp regex = new RegExp(r'^.{3,}$');
if (value!.isEmpty) {
return ("Name Cannot Be Empty");
}
if (!regex.hasMatch(value)) {
return ("Enter A Valid Name");
}
return null;
},
onSaved: (value) {
nameEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.person),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: 'Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final emailField = TextFormField(
autofocus: false,
controller: emailEC,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ("Please Enter Your Email");
}
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+[a-z]").hasMatch(value)) {
return ("Please Enter Valid Email");
}
return null;
},
onSaved: (value) {
nameEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.mail),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final nricField = TextFormField(
autofocus: false,
controller: nricEC,
keyboardType: TextInputType.number,
validator: (value) {
RegExp regex = new RegExp(r'[0-9]');
if (value!.isEmpty) {
return ("NRIC Cannot Be Empty");
}
if (!regex.hasMatch(value)) {
return ("Enter A Valid NRIC");
}
if (nricEC.text.length != 12) {
return ("Enter A Valid NRIC");
}
return null;
},
onSaved: (value) {
nricEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.card_membership),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "NRIC",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final passwordField = TextFormField(
autofocus: false,
controller: passwordEC,
obscureText: hidePassword,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ("Password Is Required For Login");
}
if (!regex.hasMatch(value)) {
return ("Please Enter Valid Password");
}
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.vpn_key),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Pasword",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
suffixIcon: InkWell(
onTap: togglePasswordView,
child: Icon(
Icons.visibility,
),
),
),
);
final confirmPasswordField = TextFormField(
autofocus: false,
controller: confirmPasswordEC,
obscureText: hidePassword,
validator: (value) {
if (confirmPasswordEC.text != passwordEC.text) {
return "Password Don't Match";
}
return null;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.vpn_key),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Confirm Pasword",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
suffixIcon: InkWell(
onTap: togglePasswordView,
child: Icon(
Icons.visibility,
),
),
),
);
final signUpButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.blue[400],
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEC.text, passwordEC.text);
},
child: Text(
"Sign Up",
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
);
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: Center(
child: SingleChildScrollView(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Form(
key: formkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
nameField,
SizedBox(height: 20),
emailField,
SizedBox(height: 20),
nricField,
SizedBox(height: 20),
passwordField,
SizedBox(height: 20),
confirmPasswordField,
SizedBox(height: 20),
signUpButton,
SizedBox(height: 10),
],
),
),
),
),
),
),
);
}
void togglePasswordView() {
setState(() {
hidePassword = !hidePassword;
});
}
void signUp(String email, String password) async {
if (formkey.currentState!.validate()) {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => {postDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
}
}
postDetailsToFirestore() async {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? mUser = _auth.currentUser;
Muser muser = Muser();
muser.email = mUser!.email;
muser.uid = mUser.uid;
muser.name = nameEC.text;
muser.nric = nricEC.text;
await firebaseFirestore
.collection("mUsers")
.doc(muser.uid)
.set(muser.toMap());
Fluttertoast.showToast(msg: "Account Created Successfully");
Navigator.pushAndRemoveUntil((context),
MaterialPageRoute(builder: (context) => homePage()), (route) => false);
}
}
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
"Name",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.name}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Email",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.email}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Position",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.post}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Department",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.dept}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Hospital",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.hosp}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Address",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.street} ${loggedInUser.city} ${loggedInUser.postcode} ${loggedInUser.state} ${loggedInUser.country}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
],
),
),
),
// Import the Firebase package
import 'package:firebase_auth/firebase_auth.dart';
// Create an instance of the Firebase authentication
final FirebaseAuth _auth = FirebaseAuth.instance;
// Create a function to update logged in user data
Future<void> updateUserData(String name, String email, String phone) async {
// Get the current logged in user
FirebaseUser user = await _auth.currentUser();
// Create a user update profile
UserUpdateInfo userInfo = UserUpdateInfo();
// Update the user profile with the provided data
userInfo.displayName = name;
userInfo.email = email;
userInfo.phoneNumber = phone;
// Finally update the user profile
await user.updateProfile(userInfo);
}

How to add divider to dropdown list?

I have the following dropdown:
DropdownButtonFormField(
isExpanded: true,
isDense: true,
value: dropdownValue,
icon: SvgPicture.asset(
AppImages.ic_expand_dropdown,
),
iconDisabledColor: AppColors.colorDarkGray,
iconEnabledColor: AppColors.colorDarkGray,
focusNode: widget.focusNode,
validator: widget.validator,
decoration: InputDecoration(
label: widget.widgetLabel,
labelStyle:
widget.labelStyle ?? AppTextStyles.transparentBlueDark16(),
labelText: widget.isLabelRes
? AppLocales.getTextOrNull(widget.label)
: widget.label,
fillColor: Colors.white,
filled: true,
hintText: widget.pickerPlaceholder,
hintStyle: widget.hintStyle ?? AppTextStyles.alto16(),
alignLabelWithHint: true,
errorText: widget.isErrorRes
? AppLocales.getTextOrNull(widget.error)
: widget.error,
contentPadding: const EdgeInsets.symmetric(
horizontal: 0,
vertical: 0,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
width: 1,
color:
widget.enabledBorderColor ?? AppColors.colorInputBorder,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
width: 2,
color: widget.focusedBorderColor ?? AppColors.colorAccent,
),
),
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(
width: 2,
color: AppColors.colorError,
),
),
border: UnderlineInputBorder(
borderSide: BorderSide(
width: 1,
color: widget.borderColor ?? AppColors.colorInputBorder,
),
),
),
style: AppTextStyles.grayDark16(
fontWeight: AppFontWeight.medium,
),
onChanged: (String? newValue) {
dropdownValue = newValue;
widget.onChanged(dropdownValue!);
},
items: widget.pickerList.map<DropdownMenuItem<String>>((value) {
return DropdownMenuItem<String>(
value: value,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
),
child: Text(
value,
style: AppTextStyles.grayDark16(
fontWeight: AppFontWeight.medium,
),
),
),
Visibility(
child: Divider(
color: AppColors.colorEden10,
height: 2.0,
indent: 10.0,
endIndent: 10.0,
),
visible: widget.pickerList.last != value,
),
],
),
);
}).toList(),
),
I need to display the dividers between items. As I didn't find any option to add it as in List, I added the divider by creating a Column that contains Text and Divider which is shown in some cases. But the problem is that when I select the item divider is also displayed in dropdown as a result and I don't see any option to hide it here. Is there any way to add a divider without displaying it after selecting item?
To avoid selected Item Divider, we need to use selectedItemBuilder:. By default, it uses items layout.
You can use on DropdownButtonFormField like
selectedItemBuilder: (context) => widget.pickerList
.map(
(text) => Text(text),
)
.toList(),
You can set your own logic to create the UI.
And the simplified State-snippet is
late List<DropdownMenuItem<String>> menuItems = [];
#override
void initState() {
super.initState();
dropdownValue = widget.pickerList.first;
for (int i = 0; i < widget.pickerList.length; i++) {
//* on 1st index there will be no divider
i == 0
? menuItems.add(
DropdownMenuItem<String>(
child: Text(
widget.pickerList[i],
),
value: widget.pickerList[i],
),
)
: menuItems.add(
DropdownMenuItem<String>(
child: Container(
width: double.maxFinite,
alignment: Alignment.centerLeft,
padding: const EdgeInsets.only(
top: 6, // adjust the way you like
),
decoration: const BoxDecoration(
border: Border(
top: BorderSide(
color: Colors.grey,
width: 2,
),
),
),
child: Text(
widget.pickerList[i],
),
),
value: widget.pickerList[i],
),
);
}
}
#override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
isExpanded: true,
isDense: true,
value: dropdownValue,
onChanged: (String? newValue) {
// dropdownValue = newValue;
// widget.onChanged(dropdownValue!);
},
items: menuItems,
selectedItemBuilder: (context) => widget.pickerList
.map(
(text) => Text(text),
)
.toList(),
);
}

Flutter, how do i make my icon same size as my DropdownButtonFormField?

I know this question is easy for you, especially for veterans, because I am new so I am still confusedHow do i make my Icon same size as my DropdownButtonFormField?
Container(
width: (globals.screenWidth * 0.85),
height: (globals.screenHeight * 0.07),
padding: EdgeInsets.only(top: 0, left: 10),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.brown),
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
child: DropdownButtonFormField(
iconSize: 20,
icon: Container(
color: Colors.black54,
child: Icon(
Icons.keyboard_arrow_down,
color: Colors.white,
),
),
style: TextStyle(
fontSize: globals.fontsize_19,
color: Colors.black,
fontWeight: FontWeight.bold,
),
value: _selectedLocation,
onChanged: (newValue) {
setState(() {
_selectedLocation = newValue;
});
},
items: _locations.map((location) {
return DropdownMenuItem(
child: new Text(location),
value: location,
);
}).toList(),
)
),
I tried this iconSize: 50, but this is the result
this is the result
this is what i want
try to add
decoration: InputDecoration(
contentPadding: EdgeInsets.zero
),
to your DropdownButtonFormField and just add an Expanded widget as parent of your Icon widget.

updating the text in the controller not working after converting the class from stateless to stateful

the code works fine when it's statelesswidget but after converting it to statefulwidget the textformfiled
stopped showing the text value from firestore.
when entering data the filed works just fine and the value stored in the firebase but when editing the the data the filed not showing the value to be edited and when entering the data in the filed new record is being stored in the firebase
class PostView extends StatefulWidget {
PostView({Key key, this.edittingPost}) : super(key: key);
final Post edittingPost;
#override
State<StatefulWidget> createState() {
return CreatePostView();
}
}
class CreatePostView extends State<PostView>{
final airlineController = TextEditingController();
final paxController = TextEditingController();
final infantController = TextEditingController();
final transitController = TextEditingController();
final dateController = TextEditingController();
Post edittingPost;
#override
Widget build(BuildContext context) {
return ViewModelBuilder<CreatePostViewModel>.reactive(
viewModelBuilder: () => CreatePostViewModel(),
onModelReady: (model) {
// update the text in the controller
airlineController.text = edittingPost?.airline ?? '';
paxController.text = edittingPost?.pax ?? '';
infantController.text = edittingPost?.infant ?? '';
transitController.text = edittingPost?.transit ?? '';
dateController.text = edittingPost?.date ?? '';
model.setEdittingPost(edittingPost);
},
builder: (context, model, child) => Scaffold(
floatingActionButton: FloatingActionButton(
child: !model.busy
? Icon(Icons.add)
: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.white),
),
onPressed: () {
if (!model.busy) {
model.addPost(date: dateController.text, airline: airlineController.text, pax: paxController.text,
infant: infantController.text, transit: transitController.text);
}
},
backgroundColor:
!model.busy ? Theme.of(context).primaryColor : Colors.grey[600],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
verticalSpace(40),
Text(
'Create Post',
style: TextStyle(fontSize: 26),
),
verticalSpaceMedium,
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 55.0,
child: TextFormField(
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.calendar_today,
color: Colors.white,
),
hintText: 'Date of Flight',
hintStyle: kHintTextStyle),
controller: dateController,
onTap: () async{
DateTime date = DateTime(1900);
FocusScope.of(context).requestFocus(FocusNode());
date = await showDatePicker(
context: context,
initialDate:DateTime.now(),
firstDate:DateTime(1900),
lastDate: DateTime(2100));
dateController.text = date.toIso8601String();},),
),
verticalSpaceMedium,
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 55.0,
child: TextFormField(
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.airplanemode_active,
color: Colors.white,
),
hintText: 'Airline',
hintStyle: kHintTextStyle,
),
controller: airlineController,
)),
verticalSpaceMedium,
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 55.0,
child: TextFormField(
keyboardType: TextInputType.number,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.airline_seat_recline_extra,
color: Colors.white,
),
hintText: 'Pax',
hintStyle: kHintTextStyle,
),
controller: paxController,
)),
verticalSpaceMedium,
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 55.0,
child: TextFormField(
keyboardType: TextInputType.number,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.child_friendly,
color: Colors.white,
),
hintText: 'Infant',
hintStyle: kHintTextStyle,
),
controller: infantController,
)),
verticalSpaceMedium,
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 55.0,
child: TextFormField(
keyboardType: TextInputType.number,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.transit_enterexit,
color: Colors.white,
),
hintText: 'Transit',
hintStyle: kHintTextStyle,
),
controller: transitController,
)),
],
),
),
)),
);
}
}
If you want see change text from textfromField - you have to use setState() where you will asssigned new value to variable.