skip to Main Content

I am new to Flutter/Dart but I have experience with Typescript. Can you help me with the following code and question:

final String? title;

appBar: title != null
        ? AppBar(
            title: Text(title),
          )
        : null,

I am getting the error message The argument type 'String?' can't be assigned to the parameter type 'String'.

I thought that the condition title != null would ensure that title is not null. Is there a better way to handle this? to not add just Text(title!),?

3

Answers


  1. Dart is null-safe,

    so you can’t define a variable without giving it an init value,

    you may define an init value and it will be an empty string or if you are sure that you will give value to that variable before assigning it to the screen you can use late keyword, Note that if you misuse it and didn’t assign a value before the screen is built, you will get a null error in the screen.

    if you want it to accept that title could be a string or null you put the ? after String.

    if you want to use that variable you need to put The null assertion operator (!)
    telling dart that you are sure it won’t be null during runtime

    refer to this documentation to have a better understanding of Null Safety in Dart Null Safety

    Login or Signup to reply.
  2. Only local variables can be used like that because there are situations where the title can return null the second time it’s accessed. So you could do this if you really don’t want to use !

      @override
      Widget build(BuildContext context) {
        final t = title;
        return Scaffold(
          appBar: t != null
                ? AppBar(
              title: Text(t),
            )
                : null,
    

    To give an example of why it’s not guaranteed that title is not null the second time consider this program:

    import 'dart:math';
    
    main() {
      var b = B('whatever');
      b.printTitleLength();
    }
    
    class A {
      final String? title;
    
      A(this.title);
    
      void printTitleLength() {
        if (title != null) {
          print(title!.length);
        }
      }
    }
    
    class B extends A {
      B(super.title);
    
      @override
      String? get title => Random().nextBool() ? 'test' : null;
    }
    

    Note I had to put the ! in the print line otherwise it wouldn’t compile. But also note that this possibly can throw an exception since it’s possible title returns null after the null check.

    Login or Signup to reply.
  3. use null aware operator to assign a default value when title is null, as Text widget expects a non null value.

    final String? title;
    
    appBar: title != null
            ? AppBar(
                title: Text(title??""),
              )
            : null,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search