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!
SnackBaralso when the status code is not 200?if (response.statusCode == 200) {...}, add anelseblock that callsshowInSnackBar('some text', _key);SnackBarshow?