Flutter compile error: non-null value must be returned since the return type 'String' doesn't allow null - displayString

Viewed 3102

My tests are failing to compile and run in a Dart only project that is referenced by my Flutter project. I'm receiving the following error message

Failed to precompile test:test:
../../../../../../../../../.pub-cache/hosted/pub.dartlang.org/analyzer-1.0.0/lib/src/error/best_practices_verifier.dart:1952:14: Error: A non-null value must be returned since the return type 'String' doesn't allow null.
  String get displayString {

Any ideas please?

Flutter 2.2.1 (current stable channel)
Tools • Dart 2.13.1

(I've asked the question in Flutter's github here also) https://github.com/flutter/flutter/issues/83683

3 Answers

There was a component using analyzer version 1.0.0

Upgrading this component to use analyzer version 1.7 or above seemed to fix the problem for me.

go to this file: flutter/.pub-cache/hosted/pub.dartlang.org/analyzer-1.5.0/lib/src/error/best_practices_verifier.dart:1978:14.

and add below:-

default:
    return '';

Please check the function displayString to make sure that it returns non-null string variable. There are some use cases that I guess you might face with

  1. Use "required" if you get the variable from parameters (ex: String displayString(required String var)).
  2. If the variable is optional parameter, then you need to check if it is null or not. Then, you could "return var!;" to let the function knows that you already confirmed the variable content.
  3. If you want to return nullable String, then you should change the function to "String? displayString".
Related