Search code examples
androidflutterdartdart-null-safety

why I have get this errorin dart?


this is my code and getting these error:

  • The operator '<' can't be unconditionally invoked because the receiver can be 'null'.
  • The argument type 'int?' can't be assigned to the parameter type 'num'.

code

 void main()
        {
          int romanToInt(String s) {
              s=s;
              Map<String,int> roman = {
                  'I':1,
                  'V':5,
                  'X':10,
                  'L':50,
                  'C':100,
                  'D':500,
                  'M':1000
                };
                int result=0;
                for(int i=0;i<s.length;i++){
                  if(i+1<s.length && roman[s[i]]<roman[s[i+1]])
                  {
                    result-= roman[s[i]];
                  }else{
                    result+= roman[s[i]];
                  }
                }
                print(result);
              return result;
            }
        }

Solution

  • Try this:

    void main()
    {
      int romanToInt(String s) {
        s=s;
        Map<String,int> roman = {
          'I':1,
          'V':5,
          'X':10,
          'L':50,
          'C':100,
          'D':500,
          'M':1000
        };
        int result=0;
        for(int i=0;i<s.length;i++){
          if(i+1<s.length && roman[s[i]]!<roman[s[i+1]]!)//<- add null check
          {
            result-= roman[s[i]]!; //<- add null check
          }else{
            result+= roman[s[i]]!;// <- add null check
          }
        }
        print(result);
        return result;
      }
    }