abhipsa biswal
abhipsa biswal

Reputation: 155

SnackBar is not showing in flutter

AS I am new to flutter, I can't find why the SnackBar is not showing on my UI while I am calling different function for API call! In one case it is showing but not in other cases. I have to show a Snackbar on success of each API call (like in my project it is on success of generateOtp and on success of verifyOtp).

Below is my code.

snackbar.dart

showInSnackBar(String message, key){
  key.currentState.showSnackBar(
      SnackBar(
        content:Text(message),
        backgroundColor: Colors.blueAccent[700],
      )
  );
}

api_service.dart

class ApiService {
  bool isVerified = false;
  BaseOptions options = BaseOptions(
    baseUrl: "http://...",
  );

  generateOtp(String mobileNo, key) async {
    Dio dio = new Dio(options);
    FormData formData = FormData.fromMap({'mobile_no': mobileNo});
    try {
      Response response = await dio.post("generate_otp/", data: formData);
      if (response.statusCode == 200) {
       // on success of generate otp I have to show a message on SnackBar. But it is not working.
        showInSnackBar(response.data["msg"], key);
        print(response.data);
      }
    } on DioError catch (e) {
      showInSnackBar(e.message, key);
    }
  }

  Future<bool> verifyOtp(String mobileNo, String otp, key) async {
    Dio dio = new Dio(options);
    FormData formData = FormData.fromMap(
    //.....);
    try {
      Response response = await dio.post("verify_otp/", data: formData);
      if (response.statusCode == 200) {
       // here also it is not working.
        showInSnackBar(response.data["msg"], key);  
        // Otp verified
        isVerified = true;
      }
    } on DioError catch (e) {
      showInSnackBar(e.message, key);
    }
    return isVerified;
  }
}

register.dart

class _RegisterPageState extends State<RegisterPage> {
  var _key = new GlobalKey<ScaffoldState>();
  //...........
      service.generateOtp(_data.mobileNo, _key); /* here I am calling generateOtp() */
    } else {
      print('invalid credentials');
    }
  }

 @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _key,
        body: SingleChildScrollView(
         //..........

otp.dart

submit() async {
    _formKey.currentState.save();
    bool verify =
        await service.verifyOtp(widget.mobNumber, pinController.text, _key); /* here I am calling 
                                                                                  verifyOtp() */
    if (verify) {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      String userInfo = preferences.getString('user_data');
     // Decoding String data to map
      Map map = json.decode(userInfo);
      service.registerUser(map);
    } else {
      showInSnackBar('Invalid otp', _key); /* here SnackBar is showing on my UI*/
    }
  }

Can anybody please help me to solve this!

Upvotes: 0

Views: 2043

Answers (2)

Aashutosh Poudel
Aashutosh Poudel

Reputation: 110

If You want to use snackbar without context u can use this package get: ^3.13.2 and call snackbar like this any where you want:

 Get.snackbar(
            "title",
            "content",
          ); 

Upvotes: 0

Son Tran
Son Tran

Reputation: 122

Lack of context, (Context). docs : https://api.flutter.dev/flutter/widgets/BuildContext-class.html

try this(work for me):

void _showSnackBar(BuildContext context, String text) {
    Scaffold.of(context).showSnackBar(SnackBar(content: Text(text)));
  }

Upvotes: 1

Related Questions