Home > Net >  how to handle adding null values with eachother
how to handle adding null values with eachother

Time:10-18

I want to input three numbers into TextFormFields. The controllers are numOneController and numTwoController for putting the percent and a totalAmountController for putting the the amount. I then want to check if the percents are in total 100 so i can display they are indeed so. When totalAmountController is empty(null) then its no problem to display that its an invalid input but when the numOneController and numTwoController are empty i get the error Invalid number (at character 1). I know its the fact that handler can't add an empty number with another. But how can i handle this so i can check if its null then i want to assign a number 0 to add that automaticly.

  sumHandler() {
    var totalPrecent = int.parse(numOneController.text)  
        int.parse(numTwoController.text) ;

    var totalAmount = totalAmountController;

    if (totalPrecent == 100 && totalAmount.text.isEmpty == false) {
      debugPrint(totalPrecent.toString());
      debugPrint(totalAmount.text.toString());
    } else {
      debugPrint("invalid input");
    }
  }

CodePudding user response:

Using the tryParse method and a default value would help...



 sumHandler() {
    var totalPrecent = int.tryParse(numOneController.text) ?? 0  
        int.tryParse(numTwoController.text) ?? 0;

    var totalAmount = totalAmountController;

    if (totalPrecent == 100 && totalAmount.text.isEmpty == false) {
      debugPrint(totalPrecent.toString());
      debugPrint(totalAmount.text.toString());
    } else {
      debugPrint("invalid input");
    }
  }

CodePudding user response:

Create a temp variable and store it with 0 and later if the textfield has values assign values to it. Like the following

sumHandler() {
    int firstNumber = 0;
    int secondNumber = 0;
    if(numOneController.text != "")
    {
      firstNumber = int.parse(numOneController.text);
    }
    if(numTwoController.text != "")
    {
      secondNumber = int.parse(numTwoController.text);
    }
    var totalPrecent = firstNumber   secondNumber ;

    var totalAmount = totalAmountController;

    if (totalPrecent == 100 && totalAmount.text.isEmpty == false) {
      debugPrint(totalPrecent.toString());
      debugPrint(totalAmount.text.toString());
    } else {
      debugPrint("invalid input");
    }
  }
  • Related