Related
I have implemented a login screen using flutter. the screen is fully functional and working properly with validations. I want this screen to be scrollable and responsive to other devices. how can I do that? below I have added my full login screen code. appreciate your help on this.
how to scroll the screen
how to implement responsive screen
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color.fromARGB(255, 3, 86, 124), Color(0xff141a3a)],
begin: Alignment.topRight,
end: Alignment.bottomLeft,
)),
child: Scaffold(
backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
children: [
Expanded(
flex: 2,
child: Column(
children: [
// Spacer(flex: 1),
Image(
image: const AssetImage(
'assets/images/LogoVector.png',
),
height: Size.width / 2.9,
width: Size.width / 2.9,
),
SizedBox(height: 5),
Text(
"LOGIN",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 30,
color: textWhite,
fontFamily: "Roboto"),
),
],
),
),
// const Spacer(flex: 1),
const Expanded(flex: 3, child: Center(child: LoginForm())),
// Spacer(
// flex: 1,
// ),
],
),
),
),
),
);
}
}
class LoginForm extends StatefulWidget {
const LoginForm({Key? key}) : super(key: key);
#override
_LoginFormState createState() => _LoginFormState();
}
Map<String, String> loginUserData = {
'email': '',
'password': '',
'id': '',
'userName': '',
'token': '',
'userStatus': '',
};
class _LoginFormState extends State<LoginForm> {
TextEditingController emailEditingController = new TextEditingController();
TextEditingController passwordEditingController = new TextEditingController();
final _formKey = GlobalKey<FormState>();
String email = "";
String password = "";
String username = "";
bool isLoading = false;
bool typing = true;
bool _isObscure = true;
// bool newValue = true;
bool checkedValue = true;
//String fcmToken = '';
Future LoginData() async {
setState(() {
isLoading = true;
typing = false;
});
try {
var response = await Dio().post(BASE_API + 'user/login',
data: {"username": email, "password": password});
if (response.data["status"] == "LoginSuccess") {
setState(() {
isLoading = false;
});
Get.snackbar(
"success",
"logged in successfully",
backgroundColor: buttontext.withOpacity(0.5),
colorText: textWhite,
borderWidth: 1,
borderColor: Colors.grey,
);
Get.to(BottomNavigation());
} else {
setState(() {
isLoading = false;
typing = true;
});
Get.snackbar(
"error",
"No User Found",
backgroundColor: buttontext.withOpacity(0.5),
colorText: textWhite,
borderWidth: 1,
borderColor: Colors.grey,
);
}
print("res: $response");
setState(() {
isLoading = false;
typing = true;
});
} catch (e) {
setState(() {
isLoading = false;
typing = true;
});
Get.snackbar("Error", "Something went wrong.Please contact admin",
backgroundColor: buttontext.withOpacity(0.5),
borderWidth: 1,
borderColor: Colors.grey,
colorText: Colors.white,
icon: Icon(
Icons.error_outline_outlined,
color: Colors.red,
size: 30,
));
print(e);
}
}
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Column(
children: [
TextFormField(
controller: emailEditingController,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(
color: textWhite,
),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 30, 10, 0),
hintText: "Email/ Username",
hintStyle: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
style: TextStyle(color: textWhite),
validator: (String? UserName) {
if (UserName != null && UserName.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
// print(email);
},
onSaved: (value) {
loginUserData['email'] = value!;
},
),
SizedBox(
height: 10,
),
TextFormField(
controller: passwordEditingController,
obscureText: _isObscure,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 10, 10, 0),
suffixIcon: IconButton(
icon: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off),
color: textWhite,
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
}),
hintText: "Password",
hintStyle: TextStyle(
color: textWhite,
fontFamily: "Roboto",
fontSize: 14,
)),
style: TextStyle(color: textWhite),
validator: (String? Password) {
if (Password != null && Password.isEmpty) {
return "Password can't be empty";
}
return null;
},
onChanged: (String? text) {
password = text!;
print(password);
},
onSaved: (value) {
loginUserData['password'] = value!;
},
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: CheckboxListTile(
title: const Text(
"Remember Me",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
activeColor: buttontext,
// tileColor: buttontext,
value: checkedValue,
onChanged: (newValue) {
FocusManager.instance.primaryFocus?.unfocus();
setState(() {
if (isLoading != true) {
checkedValue = newValue!;
print(newValue);
}
});
},
contentPadding: EdgeInsets.only(left: 0, top: 0),
controlAffinity:
ListTileControlAffinity.leading, // <-- leading Checkbox
),
),
TextButton(
child: Text(
"Forget Password",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
onPressed: () {
Get.to(() => Forget_Screen());
},
)
],
),
SizedBox(height: 40),
isLoading
? SpinKitDualRing(
color: textWhite,
size: 40,
)
: GestureDetector(
child: MainButton("Login"),
onTap: () async {
FocusManager.instance.primaryFocus?.unfocus();
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
await LoginData();
// Get.to(BottomNavigation());
}
},
),
SizedBox(height: 15),
Container(
width: 275.0,
height: 40.0,
child: OutlinedButton(
onPressed: () {
Get.to(() => const Signup_Screen());
},
child: const Text(
'Signup',
style: TextStyle(
fontSize: 15, fontFamily: "Roboto", color: textWhite
//fontWeight: FontWeight.w500,
// color: Colors.black,
),
),
style: OutlinedButton.styleFrom(
side: const BorderSide(
width: 1.0,
color: textWhite,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
// side: BorderSide(width: 2, color: Colors.green),
),
),
),
)
],
),
);
}
}
How to scroll the screen? Use SingleChildScrollView wrap your Column, remember to ristrict the content size to avoid error.
How to implement responsive screen? Simplest is use LayoutBuilder widget that provide constrains as a props. This constrains can provide maxHeight, maxWidth,... You can then rely on it to determine how you build your application (responsive).
Example:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: LayoutBuilder(
builder: (context, constrains){
final maxw = constrains.maxWidth;
String text = '';
if(maxw < 420) {text = 'Smaller than 420';}
else {text = 'Bigger than 420';}
return Center(child: Text('Width is: $maxw, $text'));
}
),
);
}
I am design a screen in which I need to opening a drop down list when user click on textfield till now I am using CupertinoActionSheetAction sheet which is correctly working now I need to replace it with DropdownButton but when I am doing it is not displaying on screen I don't know why.
Here is my code focus on line number 136 (function for CupertinoActionSheetAction is working code) and line 138 where (function for drop not working code) according to me may be it due to build context but I m not sure how to use 'build context' in this context can any one help me out to fix that.
Thanks in advance, And any suggestion for making my code more reusable will be helpful as well :)
import 'dart:ffi';
import 'package:fleet_management/AppContants/Contants.dart';
import 'package:fleet_management/Controllers/NewFuelExpenseController.dart';
import 'package:fleet_management/Models/NewFuelExpenseModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AddFuelView extends StatefulWidget {
const AddFuelView({Key? key}) : super(key: key);
#override
_AddFuelView createState() {
return _AddFuelView();
}
}
// MyTripHistoryView
class _AddFuelView extends State<AddFuelView> {
NewFuelExpenseModel fuelExpense =
NewFuelExpenseController().getNewFuelExpense();
DateTime _selectedDate = DateTime.now();
String dropdownvalue = 'Item 1';
// List of items in our dropdown menu
var items = [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
];
TextStyle _titleTextStyle = const TextStyle();
TextStyle _valueTextStyle = const TextStyle();
final GlobalKey newFuelExpenseFormField = GlobalKey<FormState>();
final TextEditingController _dateEditingController = TextEditingController();
final TextEditingController _priceTextEditingController =
TextEditingController();
final TextEditingController _gallonsTextEditingController =
TextEditingController();
final TextEditingController _totalTextEditingController =
TextEditingController();
final TextEditingController _odometerTextEditingController =
TextEditingController();
final TextEditingController _fuelTypeTextEditingController =
TextEditingController();
final TextEditingController _vendorTextEditingController =
TextEditingController();
#override
void initState() {
super.initState();
_titleTextStyle =
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600);
_valueTextStyle = const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black38);
_dateEditingController.text =
"${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
}
#override
Widget build(BuildContext context) {
var scaffold = Scaffold(
appBar: AppBar(
title: Text(StringsConstants.newFuelExpense),
backgroundColor: AppColorsConstants.primaryColor,
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () {
print("SAVE Button Clicked");
},
child: Text("Save", style: _titleTextStyle),
),
],
),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: newFuelExpenseFormField,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
showDateRow(context),
addTextFieldInput(
StringsConstants.priceGallon,
"\u{20B9}0.00",
false,
_priceTextEditingController,
TextInputType.datetime,
null,
null),
addTextFieldInput(
StringsConstants.gallons,
"",
false,
_gallonsTextEditingController,
TextInputType.number,
null,
null),
addTextFieldInput(
StringsConstants.total,
"\u{20B9}0.00",
false,
_totalTextEditingController,
TextInputType.number,
null,
null),
addTextFieldInput(
StringsConstants.odometer,
"",
false,
_odometerTextEditingController,
TextInputType.number,
null,
null),
// show action sheet
addTextFieldInput(
StringsConstants.fuelType,
"",
true,
_fuelTypeTextEditingController,
TextInputType.none,
null, () {
// Working. - >>>> HERE <<<<<
showActionSheet(context);
// Not Working >>>> HERE <<<<< Uncomment following function before
// showDropDown();
}),
addTextFieldInput(
StringsConstants.vendor,
"",
false,
_vendorTextEditingController,
TextInputType.text,
null,
null),
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
print("Submit button pressed!");
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24),
primary: AppColorsConstants.primaryColor,
textStyle:
const TextStyle(fontWeight: FontWeight.bold),
),
child: Text(StringsConstants.submit)),
ElevatedButton(
onPressed: () {
print("Cancel button pressed!");
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24),
primary: AppColorsConstants.primaryColor,
textStyle:
const TextStyle(fontWeight: FontWeight.bold),
),
child: Text(StringsConstants.cancel))
],
)
],
),
),
),
),
),
);
return scaffold;
}
void showDropDown() {
DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
);
}
Future<dynamic> showActionSheet(BuildContext context) {
return showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => CupertinoActionSheet(
title: const Text('Choose Options'),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Oil'),
onPressed: () {
_fuelTypeTextEditingController.text = "Oil";
Navigator.pop(context, 'Oil');
},
),
CupertinoActionSheetAction(
child: const Text('Petrol'),
onPressed: () {
_fuelTypeTextEditingController.text = "Petrol";
Navigator.pop(context, 'Petrol');
},
),
CupertinoActionSheetAction(
child: const Text('diesel'),
onPressed: () {
_fuelTypeTextEditingController.text = "diesel";
Navigator.pop(context, 'diesel');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)),
);
}
Container addTextFieldInput(
String title,
String initialValue,
bool isEditable,
TextEditingController textfieldController,
TextInputType keyboardType,
FormFieldValidator<String>? validator,
GestureTapCallback? tabCallback,
) {
return Container(
padding: const EdgeInsets.fromLTRB(0, 16, 0, 8),
child: SizedBox(
child: TextFormField(
onTap: tabCallback,
keyboardType: keyboardType,
cursorHeight: 16,
cursorWidth: 1.4,
readOnly: isEditable,
controller: textfieldController,
validator: validator,
decoration: InputDecoration(
isDense: true,
floatingLabelStyle:
TextStyle(color: AppColorsConstants.primaryColor),
labelText: title,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: AppColorsConstants.primaryColor, width: 1.5),
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black38, width: 1.5),
),
border: const OutlineInputBorder()),
style: const TextStyle(fontSize: 18),
cursorColor: Colors.black38,
showCursor: true,
autofocus: true,
),
),
);
}
Container showDateRow(BuildContext context) {
return Container(
child: TextFormField(
onTap: () => {_selectDate(context)},
cursorHeight: 16,
cursorWidth: 1.4,
readOnly: true,
enableInteractiveSelection: false,
controller: _dateEditingController,
decoration: InputDecoration(
isDense: true,
labelStyle: const TextStyle(color: Colors.orangeAccent),
labelText: StringsConstants.date,
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.orangeAccent, width: 1.5),
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black38, width: 1.5),
),
border: const OutlineInputBorder()),
style: const TextStyle(fontSize: 18),
cursorColor: Colors.black38,
showCursor: true,
autofocus: true,
),
);
}
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(1990),
lastDate: DateTime.now());
if (picked != null && picked != _selectedDate) {
setState(() {
_selectedDate = picked;
this._dateEditingController.text =
"${_selectedDate.day}-${_selectedDate.month}-${_selectedDate.year}";
});
}
}
}
For DropDown in flutter you need
an initail value,
a list to be shown just
String selectedvalue='myvalue';
/// be sure you add the variable value in the 0 index of you list other wise it will thrown error or exception..
List<String> myList=[
'myvalue',/// the value is same as variable value
'othe value', ....
];
DropDownButton(
onChanged: (resultValue){
/// you can get selected value from here
},
items: myList.map((e){
retrun DropdownMenuItem(
value: e,
child: Text(e));
}).toList(),
value: selectedvalue,
),
You can use DropdownButtonFormField in place of TextFormField and can make some style related changes per your requirement.
class MyWidget extends StatelessWidget {
String selectedValue = "USA";
List<DropdownMenuItem<String>> get dropdownItems{
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(child: Text("USA"),value: "USA"),
DropdownMenuItem(child: Text("Canada"),value: "Canada"),
DropdownMenuItem(child: Text("Brazil"),value: "Brazil"),
DropdownMenuItem(child: Text("England"),value: "England"),
];
return menuItems;
}
#override
Widget build(BuildContext context) {
return DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(20),
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(20),
),
filled: true,
fillColor: Colors.blueAccent,
),
dropdownColor: Colors.blueAccent,
value: selectedValue,
onChanged: (String? newValue) {
selectedValue = newValue!;
},
items: dropdownItems);
}
}
I am using multi_select_flutter to show multi chips in my flutter project. However, am trying to add more items to the chip with data loaded from my api while the user is searching but it doesn't update the state of the multi chip widget. Here is my full code.
Even when I hot reload, it does not update itself. The only way I can manually enforce a refresh update is to re-ad the widget and reload consecutively. Any information as to why this strange behavior happens?
class MultiChoiceComponent extends StatefulWidget {
const MultiChoiceComponent({Key key}) : super(key: key);
#override
_MultiChoiceComponentState createState() => _MultiChoiceComponentState();
}
class _MultiChoiceComponentState extends State<MultiChoiceComponent> {
ApiMethods apiMethods;
TextEditingController searchController = TextEditingController();
List<MultiSelectItem<dynamic>> labels = [];
final TextEditingController textEditingController = TextEditingController();
#override
void initState() {
// TODO: implement initState
super.initState();
apiMethods = new ApiMethods(context: context);
}
#override
Widget build(BuildContext context) {
return ListView(
shrinkWrap: true,
children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Search and select as many symptoms been experienced, it helps with a more accurate diagnosis',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 14,
height: 1.8,
fontWeight: FontWeight.w400,
fontFamily: 'Euclid',
color: AppColors.grey1,
),
),
),
SizedBox(
height: 20,
),
Container(
padding: EdgeInsets.symmetric(horizontal: 16,),
// height: maxLines * 50.0,
child: TextField(
controller: textEditingController,
cursorColor: Colors.black26,
onChanged: (val){
if(val!=""){
searchSymptoms(val);
}
},
decoration: InputDecoration(
filled: true,
hintStyle: TextStyle(
fontSize: 14,
height: 1.6,
fontWeight: FontWeight.w400,
fontFamily: 'Euclid',
color: AppColors.grey1,
),
hintText: "Search for a symptom/illness",
fillColor: Colors.white,
contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12.0),
borderSide: BorderSide(color: AppColors.textColor.withOpacity(0.5)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12.0),
borderSide: BorderSide(color: AppColors.textColor.withOpacity(0.5)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12.0),
borderSide: BorderSide(color: AppColors.textColor.withOpacity(0.5)),
)),
),
),
MultiSelectChipField(
scroll: false,
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent, width: 1.8),
),
showHeader: false,
selectedTextStyle: TextStyle(
fontSize: 12.5,
height: 1.8,
fontWeight: FontWeight.w400,
fontFamily: 'Euclid',
color: Colors.white,
),
chipShape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(12),
),
),
selectedChipColor: AppColors.customGreen,
chipColor: Colors.white,
textStyle: TextStyle(
fontSize: 12.5,
height: 1.8,
fontWeight: FontWeight.w400,
fontFamily: 'Euclid',
color: AppColors.textColor,
),
items: labels,
onTap: (value) {
///add symptoms to list
print(value);
selectedSymptoms = value as List<Conditions>;
},
),
],
);
}
Future<void> searchSymptoms(String searchQuery) async {
List<dynamic> _data = await apiMethods.searchConditions(symptomCheckerAge, searchQuery);
conditions = Conditions.fromJsonList(_data);
labels = conditions.map((e) => MultiSelectItem(e, e.label)).toList();
setState(() {});
}
}
I tried this given Chip Widget with custom data and it is working properly.. Meaning the items that I am adding on pressed are being added to the new list. Take a look and try out the few changes and see if that works for you
class _MyHomePageState extends State<MyHomePage> {
static List<Animal> _animals = [
Animal(id: 1, name: "Lion"),
Animal(id: 2, name: "Flamingo"),
Animal(id: 3, name: "Hippo"),
Animal(id: 4, name: "Horse"),
Animal(id: 5, name: "Tiger"),
Animal(id: 6, name: "Penguin"),
Animal(id: 7, name: "Spider"),
Animal(id: 8, name: "Snake"),
Animal(id: 9, name: "Bear"),
Animal(id: 10, name: "Beaver"),
Animal(id: 11, name: "Cat"),
Animal(id: 12, name: "Fish"),
Animal(id: 13, name: "Rabbit"),
];
dynamic _items = _animals
.map((animal) => MultiSelectItem<Animal>(animal, animal.name))
.toList();
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
appBar: new AppBar(
title: new Text('Hello'),
),
body: ListView(
scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(),
children: [
Container(
child: MultiSelectChipField(
scroll: false,
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent, width: 1.8),
),
showHeader: false,
selectedTextStyle: TextStyle(
fontSize: 12.5,
height: 1.8,
fontWeight: FontWeight.w400,
color: Colors.blue,
),
chipShape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(12),
),
),
selectedChipColor: Colors.green,
chipColor: Colors.yellow,
textStyle: TextStyle(
fontSize: 12.5,
height: 1.8,
fontWeight: FontWeight.w400,
color: Colors.black,
),
items: _items,
onTap: (value) {
///add symptoms to list
print(value);
},
),
),
ElevatedButton(
onPressed: () {
_items.add(MultiSelectItem<Animal>(
Animal(id: 27, name: 'name'), 'new'));
setState(() {});
},
child: Text('Add'))
],
),
);
}
}
class Animal {
final int id;
final String name;
Animal({
required this.id,
required this.name,
});
}
Try this
Future<void> searchSymptoms(String searchQuery) async {
List<dynamic> _data = await apiMethods.searchConditions(symptomCheckerAge, searchQuery);
conditions = Conditions.fromJsonList(_data);
labels = conditions.map((e) => MultiSelectItem(e, e.label)).toList();
setState(() {});
}
I was also struggling with hot reload of the MultiSelectChipField and the solution was to update the globalkey during reload.
Pseudo code:
late var _multiSelectKey;
late List<MultiSelectItem<SomeClass?>>? _items;
#override
void initState() {
_items = null;
}
void reloadChip()
{
_multiSelectKey = GlobalKey<FormFieldState>();
_items = getItemsFromSomeWhere();
}
In scaffold the chip has these params
MultiSelectChipField<SomeClass?>(
initialValue: getSelected(),
key: _multiSelectKey,
title: const Text("Title"),
items: _items!,
onTap: (items) async { },
},
),
When function reloadChip() is called and a setState(() {}); is triggered the MultiSelectChipField will update.
im new in flutter and I create a drop down button fields in flutter for the record form. My question is when I click save in the record, how can I make the dropdown is clear (back to the first or no value) for now when I click save, it did not reset the drop down value (still have a value from previous record) And also when I click the clear button, how can I make the drop down is clear? Thanks
class RecordExpense extends StatefulWidget {
#override
_RecordExpenseState createState() => _RecordExpenseState();
}
class _RecordExpenseState extends State<RecordExpense> {
//DatabaseReference _ref;
final date = TextEditingController();
final currency = TextEditingController();
final category = TextEditingController();
final amount = TextEditingController();
final description = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final databaseReference = FirebaseFirestore.instance;
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _email, _password;
Future<String> getCurrentUID() async {
Future.value(FirebaseAuth.instance.currentUser);
//return uid;
}
#override
String selectCurrency;
String selectExpense;
final expenseSelected = TextEditingController();
final currencySelected = TextEditingController();
DateTime _selectedDate;
void initState(){
//_ref = FirebaseDatabase.instance.reference().child('Transaction');
}
Widget build(BuildContext context) {
//FirebaseFirestore firestore = FirebaseFirestore.instance;
//CollectionReference collect= firestore.collection("TransactionExpense");
final FirebaseAuth _auth = FirebaseAuth.instance;
final User user =_auth.currentUser;
final uid = user.uid;
String dates;
String amounts;
//String selectExpenses;
String descriptions;
return new Form(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Container(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Please fill up the text fields';
},
cursorColor: Colors.grey,
controller: date,
onTap: () {
_selectDate(context);
},
decoration: InputDecoration(
labelText: getTranslated((context), "date_text"),
labelStyle: TextStyle(
fontSize: 18.0, color: Colors.black),
hintText: getTranslated((context), "date_hint"),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
),
),
SizedBox(height: 20),
Row(
children: <Widget> [
new Expanded(child: new DropdownButtonFormField<String>(
value: selectCurrency,
hint: Text(getTranslated((context), "currency_hint"),),
//controller: currencySelected,
//labelText: getTranslated((context), "currency_hint"),
//enabled: true,
//itemsVisibleInDropdown: 4,
//items: currencycategories,
onChanged: (salutation) =>
setState(() => selectCurrency = salutation),
validator: (value) => value == null ? 'Please fill up the drop down' : null,
items:
['IDR.', 'MYR', 'USD', 'CNY'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
//flex: 2,
),
//value: selectCurrency,
//required: false,
),
new SizedBox(
width: 10.0,
),
new Expanded(child:
TextFormField(
validator: (input) {
if (input.isEmpty) return 'Please fill up the text fields';
},
cursorColor: Colors.grey,
controller: amount,
decoration: InputDecoration(
labelText: getTranslated((context), "amount_text"),
labelStyle: TextStyle(
fontSize: 18.0, color: Colors.black),
hintText: getTranslated((context), "amount_text"),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
keyboardType: TextInputType.number,
),)
],
),
Container(
padding: EdgeInsets.only(top: 20.0),
child: DropdownButtonFormField <String>(
value: selectExpense,
hint: Text(getTranslated((context), "category_text"),),
//controller: currencySelected,
//labelText: getTranslated((context), "currency_hint"),
//enabled: true,
//itemsVisibleInDropdown: 4,
//items: currencycategories,
onChanged: (salutation) =>
setState(() => selectExpense = salutation),
validator: (value) => value == null ? 'Please fill up the drop down' : null,
items:
['Food.', 'Social Life', 'Transportation', 'Beauty', 'Household', 'Education', 'Health', 'Gift', 'Other'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
//flex: 2,
),
),
SizedBox(height: 20),
Container(
//padding: EdgeInsets.all(20),
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Please fill up the text fields';
},
cursorColor: Colors.grey,
controller: description,
maxLines: 2,
decoration: InputDecoration(
labelText: getTranslated((context), "description_text"),
labelStyle: TextStyle(
fontSize: 18.0, color: Colors.black),
hintText: getTranslated((context), "description_expense"),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
),
),
Container(
padding: EdgeInsets.only(
top: 25.0, left: 20.0, right: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: ElevatedButton(
onPressed: () async {
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
await FirebaseFirestore.instance.collection('users').doc(userID).collection('TransactionExpense').add({
'date': date.text,
'currency': selectCurrency,
'amount': amount.text,
'category': selectExpense,
'description': description.text,
});
date.text = "";
amount.text = "";
description.text = "";
//selectCurrency = "";
//selectExpense = "";
/*
UserCredential _user =
await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password);
String _uid = _user.user.uid;
*/
//await FirebaseFirestore.instance.collection('TransactionExpense').doc(_uid).set({
/*
final FirebaseAuth _auth = FirebaseAuth
.instance;
final User user = _auth.currentUser;
final uid = user.uid;
await DatabaseService().updateData(
uid, date.text, amount.text,
selectExpense, description.text);
Navigator.pop(context);
*/
},
child: Text(
getTranslated((context), "save_button").toUpperCase(), style: TextStyle(
fontSize: 14,
)),
style: ButtonStyle(
padding: MaterialStateProperty.all<
EdgeInsets>(EdgeInsets.all(15)),
foregroundColor: MaterialStateProperty
.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty
.all<Color>(Colors.pink),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0),
side: BorderSide(color: secondary)
),
),
),
),
),
SizedBox(width: 20, height: 10),
Expanded(
child: ElevatedButton(
onPressed: () {
clearButton();
},
child: Text(
getTranslated((context), "clear_button").toUpperCase(), style: TextStyle(
fontSize: 14
)),
style: ButtonStyle(
padding: MaterialStateProperty.all<
EdgeInsets>(EdgeInsets.all(15)),
foregroundColor: MaterialStateProperty
.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty
.all<Color>(Colors.pink),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0),
side: BorderSide(color: secondary)
),
),
),
),
)
],
)
),
],
),
),
),
)
),
);
}
void clearButton(){
date.clear();
amount.clear();
category.clear();
description.clear();
//selectCurrency.clear();
}
_selectDate(BuildContext context) async {
DateTime newSelectedDate = await showDatePicker(
context: context,
initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2040),
builder: (BuildContext context, Widget child) {
return Theme(
data: ThemeData.dark().copyWith(
colorScheme: ColorScheme.dark(
primary: secondary,
onPrimary: Colors.black,
surface: primary,
onSurface: Colors.white,
),
dialogBackgroundColor: Colors.black,
),
child: child,
);
});
if (newSelectedDate != null) {
_selectedDate = newSelectedDate;
date
..text = DateFormat.yMMMd().format(_selectedDate)
..selection = TextSelection.fromPosition(TextPosition(
offset: date.text.length,
affinity: TextAffinity.upstream));
}
}
}
class AlwaysDisabledFocusNode extends FocusNode {
#override
bool get hasFocus => false;
}
When the user taps on the save button the onPressed function is executed, inside that function use setstate to set selectCurrency = null; & selectExpense = null;. This will make the dropdownbutton show the hint instead of old record
[]1] here is my code for ..
i have two textfiled for selecting birth date and month....! and user is existing then value will shown automatically on textfiled ! and user can add new selected value from dropdown selection....! in my case i can select items from dropdown but cant show selected items/value on tetxfild it is removing and textfiled showing blank ! plz help me on this......
String _Dob;
String _Anniversary;
Future<UserUpdate> _futureDateeupdate;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
var month = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUEST", "SEPTEMBER", "OCTOBER",
"NOVEMBER", "DECEMBER"];
var date = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31];
#override
void initState() {
super.initState();
_futureDateeupdate = DateUpadte();
}
void nextField({String value, FocusNode focusNode}) {
if (value.isNotEmpty) {
focusNode.requestFocus();
}
}
FocusNode Anniversary;
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
resizeToAvoidBottomInset: false,
body: (_isLoading)
? Center(child: CircularProgressIndicator())
: FutureBuilder<UserUpdate>(
future: _futureDateeupdate,
// ignore: missing_return
builder: (context, snapshot) {
if (snapshot.hasData) {
TextEditingController _textEditingControllerDOBb = TextEditingController(
text: snapshot.data.birthDate);
TextEditingController _textEditingControllerDate = TextEditingController(
text: snapshot.data.birthMonth);
TextEditingController _textEditingControllerAnniversaryy = TextEditingController(
text: snapshot.data.anniversaryDate);
return Form(
key: _formKey,
child: Stack(
children: <Widget>[
Positioned(
top: 330,
left: 30,
right: 30,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SizedBox(
height: 70,
width: MediaQuery
.of(context)
.size
.width / 2.6,
child: TextFormField(
textInputAction: TextInputAction.next,
onTap: () {
FocusScope.of(context).requestFocus(
new FocusNode());
},
onFieldSubmitted: (value) {
nextField(
value: value, focusNode: Anniversary);
},
keyboardType: TextInputType.datetime,
controller: _textEditingControllerDOBb,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0),
borderSide: BorderSide(
color: const Color(0x3df58634)
)
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0)
),
labelText: 'Date Of Birth',
labelStyle: GoogleFonts.nunito(
color: const Color(0xfff58634)),
hintText: "Date Of Birth",
hintStyle: GoogleFonts.nunito(
color: const Color(0xfff58634)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0),
borderSide: BorderSide(
color: const Color(0x3df58634),
)
),
suffixIcon: PopupMenuButton<String>(
icon: const Icon(Icons.arrow_drop_down),
onSelected: (String value) {
_textEditingControllerDOBb.text = value;
},
itemBuilder: (BuildContext context) {
return month
.map<PopupMenuItem<String>>((
String value) {
return new PopupMenuItem(
child: new Text(value),
value: value);
}).toList();
},
),
),
validator: (String value) {
if (value.isEmpty) {
return 'DOB is Missing';
}
return null;
},
onSaved: (String value) {
_Dob = value;
},
),
),
SizedBox(
height: 70,
width: MediaQuery
.of(context)
.size
.width / 2.6,
child: TextFormField(
onTap: () {
FocusScope.of(context).requestFocus(
new FocusNode());
},
onFieldSubmitted: (value) {
nextField(
value: value, focusNode: Anniversary);
},
controller: _textEditingControllerDate,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0),
borderSide: BorderSide(
color: const Color(0x3df58634)
)
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0)
),
labelText: 'Date Of Birth',
labelStyle: GoogleFonts.nunito(
color: const Color(0xfff58634)),
hintText: "Date Of Birth",
hintStyle: GoogleFonts.nunito(
color: const Color(0xfff58634)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
5.0),
borderSide: BorderSide(
color: const Color(0x3df58634),
)
),
suffixIcon: PopupMenuButton<int>(
icon: const Icon(Icons.arrow_drop_down),
onSelected: (int value) {
_textEditingControllerDate.text =
"$value";
},
itemBuilder: (BuildContext context) {
return date
.map<PopupMenuItem<int>>((
int value) {
return new PopupMenuItem(
child: new Text("$value"),
value: value);
}).toList();
},
),
),
validator: (String value) {
if (value.isEmpty) {
return 'DOB is Missing';
}
return null;
},
onSaved: (String value) {
_Dob = value;
},
),
),
]
)
),