I'm trying to use a InputForm to validate the change of a purchase (It can'tbe less than the total purchase amount), the validation itself is working, but when I type a number, then I clean it, it gives me a FormatException uppon deleting all the numbers. Does anyone know why this happen?
Here's the InputForm:
`ShinInputForm(
controller: trocoController,
placeholder: 'R\$00,00',
borderWidth: 2.0,
validator: (String? trocoController) {
frete = double.parse(appModel
.enderecoLojaSelecionada!.frete!.valor
.toString());
var valorTotal = carrinhoModel.valorTotal + frete;
var valorTroco = num.parse(trocoController!);
if (valorTroco <= valorTotal) {
return "Digite um valor maior que R\$" +
valorTotal.toString();
}
return null;
},
),`
i've tryed to change the return type, but it didn't help.
Related
I want to allow users to select numbers from 0 to 9999.99 and 4 before the decimal separator and 2 after the decimal separator.
I used the following script to get the desired result
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
// Allow Decimal Number With Precision of 2 Only
FilteringTextInputFormatter.allow(
RegExp(r"^\d{0,4}^\d*\.?\d{0,2}")),
],
maxlength = 7,
onChanged: (value) {
if (value.isNotEmpty) {
fixedString = double.parse(value);
}
if (fixedString > 9999.99) {
showSnackbar(context,
text: "value can not be greater than 9999.99");
allowanceValue = "9999.99";
} else {
allowanceValue = value;
print("String fixed $allowanceValue");
}
},
the result I get when the user try to type a value greater than 9999 will show a snack bar to user but I am not satisfied with this solution as I am getting unhandled exemptions sometimes.
the i want to achieve that whenever the user type a value before the decimal separator it will no typed and after 4 digits it stops and when user add decimal separator it continue to 2 digits
I want to run if else condition but it seems to be an error i don't know what the error.I also print Correct option it seems to be equal to selected value but it is not running my if condition.Please solve error,
This is the output of correct option and selected option
this is my code:
ElevatedButton(onPressed: (){
if(Selectedvalue==snapshot.data!.docs[randomIndexes[index]]["Correct"]){
correctAnswers++;
print("correct");
print(Selectedvalue);
}
else{
print("incorrect");
print("Selected value:$Selectedvalue");
print("Correct:${snapshot.data!.docs[randomIndexes[index]]["Correct"]}");
}
Selectedvalue=0;
num++;
qno++;
_pageController.nextPage(duration: Duration(milliseconds: 300), curve: Curves.easeIn);
if (index == randomIndexes.length-1) {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=>show_result(result: correctAnswers.toString())));
}
},
child: Text("Submit",style: TextStyle(color: Colors.yellowAccent),)),
Can you check that value that you are getting from snapshot.data!.docs[randomIndexes[index]]["Correct"] is type of number or not
As condition will be false if you are trying to compare integer with string
for ex :-
void main() {
String str = "1";
int numberVar = 1;
if(str == numberVar){
print("equal");
}else{
print("not equal");
}
}
output - not equal
in above example , both have same value but have different type so condition is getting false
if you have same issue as above example then here is solution for your code
replace this line
if(Selectedvalue==snapshot.data!.docs[randomIndexes[index]]["Correct"]){
with this
if(Selectedvalue==int.parse(snapshot.data!.docs[randomIndexes[index]]["Correct"])){
hope this will help you
I know it seens duplicate, but its not, the answers from the other topics is nothing like i am facing here.
I really dont know whats going on, everthing is integer but stills aplies as string...
The problem occur on the FOR LOOP (if i print the somaModulos it shows the math correctly, only if i print inside the FOR LOOP, if i print outsite the FOR, it brings the errow below).
Everthing later dont execute because the problem "type 'int' is not a subtype of type 'String'"
var textModulos = modulosNecessarios.toString();
int somaModulos = 0;
void recalcularModulos() {
print(modulosConfig);
print(int.parse(modulosConfig[0][0]) * int.parse(modulosConfig[0][1])); //THIS WORKS
for (var i = 0; i < modulosConfig.length; i++) { // THIS DONT WORK
somaModulos +=
int.parse(modulosConfig[i][0]) * int.parse(modulosConfig[i][1]);
}
/*
setState(() {
textModulos = (modulosNecessarios - somaModulos).toString();
});
*/
}
The results of the prints:
1º
[[20, 3, colonial, retrato], [0, 0, colonial, retrato]]
2º
60
Well, it seens that the array type values changed on the textField onChange.
Even the text input type was a number, it changes to string if i put it on the onChange method, i was not paying attetion to that (i am new to dart).
The items in the list was always creating with int values, but it changed to string in the middle of the process...
TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: "Quantidade de módulos"),
style: TextStyle(fontSize: 18),
controller: _controllerQnt,
onChanged: (String value) {
setState(() {
modulosConfig[itemUtilized][0] = value;
});
},
To make it work, i changed the array incremention from:
modulosConfig.insert(indexStart, [0, 0, 'colonial', 'retrato']);
To:
modulosConfig.insert(indexStart, ['0', '0', 'colonial', 'retrato']);
Or change the TextField onChange method integer.
I choose to change the incremention to all string and then parse it on the FOR LOOP.
I know that there is many ways / package to implement multi select in dropdownbutton in flutter like --> this one
But with my little knowledge, I want to reinvent the wheel for basic building!!!
My scenario ->
I have a list of location's in json format like this -->
[{id: 928, location: Amtoli}, {id: 905, location: Ashok Tala}, {id: 899, location: Badur Tola}]
and two List -->
List _location = new List(); // this comes from API;
List _multiSelectLoc = new List();
And in DropDownButton's onChanged property -->
onChanged: (newValue) {
setState(() {
_location.forEach((e) {
if (e["id"] == newValue.toString()) {
_multiSelectLoc.add(e);
print(_multiSelectLoc);
}
});
_location.removeWhere(
(e) => e['id'] == newValue.toString());
print(_location);
});
},
I am curious to know why my code was not working, why I can't remove data from List _location, and and add to List _multiSelectLoc
I already simulated such condition in dartpad and it's just woking fine!
I guess I found the problem,
rewritten code -->
onChanged: (newValue) {
_location.forEach((e) {
if (e['id'].toString() == newValue.toString()) {
_multiSelectLoc.add(e);
// print(_multiSelectLoc);
}
});
_location.removeWhere(
(e) => e['id'].toString() == newValue.toString());
setState(() {
// print(_location);
});
},
I think the problem was, I was using a dynamic type to compare with string type, when I added .toString() the code started to giving me the results!
I need to store some hexadecimal colors for my items like #fff, #fafafa, red. What is the best type should I use for this purpose?
Thanks!
Simply use String and add some validation to make sure the input is of the correct type:
COLORS = ['red', 'blue', ...];
function colorValidator (v) {
if (v.indexOf('#') == 0) {
if (v.length == 7) { // #f0f0f0
return true;
} else if (v.length == 4) { // #fff
return true;
}
}
return COLORS.indexOf(v) > -1;
};
new Schema({
color: { type: String, validate: [colorValidator, 'not a valid color'] }
});
I wrote the colorValidator quickly to help you get an idea but you can easily extend it to get a more sophisticated color verification.
You can use validator with a regular expression test:
const colorValidator = (v) => (/^#([0-9a-f]{3}){1,2}$/i).test(v)
const schema = new Schema({
color: {
type: String,
validator: [colorValidator, 'Invalid color'],
required: true,
},
});
It matches #fff #ffffff #FFF #FFFFFF (3 and 6 digits, case insensitive).