-1
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);
  }
}
Ivo
  • 18,659
  • 2
  • 23
  • 35

3 Answers3

0
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

MohitJadav86
  • 782
  • 3
  • 11
0

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);
Ivo
  • 18,659
  • 2
  • 23
  • 35
0

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

noxgood
  • 180
  • 1
  • 7