I have the following code for the dropdownSearch in Flutter
However, the font is fixed and does not change when I change the screen size
enter image description here
DropdownSearch<String>(
items: items,
showSearchBox: showSearchBox ?? false,
dropdownSearchDecoration: InputDecoration(
contentPadding: const EdgeInsets.only(right: 8.0, left: 8.0),
floatingLabelStyle:
kResponsiveTextUbuntuFont(context, kDarkGreyColor),
labelText: labelTxt,
labelStyle: kResponsiveTextUbuntuFont(context, kDarkGreyColor),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: kDarkGreyColor, width: 2),
),
border: const OutlineInputBorder(
borderSide: BorderSide(color: kDarkGreyColor, width: 2),
),
),
onChanged: (newItem) => {},
showSelectedItems: true,
selectedItem: selectedItem,
popupBackgroundColor: kBackgroundColor,
dropdownSearchBaseStyle:
kResponsiveTextUbuntuFont(context, kDarkGreyColor),
mode: Mode.MENU,
),
Font:
TextStyle KResponsiveTitleUbuntuFont(BuildContext context, Color color) {
return TextStyle(
fontFamily: 'Ubuntu',
fontSize:
(setWidth(context, 0.001) >= 1) ? 30 * setWidth(context, 0.001) : 50,
fontWeight: FontWeight.w100,
wordSpacing: 5,
color: color);
}
I always find the solution directly after asking my own question xD...
Here's the solution:
Widget _customDropDownText(BuildContext context, String? name) {
return Container(
child: Text(
name.toString(),
style: kResponsiveTextUbuntuFont(context, kDarkGreyColor),
),
);
}
Build:
#override
Widget build(BuildContext context) {
.
.
.
DropdownSearch<String>(
items: widget.items,
dropdownBuilder: _customDropDownText,
showSearchBox: widget.showSearchBox ?? false,
.
.
.
}
solution
Related
UI
I want to build a form that is used to fill in the departure station and destination station. But I haven't implemented a way to prevent the user from filling in the same value in the 2 fields. And this is my code
Form(
key: _formKey,
child: Column(
children: [
// Stasiun Keberangkatan Form
DropdownSearch<String>(
validator: (value) {
if (value == null) {
return 'please input station';
}
return null;
},
popupProps: const PopupProps.menu(
showSelectedItems: true,
showSearchBox: true,
),
items: stationsToStName(),
dropdownDecoratorProps: DropDownDecoratorProps(
dropdownSearchDecoration: InputDecoration(
filled: true,
fillColor: const Color.fromRGBO(37, 37, 37, 0.1),
//hintText: "Stasiun keberangkatan",
hintText: "Departure Station",
hintStyle:
const TextStyle(fontFamily: 'Inter', fontSize: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
prefixIcon: const Padding(
padding: EdgeInsets.all(8.0),
child: Image(
height: 33,
image: AssetImage(
'assets/images/icon_departureSt.png'),
),
),
),
),
onChanged: (newvalue) {
setState(() {
stKeberangkatan = newvalue!; //updated
});
},
),
const SizedBox(height: 11),
// Destination Form
DropdownSearch<String>(
validator: (value) {
if (value == null) {
return 'please input station';
}
return null;
},
popupProps: const PopupProps.menu(
showSelectedItems: true,
showSearchBox: true,
),
items: stationsToStName(),
dropdownDecoratorProps: DropDownDecoratorProps(
dropdownSearchDecoration: InputDecoration(
filled: true,
fillColor: const Color.fromRGBO(37, 37, 37, 0.1),
//hintText: "Stasiun tujuan",
hintText: "Destination Station",
hintStyle:
const TextStyle(fontFamily: 'Inter', fontSize: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
hintMaxLines: 2,
prefixIcon: const Padding(
padding: EdgeInsets.all(11.0),
child: Image(
height: 33,
image: AssetImage(
'assets/images/icon_destinationSt.png'),
),
),
),
),
onChanged: (newvalue) {
setState(() {
stTujuan = newvalue!; //updated
});
},
),
const SizedBox(height: 35),
// "Submit" Button
SizedBox(
width: size.width,
height: 48,
child: ElevatedButton(
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all<Color>(Colors.white),
backgroundColor:
MaterialStateProperty.all<Color>(primColor),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
side: const BorderSide(color: primColor)))),
onPressed: () {
if (_formKey.currentState != null &&
_formKey.currentState!.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BestRoute(
stKeberangkatan: stKeberangkatan,
stTujuan: stTujuan,
)),
);
}
},
child: const Text("Submit",
style: TextStyle(
fontFamily: 'Inter',
fontWeight: FontWeight.w700,
fontSize: 14))),
),
],
),
),
I want to apply alert or validator if user fill in same value when click submit button
For example, the user fills in station A for departure station and destination station. And I want to avoid that. and I want to apply alert or validator if user fill in same value when click submit button
How can I implement that?
You can create two variables, one called departure and the other called destination. Then when the user selects a value from the dropdown, use setState((){}) to put the value in the variables.
Finally, when the user clicks on submit button, check if the value of destination and departure are different and only then allow the user to proceed.
I'm building a form for shipping and am able to add as many items as possible. (Adding a Widget in a ListView every time a button is pressed)
My question is, once the form widgets are created and filled, how do I get the information from each TextFormField in each Widget?
Once the information is retrieved I will send it to Firebase.
Here's the code I Have:
import 'package:flutter/material.dart';
import 'package:flutter_login_test/helpers/constants.dart';
class AddItemsToRequest extends StatefulWidget {
const AddItemsToRequest({Key? key}) : super(key: key);
#override
State<AddItemsToRequest> createState() => _AddItemsToRequestState();
}
class _AddItemsToRequestState extends State<AddItemsToRequest> {
List<TextEditingController> controllers = [];
List<Widget> fields = [];
RegExp regExp = RegExp('[aA-zZ]');
int quantity = 0;
double weight = 0;
double height = 0;
Widget itemForm() {
return Column(children: [
Container(
decoration:
BoxDecoration(color: grey, border: Border.all(color: black)),
width: double.infinity,
child: const Center(
child: Text('Package details',
style: TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: grey,
fontSize: 24)),
)),
Row(
children: [
Flexible(
child: TextFormField(
onChanged: (value) {
quantity = value as int;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || value is int
? 'Quantity cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Quantity : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
weight = value as double;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || regExp.hasMatch(value)
? 'Weight cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Weight : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
height = value;
},
validator: (value) => value!.isEmpty ? 'Height cannot be empty' : null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Height : "),
),
),
],
),
]);
}
Widget _addTile() {
return ElevatedButton(
child: const Icon(Icons.add),
onPressed: () async {
final controller = TextEditingController();
final field = itemForm();
setState(() {
controllers.add(controller);
fields.add(field);
});
});
}
Widget _listView() {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: fields.length,
itemBuilder: (context, index) {
final item = fields[index];
return Dismissible(
key: ObjectKey(item),
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
fields.removeAt(index);
});
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Package removed')));
},
background: Container(
color: const Color.fromARGB(255, 210, 31, 19),
child: const Center(
child: Text(
'Remove ',
style: TextStyle(
color: white, fontWeight: FontWeight.bold, fontSize: 32),
),
)),
child: Container(
width: double.infinity,
margin: const EdgeInsets.all(5),
child: fields[index],
),
);
},
);
}
Widget _okButton() {
return ElevatedButton(
onPressed: () {
for (var element in fields) {
print(quantity);
}
Navigator.of(context).pop();
print('ok');
},
child: const Text("OK"),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: blue),
body: Column(
mainAxisSize: MainAxisSize.max,
children: [
Flexible(child: _addTile()),
SizedBox(
height: MediaQuery.of(context).size.height - 200,
child: _listView()),
Flexible(child: _okButton()),
],
),
);
}
}
I think you are expecting this answer. iterate your list of texteditingcontroller and get the text stored in that controllers one by one.
for (int i = 0; i < controllers.length; i++) {
var data = controllers[i].text;
//print or add data to any other list and insert to another list and save to database
}
I am using flutter typeahead to suggest options to a user based on their text input.
When entering any input, the first suggestion is always just what the user types. I would like to restrict this to just suggestions retrieved from the backend, and this is getting in the way of that. Is there a solution?
Widget get typeAheadField{
return SingleChildScrollView (
child: TypeAheadField(
//autoFlipDirection: true,
hideOnEmpty: true,
hideOnLoading: true,
minCharsForSuggestions: 1,
getImmediateSuggestions: false,
direction: AxisDirection.up,
keepSuggestionsOnLoading: false,
textFieldConfiguration: TextFieldConfiguration(
textAlign: TextAlign.center,
autofocus: true,
style: DefaultTextStyle.of(context).style.copyWith(
color: Colors.white,
fontSize: 20.0,
),
decoration: InputDecoration(
hintText: "Tag Friends: ",
hintStyle: TextStyle(color: Colors.grey, fontSize: 20.0,),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12.0),
borderSide: const BorderSide(
color: Colors.white,
width: 2.0,
),
),
),
),
suggestionsCallback: getSuggestions,
itemBuilder: (context, suggestion) {
return getList(context, suggestion);
},
onSuggestionSelected: (suggestion) {
addUser(suggestion);
},
)
);
}
replace return getList(context, suggestion);
with
List<String> newSuggestions=suggestion.where((e)=>e!= "the user input from the controller " ) ).toList() ;
return getList(context, newSuggestions);
I am using the typeahead package for flutter to show a textfield with the suggestions capability, but I am getting unwanted behavior. When the user first tap the field, I do not want to show any suggestions but it's showing a list of all suggestions like a dropdown field. I have even set getImmediateSuggestion: false but it's still doing this[![enter image description here][1]][1]
alignment: Alignment.center,
//padding: EdgeInsets.symmetric(vertical: 16),
//height: (0.0725 * y),
child: TypeAheadFormField(
keepSuggestionsOnLoading: false,
hideOnEmpty: true,
hideOnLoading: true,
//initialValue: '',
enabled: false,
hideOnError: true,
textFieldConfiguration: TextFieldConfiguration(
//textAlign: TextAlign.left,
//autofocus: true,
controller: _typeAheadController,
style: TextStyle(color: mainTextColor, fontSize:14, fontWeight: FontWeight.w400 ),
decoration: InputDecoration(
filled: true,
fillColor: cardColor,
labelStyle: TextStyle(fontSize: (0.04*x), color: mainTextColor, fontWeight: FontWeight.w400),
hintText: 'Type degree',
hintStyle: TextStyle(fontSize: (14), color: hintColor, fontWeight: FontWeight.w400),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide.none),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: hintColor, width: 0.8)
)
),
),
//suggestionsBoxController: ,
getImmediateSuggestions: false,
suggestionsCallback: (pattern){
return DegreeSearchService(uni: currentUniversity).getSuggestions(pattern);
},
itemBuilder: (context, suggestion){
return ListTile(
dense: true,
title: Text(suggestion, style: TextStyle(fontSize: 14,color: Colors.black),)
);
},
onSuggestionSelected: (suggestion){
_typeAheadController.text = suggestion;
currentDegree = suggestion;//enable next press
//pageController.animateToPage(++currentPage, duration: Duration(milliseconds: 250), curve: Curves.bounceInOut );
}
)
), ```
[1]: https://i.stack.imgur.com/FUXjl.png
Try to change your suggestionsCallback to not show results if the pattern length is 0, for example:
suggestionsCallback: (pattern){
if (pattern.length > 1) {
return DegreeSearchService(uni:currentUniversity).getSuggestions(pattern);
}
},
I'm using flutter package country_code_picker into my TextFormField and i achieve to put users country dial code into my phone TextEditingController text after they select there country. So if for example in Senegal user put 7712345678, i will get +2217712345678 in my TextEditing controller text. Thanks in advance for help.
here is my code
TextEditingController phoneController = new TextEditingController(text: "");
Widget _phoneContainer() {
return new Container(
child: new TextFormField(
controller: phoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 2),
prefixIcon: CountryCodePicker(
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: '+221',
favorite: ['+221', 'SN'],
textStyle: TextStyle(color: Colors.orange[900]),
showFlag: true,
//showFlagDialog: true,
//comparator: (a, b) => b.name.compareTo(a.name),
//Get the country information relevant to the initial selection
//onInit: (code) => print("${code.name} ${code.dialCode}"),
),
labelText: Texts.PHONE_NUMBER_LOGIN,
focusColor: Colors.orange[900],
labelStyle: TextStyle(fontSize: 15.0, color: Colors.orange[900]),
/* hintStyle: TextStyle(
color: Colors.orange[900]
) */
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
hasFloatingPlaceholder: false
),
keyboardType: TextInputType.phone,
style:TextStyle(
color: Colors.orange[900],
decorationColor: Colors.white,
),
),
margin: EdgeInsets.only(bottom: 20.0, left: 40.0, right: 40.0),
color: Colors.white,
height: 40.0,
);
}
Run this code. On Check Button, it will print your whole phone number (dial code + entered phone number in text field) on console
import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
TextEditingController phoneController = new TextEditingController();
String phoneNumber = "";
void _onCountryChange(CountryCode countryCode) {
this.phoneNumber = countryCode.toString();
print("New Country selected: " + countryCode.toString());
}
void check(){
print("Full Text: "+ this.phoneNumber + phoneController.text);
}
#override
Widget build(BuildContext context) {
final phone = new TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
autofocus: false,
style: new TextStyle(fontSize:14.0,
color: Colors.black,
fontWeight: FontWeight.w400,),
);
final checkBtn = RaisedButton(key: null, onPressed: check,
color: Colors.blue,
child: new Text("Check")
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Country Code Demo'),
),
body: Center(
child: new ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
CountryCodePicker(
onChanged: _onCountryChange,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT',
favorite: ['+39','FR'],
// optional. Shows only country name and flag
showCountryOnly: false,
// optional. Shows only country name and flag when popup is closed.
showOnlyCountryWhenClosed: false,
// optional. aligns the flag and the Text left
alignLeft: false,
),
SizedBox(height: 16.0),
phone,
SizedBox(height: 16.0),
checkBtn
]
),
),
)
);
}
}