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

Time:09-15

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);
  }
}

CodePudding user response:

import 'package:flutter/material.dart';

class Utils{ 
   

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

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

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

try this pass global key in function,seems like due to not initializing key you are getting issue

CodePudding user response:

showSnackBar is a function of currentState but you try to apply it to another function. Split it up like

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

or alternatively write it like this:

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

CodePudding user response:

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

  • Related