Flutter- how to disable a Button untill the requireed fields are filled - flutter

I want to disable a button untill all the required fields are filled. I found similar questions here but all answers are based on making the onPressed property to null. But it does not disable the tap effect.
I want something like this. On disabled mode, clicking on the button won't even cause a Tap effect. Can someone help with a solution?

For a limited number of widgets, you can wrap them in a widget IgnorePointer: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.
IgnorePointer(
ignoring: true, // or false
child: CustomButton(
onPressed: _login,
child: Text("Login"),
),
)

checkout this widget.set absorb to true when the required field is empty or is not validated.
https://api.flutter.dev/flutter/widgets/AbsorbPointer-class.html

In the textField add
onChanged : (val){ setastate((){});}
You mustbe already having a TextEditingController for the textfield. For example i shall name it phoneTextController.
Now in the button check the condition
phoneTextController.text.length > 10
For example
Inkwell(
onTap:(){
if(phoneTextController.text.length > 10){
SendOtp()
}
}
child: Container(
color: phoneTextController.text.length > 10 ? Colors.blue : Color.blue.withOpacity(0.5),
)
)

If you're using one of Flutter's built-in button Widgets, setting the onTap to null should automatically disable the button and its effect. Now all that remains is to conditionally do this during your build. Say, like the other answer, your TextEditingController is named phoneTextController:
ElevatedButton(
child: Text('Next'),
onTap: phoneTextController.text.length > 10 ? () => goToNextPage() : null,
),
Which will automatically enable the button and add the callback as soon as the condition is met (in this example, the input length is >10.

Related

How do i modify the data of an existing variable in flutter?

I want to make an editable TextWidget in flutter but I don't really know how to go around it, I did some research, but still can't find a good solution.
Here's my sample code below.
I have a variable called
int qty = 1;
and so I called the variable in TextWidget
Column(
children: [
Text(
"${qty}",
style: TextStyle(),
)
],
),
I want to have these features that make user tab on the value to change it if they want, upon tap, a pop-up dialog will show to give the user the ability to change the existing value to whatever the user wants.
Please if anyone knows how, please help.
You will need a statfull widget to call setState and make the UI update with the new value stored in your qty variable. (I'am assuming that you are not using any state managment).
I wrote a possible solution for what you need.
Let look into some considerations:
Text will show whatever is in the qty as long we call setState after (or do it inside) we change the value of qty.
You need some widget to detect your tap. If you want to the text be 'clicable' then it should be wraped inside that widget.
The onTap/onPress call back of that widget should show a new widget. For this you can use the already made showDialog() and pass it a Dialog Widget. in here you will put your ui for that.
In some point of that UI you need to introduce the new value. So you can use a simple TextField that will save the introduced value, where you can assign it to qty, without forgetting to call setState! Note that it deal with strings, so you neet to do an int.parse() ou double.parse accordingly to you qty var type.
And I think that's it.
The could be other ways of doing it. This is a good and simple approach for your need.
I wrote a piece of code to help or somelse how is trying to do it:
InkWell(
// can be gesture detector, button, etc
onTap: () => showDialog(
context: context,
builder: (context) => Dialog(
child: Container(
color:
Colors.white60, // change it accordingly to you
height: 80, // change it accordingly to you
width: 200, // change it accordingly to you
child: Column(
children: [
const Text('Change your value here'),
TextField(
decoration:
InputDecoration(hintText: qty.toString()),
onChanged: (insertValue) => setState(() {
qty = int.parse(insertValue);
}),
// you can use other callBack function (like onComplete,
// onSaved), wich is more eficient than calling setState eveytime,
// but you have to do the needed adtaptions. Like onSave
// needs a key to call the save function. is easy just google it.
),
],
)),
)),
child: Text(
"${qty}",
),
),
What you are probably looking is a DropdownButton.
You would have something like this:
int qty = 1;
List<int> listOfValues = [1,2,3,4];
and then in your column you would have
DropdownButton<int>(
// This are the list of items that will appear in your dropdown menu.
// items is all the options you want your users to be able to select from,
// and it take a list of `DropdownMenuItem`. So instead of creating a `DropdownMenuItem`
// for each of the items in `listOfValues`, we iterate through it and return
// a `DropdownMenuItem`
items: listOfValues
.map((item) => DropdownMenuItem<int>(
value: item,
child: Text('$item'),
))
.toList(),
value: qty,
onChanged: (value) {
if (value != null) {
setState(() {
qty = value;
});
}
},
),
For more information on DropDownButton, check the following links:
https://api.flutter.dev/flutter/material/DropdownButton-class.html
https://www.youtube.com/watch?v=K8Y7sWZ7Q3s
Note: In a scenario where you want to increase the quantity of an item, like in a shopping cart, maybe having a button increment qty by 1 would be better.

How to change a state of a widget that is generated from list in flutter

My problem is simple. I was building a ListTile from the list of documents I get from firebase by iterating through the results. The ListTile contains a leading icon, a title, and a trailing favorite IconButton. The list tile shows perfectly as I want it to. But the problem arises when I try to change the color of the IconButton while a user taps on it. For some reason, the code I wrote isn't doing the trick. What i tried to do was to set the value of the IconButton's color by a ternary which uses a class variable named isFavorited. What i wanted it to do is change the color of the IconButton when i tap on that same IconButton. Here is my code block:
// Builds a tile for each brought up names of taxistops
if (retrievedData.isNotEmpty) {
retrievedData.forEach((element) {
if (element.contains(query) ||
element.contains(query.toUpperCase()) ||
element.contains(query.toLowerCase())) {
ListTile listTile = ListTile(
leading: Icon(Icons.local_taxi),
title: Text(element),
trailing: IconButton(
icon: isFavorited
? Icon(
Icons.star,
color: Colors.amber[400],
)
: Icon(Icons.star_border),
onPressed: () => {
setState(() {
isFavorited = true;
}),
addToFavorite()
},
),
onTap: () => close(context, element),
);
searchedTiles.add(listTile);
}
});
}
Any help is appreciated! Thank you in advance!
I think the problem is because you are adding the widget in the list you should preview it directly inside the widget father (ListView) so it can do the setState correctly and not inside a list you created as a data structure to store elements.
I think that's the issue if it still doesn't work I would need to see how you are showing the list.

flutter typeahead suggestionbox doesn't hide

my problem:
The suggestionbox doesn't hide, except i choose one suggestion. hideSuggestionsOnKeyboardHide changes absolutely nothing...
I saw that others solved this problem with another package named keyboardvisibility.
But for me this is not a solution, beause i don't want the suggestionbox to disappear as soon as the keyboard disappears, I want the suggestionbox to disappear as soon as I tap somewhere outside the suggestionbox. Hope someone can help.
Here my code if it helps:
TypeAheadField(
hideOnEmpty: true,
hideOnError: true,
suggestionsBoxController: _suggestionsBoxController,
textFieldConfiguration: TextFieldConfiguration(
controller: typeAheadControllerA,
decoration: const InputDecoration(
hintText: 'Artikelnummer',
icon: const Icon(
Icons.business_center,
color: Colors.grey,
))),
suggestionsCallback: (pattern) {
return autoA
.where((autoA) =>
autoA.toLowerCase().contains(pattern.toLowerCase()))
.toList();
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(suggestion),
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
typeAheadControllerA.text = suggestion;
},
)
Another minor problem/question:
How can i change the width of the suggestionbox / adapt to the width of the input field?
When I set the icon, logically the width of the input field decreased but the width of the suggestion box did not adapt to the width of the input field. I tried with suggestionsBoxDecoration offsetX. With offsetX I can move the box to the right, but the box keeps its width and therefore goes too far to the right but then i tried with wrapping the typeaheadfield in a padding widget or sizedbox but nothing works. If nobody knows how to solve this, I will probably remove the icons...
Thanks for help :)
You just use the keyboard "done" on iOS physical devices (I haven't tested it on Android yet - assuming there is something similar?), or click another field if there is one. The iOS simulator just doesn't bring up the keyboard when typing so it annoyingly seems like it can't be hidden without selecting a suggestion.
Tapping outside the field but not on another field doesn't unfocus normal TextFields either.
Use this metod: hideSuggestionsOnKeyboardHide: true,
You should wrap your scaffold with GestureDetector and with the property onTap() you call _suggestionBoxController.close();. Another thing if it does not work for you maybe you have a lot of code that is executed in one single file a simple refactoring can be your solution and set hideSuggestionsOnKeyboardHide : true (it was my case). For the width of the box suggestionBoxController.resize()

Flutter toggle Radio widget

I'm using Radio widgets to set the user gender. These Radio button widgets are designed very well to handle the selection changes act accordingly, but I does not find a solution to somehow deselect one already selected option. I would like the gender radio group to be optional. But after user selects let's say female, he/she can change the selection to male, but can't deselect the female/male option. (So that none of the option is selected.)
There is only an onChanged property and it only changes if the gender changes. No such thing like onTap or something similar. So no matter if I check that gender if it's the same, onChanged won't be called.
For that reason I tried to use a GestureDetector which should solve this issue (with this I should be able to deselect the already selected option) but in case of radio widgets it does not work. I also tried to change it's behavior property but it did not help either.
Here is the function which I use to create gender radio option with a text in a Row.
Widget _buildRadioWithText(final genderChangeNotifier, final Gender genderParam, final String genderText) {
return Row(
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
child: Radio<Gender>(
visualDensity: VisualDensity.compact,
value: genderParam,
groupValue: genderChangeNotifier.gender,
onChanged: (Gender gender) {
genderChangeNotifier.gender = gender;
print(gender.toString());
},
),
onTap: () {
if (genderChangeNotifier.gender == genderParam) {
genderChangeNotifier.gender = Gender.NA;
print("Not answered!");
}
},
),
GestureDetector(
onTap: () {
if (genderChangeNotifier.gender == genderParam) {
genderChangeNotifier.gender = Gender.NA;
print("Not answered!");
} else {
genderChangeNotifier.gender = genderParam;
print(genderParam.toString());
}
},
child: Text(
genderText,
style: TextStyle(
fontSize: _fontSize,
),
),
),
],
);
}
Function call:
_buildRadioWithText(genderChangeNotifier, Gender.FEMALE, "Female"),
_buildRadioWithText(genderChangeNotifier, Gender.MALE, "Male"),
genderChangeNotifieris just a provider to set and get the Gender value and notify listeners when a Gender is set.
final GenderNotifier genderChangeNotifier= Provider.of<GenderNotifier>(context);
GestureDetector's onTap works well when I tap on the Text widget. It selects then deselects the option just as I'd like to but in case of the Radio widget onTap is never called.
Any idea how to achieve the deselection when I tap/click on the Radio widget itself? And why the GestureDetector that wraps the Radio does not register the tap events?
The GestureDetector's onTap is not being called because the GestureDetector inside the Radio widget is taking priority. By default, when two GestureDetectors are competing for input, only one will "win". In this case, the winner is the one in the Radio. This article discusses "GestureArenas" and how you can allow both GestureDetectors to process input.
However, consider whether allowing the user to deselect the radio button is the correct solution. Radio buttons are designed not to be deselected once the user has selected an option. You might instead:
Offer a third, "I'd rather not say" option
Use toggleable buttons instead of a radio group
Use a dropdown menu instead of a radio group
See this answer for more info on the usability aspect of this.

In flutter, RaisedButton has disabledColor option in its constructor but no option to disable it?

In flutter, Raisedbutton has disabledColor option in its constructor but not any option to disable it? So how can someone apply the disabledColor when there is no information about whether RaisedButton is disabled or not.
If don't set onPressed callback, the button will be disabled.
RaisedButton(
child:Text("Disabled)
)
You need to pass onPressed otherwise IDE will show error/warning.
Use this,
RaisedButton(
onPressed: null, // disables the button
disabledColor: Colors.orange,
child: Text("Disabled"),
)
Output: