Home > Net >  How to set Api response message like {Success or Not - message} in UI / Screen in flutter?
How to set Api response message like {Success or Not - message} in UI / Screen in flutter?

Time:09-17

I want to display message on screen or a snackbar or AlertDialog which get from api response.

So how to get API response message?

Here is my Function for Validate OTP as below in api_manager.dart file.

Now how can i pass the snackbar to my screen?

Future validateOtp(BuildContext context, String otp, LogedinUser? userData,
      UserPlan? userPlan) async {
    final String otpUrl = "$baseUrl/otp/validate";
    var formData = FormData.fromMap({
      'user_id': userData!.userId,
      'otp': otp,
      'device_id': userData.deviceId,
    });
    var response = await dio.post(otpUrl, data: formData);

    final validateOtpData = validateOtpFromJson(response.data);
    final status = validateOtpData.success;

    print(response.data);

    if (response.statusCode == 200) {
      var res = response.data;
      print(userData.userId);
      print(userData.deviceId);
      print(otp);
      print(res);
      if (status == 1) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DashBoard(
              user: userData,
              userPlan: userPlan,
            ),
          ),
        );
        return status;
      } else if (status == 0) {
        final apiMsg = validateOtpData.msg;
        final snackBar =
            SnackBar(content: Text(apiMsg!), backgroundColor: Colors.grey);
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }
    }
  }

Here is my OTP verifivation screen.

@override
  void initState() {
    super.initState();

    ApiManager().validateOtp(context, otp, userData, userPlan).then((apiMsg) {
      setState(() {
        //msg = apiMsg;
      });
    });
  }

 @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        OtpTextField(
          numberOfFields: 6,
          fieldWidth: 43,
          focusedBorderColor: Colors.black,
          onSubmit: (String otpValue) {
            setState(() {
              otp = otpValue;
            });
          },
        ),
        ElevatedButton(
          onPressed: () {
            ApiManager().validateOtp(context, otp, userData, userPlan);
          },
          child: Text("Verify"),
        )
      ],
    );
  }

Here is the response for invalid or expired OTP .

enter image description here

And this is valid OTP response.

enter image description here

Below is Validate OTP Model Class in validate_otp.dart file.

// To parse this JSON data, do
//
//     final validateOtp = validateOtpFromJson(jsonString);

import 'dart:convert';

ValidateOtp validateOtpFromJson(String str) =>
    ValidateOtp.fromJson(json.decode(str));

String validateOtpToJson(ValidateOtp data) => json.encode(data.toJson());

class ValidateOtp {
  ValidateOtp({
    required this.success,
    required this.msg,
  });

  int success;
  String? msg;

  factory ValidateOtp.fromJson(Map<String, dynamic> json) => ValidateOtp(
        success: json["success"] == null ? null : json["success"],
        msg: json["msg"] == null ? null : json["msg"],
      );

  Map<String, dynamic> toJson() => {
        // ignore: unnecessary_null_comparison
        "success": success == null ? null : success,
        "msg": msg == null ? null : msg,
      };
}

So when OTP is incorrect or expired i want to display OTP is either expired or not valid. response from api on Validate OTP Screen.

Thank you.

CodePudding user response:

The below snippet should help. It gives you a very basic idea of how to achieve your purpose.

N.B: Example is just an abstract explanation

   import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: OTP(),));
}

class OTP extends StatefulWidget {
  @override
  _OTPState createState() => _OTPState();
}

class _OTPState extends State<OTP> {
  String error = "";

  Future OtpValidation() async{
    error= "Error occured";
  }

  Future validateOtp() async {
   await OtpValidation(); //Do your Networking & logic
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: !error.isEmpty
          ? Text(error)
          : Column(
        children: [
          ElevatedButton(
            onPressed: () {validateOtp();},
            child: Text("Validate OTP"),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

Your model ValidateOtp exposes the data member msg which you can use to access the "msg" field from the received JSON.

Just do

var response = await dio.post(otpUrl, data: formData);
final validateOtpData = validateOtpFromJson(response.data);
final apiMsg = validateOtpData.msg;
final status = validateOtpData.success;

print(apiMsg!);

Just remember that validateOtpData.msg would be null in case of successful verification so you'd have to handle that case appropriately.

Now to show a snackbar on success or failure, you could do something like this

if(response.statusCode != 200){
    final snackbar = SnackBar(content: Text(apiMsg!), backgroundColor: Colors.red);
    ScaffoldMessenger.of(context).showSnackBar(snackbar);
}

For the context variable, you'd have to pass an additional BuildContext from the widget from which you are trying to show the snackbar. So change your function arguments to look something like

validateOtp(
      context, String otp, LogedinUser? userData, UserPlan? userPlan, BuildContext context)

And now pass the context as well when you try to call the function.

  • Related