skip to Main Content

Say I have the function below that formats a string response back from an API call.

String formatResponse(String text){
    return text.toUpperCase();
}

and I want to use this function in my Flutter component like so.

class _ComponentWithState extends State<ComponentWithState> {
    
    String? serverResponse;
 
    @override
    void initState() {
        ApiController().loadFromServer().then((response){
            setState((){
                serverResponse = response;
            })
        }
    }

    @override
    Widget build(BuildContext context) {
        
        if(serverResponse == null){
            return LoaderComponent();
        }
        return Text(formatResponse(serverResponse)); // This line says String? cant be passed to type String

    }
    
}

This code would raise an error saying that you cant pass a String? to type String.
Which in the case of null saftey makes sense, but this code has an early return to handle the null check.

Is there something im not understanding about null safe design patterns? The code seems logical to me coming from non null safe languages. This example is obviously very trivial, but I think it conveys the issue.

Note:

  • as a hack (and that’s truly what it feels like) ive just been using serverResponse ?? "" but that feels really bad to have to do.

2

Answers


  1. return switch(serverResponse) {
      null => LoaderComponent(),
      final v => Text(formatResponse(v)),
    };
    
    Login or Signup to reply.
  2. Because your string is in the class and not inside the function the analyzer can’t infer the string is not null even after the if, because your other methods can change it.

    Try reading it into a variable inside your method and use that var

    final String? response = server response
    
    if (response == null) {
        return LoaderComponent();
    }
    return Text(formatResponse(response)); // it won't throw a possible null
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search