Search code examples
flutterdartvoiddart-null-safetysnackbar

error: This expression has a type of 'void' so its value can't be used


import 'package:flutter/material.dart';

class Utils{
  static final messengerKey = GlobalKey<ScaffoldMessengerState>();

  static showSnackBar(String? text){
    if (text == null) return;

    final snackBar = SnackBar(content: Text(text), backgroundColor: Colors.red,);

    messengerKey.currentState!.removeCurrentSnackBar().showSnackBar(snackBar);
  }
}

Solution

  • As mentioned before void Funtion() can't be assigned to anything. So what happens here is messengerKey.currentState!.removeCurrentSnackBar() returns void, that's why you can't use anything after that. But if you use .. you return the object function was called on, therefore messengerKey.currentState!..removeCurrentSnackBar()..showSnackBar(snackBar); is a valid expression