skip to Main Content

I have performed a null check but still I’m getting the below error.

error: The argument type 'String?' can't be assigned to the parameter type 'String'. (argument_type_not_assignable at [sitewalk] lib/modules/floor_plan/widgets/dialog_nested/dialog_nested.dart:122)

Screenshot below for better understanding:
enter image description here

Now if I use the null assertion operator(!) the error will be gone. But I wanted to know why it’s giving an error on the first place?

Is it because if we use multi thread this value can be changed which might cause an error?

5

Answers


  1. You need a variable, that is considered to be a candidate for type promotion from String? to String. The easiest way is to have a local variable:

    @override
    Widget build(BuildContext context) {
      final localErrorMessage = errorMessage;
      if(localErrorMessage == null) {
        return SizedBox.shrink();
      } else {
        return Text(localErrorMessage);
      }
    }
    
    Login or Signup to reply.
  2. Dart complier doesn’t consider the null checks in the if else condition. That’s why it failed to recongize the "errorMessage" will not receive null value.

    Instead you can

    1. Either make the errorMessage Required in the class or assign the default value
    2. You can assign null check the value errorMessage ?? 'Something went wrong or errorMessage!
    Login or Signup to reply.
  3. The reason is actually that subclasses of your Test class may override the field with a getter that doesn’t consistently give the same value back. Like this:

    class Test2 extends Test {
      const Test2({super.key, super.errormessage});
    
      @override
      String? get errorMessage => Random().nextBool() ? null : 'aaa';
    }
    

    In this case the null check might pass the first time but when getting it for the Text it might return null

    Login or Signup to reply.
  4. You can do it like:

    Put bang operator to end of the ‘errorMessage’

    class Test extends StatelessWidget {
      final String? errorMessage;
    
      const Test({
        Key? key,
        this.errorMessage,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        if (errorMessage == null) {
          return const SizedBox.shrink();
        } else {
          return Text(errorMessage!);
        }
      }
    }
    
    Login or Signup to reply.
  5. use this code

      class MyClass extends StatelessWidget {
      final String? errorMessage;
      const MyClass({Key? key, this.errorMessage,}) : super(key: key);
        @override
         Widget build(BuildContext context) {
          if (errorMessage == null) {
          return const SizedBox.shrink();
        } else {
          return Text("$errorMessage");
        }
      }
    }
    

    have good time;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search