Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : Handling error Dio Package (404,400 etc)

Tags:

I'm learn searching data by ID with package DIO https://pub.dev/packages/dio, my problem is every time I'm type wrong keyword search, the app suddenly crash with debug message 404 Not Found.

enter image description here

I know data not found because I'm type wrong keyword, but I'm already handle this with this code

Widget _searchKeywordMahasiswa() {
    return FutureBuilder<List<Mosque>>(
      future: api.getMahasiswaById(_searchText),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          return Expanded(
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(snapshot.data[index].id);
              },
            ),
          );
        } else if (!snapshot.data) { <<<<<< IN THIS LINE
          return Center(
            child: Icon(
              Icons.sentiment_very_dissatisfied,
              size: 150.0,
            ),
          );
        }
        return CircularProgressIndicator();
      },
    );
    // return CircularProgressIndicator();
  }
Future<List<Mosque>> getMahasiswaById(String id) async{
    try {
      var apiRespon = await dio.get('${Urls.BASE_API_URL}/mahasiswa/get/id/$id');
      var apiResponJson = apiRespon.data;
      print(apiResponJson);
      return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();

    }on DioError catch (e) { <<<<< IN THIS LINE
      if(e.response.statusCode == 404){
        print(e.response.statusCode);
      }else{
        print(e.message);
        print(e.request);
      }
    }
  }

In same case my App crash too if i'm get error 400 Bad Request And i'm already handle this error but not works.

Can you Help Me With This?

like image 372
Zeffry Reynando Avatar asked Aug 12 '19 04:08

Zeffry Reynando


People also ask

How do you handle error response in Flutter?

Errors that don't occur within Flutter's callbacks can't be caught by the framework, but you can handle them by setting up a error handler on the PlatformDispatcher . All errors caught by Flutter are routed to the FlutterError. onError handler. By default, this calls FlutterError.

What is a Dio error?

DioError describes the error info when request failed.

What is Dio package in Flutter?

Dio package comes handy as it provides a powerful HTTP client for Dart and Flutter and it supports Interceptors, Global configuration, FormData, Request Cancellation, File Downloading, Timeout etc. Also less boilerplate leads to cleaner code.

Which is better Dio or HTTP in Flutter?

Flutter offers an http package that's nice for performing basic network tasks but is pretty daunting to use when handling some advanced features. By comparison, Dio provides an intuitive API for performing advanced network tasks with ease.


Video Answer


1 Answers

 var response = await dio.delete(
          url,
          data: postData,
          options: Options(
            followRedirects: false,
            validateStatus: (status) {
              return status < 500;
            },
            headers: headers,
          ),
        );

please use the code below bro,

add followRedirects, validateStatus to your code.

like image 150
Daanzel Avatar answered Oct 13 '22 17:10

Daanzel