Home > Mobile >  How to print error message from Backend in Flutter
How to print error message from Backend in Flutter

Time:05-28

Error message from backend appears in flutter terminal. How can I print this on the app?

I/flutter (16113): {"status":"Fail","error":{"code":1138,"message":"Kullanıcı zaten mevcut"}}

Service

class RegisterService extends ChangeNotifier {
  bool isBack = false;

  Future<RegisterResModel> register(RegisterReqModel data) async {
    final http.Response response = await http.post(
        Uri.parse("http://192.168.0.16:2526/api/v1/auths/register"),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(data.toJson()));

    if (response.statusCode == 200) {
      isBack = true;
      print(response.body);

      return RegisterResModel.fromJson(json.decode(response.body));
    } else {
      isBack = false;

      throw Exception(response.body);
    }
  }
}

Res Model

class RegisterResModel {
  String? message;
  String? status;

  RegisterResModel({this.message, this.status});

  RegisterResModel.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    status = json['status'];
  }

  Map<String, dynamic> toJson(decode) {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['message'] = message;
    data['status'] = status;
    return data;
  }
}

CodePudding user response:

You can wrap your main code in try catch block and incase it shows an exception/error, you can show a toast or snackBar to show the message.

Learn more about-

CodePudding user response:

You could use an Alert Dialog to ensure that the error is seen and acknowledged for whatever reason you're doing this.

CodePudding user response:

You need to add one class to store the error details.

class ErrorModel{
  String? message;
  int? code;

  ErrorModel({this.message, this.code});
  ErrorModel.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    code = json['code'];
  }

  Map<String, dynamic> toJson(decode) {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['message'] = message;
    data['code'] = code;
    return data;
  }
}

You can add this model to your own Register class.

class RegisterResModel {
  String? message;
  String? status;
  ErrorModel? error;

  RegisterResModel({this.message, this.status, this.error});

  fromJson(Map<String, dynamic> json) {
    message = json['message'];
    status = json['status'];
    error = ErrorModel.fromJson(json['error']);
  }

  Map<String, dynamic> toJson(decode) {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['message'] = message;
    data['status'] = status;
    return data;
  }
}

similar to you have parse the response, you can now get the error information as well. Please check sample code as below.

class RegisterService extends ChangeNotifier {
  bool isBack = false;

  Future<RegisterResModel> register(RegisterReqModel data) async {
    final http.Response response = await http.post(
        Uri.parse("http://192.168.0.16:2526/api/v1/auths/register"),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(data.toJson()));

    if (response.statusCode == 200) {
      isBack = true;
      print(response.body);

      return RegisterResModel.fromJson(json.decode(response.body));
    } else {
      isBack = false;

      return RegisterResModel.fromJson(json.decode(response.body));
    }
  }
}

Now you can return register class and check for status fail or pass based on the response and show the error.

To show the error, there are multiple options like Show Alert dialog, Show snackbar. Those are listed as below

Alert dialog:

showAlertDialog(BuildContext context) {

  // set up the button
  Widget okButton = TextButton(
    child: Text("OK"),
    onPressed: () { },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("My title"),
    content: Text("This is my message."),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Snackbar :

import 'package:flutter/material.dart';

void main() => runApp(const SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  const SnackBarDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SnackBar Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('SnackBar Demo'),
        ),
        body: const SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  const SnackBarPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: const Text('Yay! A SnackBar!'),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // Some code to undo the change.
              },
            ),
          );

          // Find the ScaffoldMessenger in the widget tree
          // and use it to show a SnackBar.
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
        },
        child: const Text('Show SnackBar'),
      ),
    );
  }
}
  • Related