Flutter/Dart - How to Solve CERTIFICATE_VERIFY_FAILED Error in Flutter (2023)

In app development. We need to implement API calling to store data in the backend, but sometimes we are using a local or live server for data storing during the API implementation or calling API  you may be seen this type of error CERTIFICATE_VERIFY_FAILED. So in this article, I am going to share How to Solve CERTIFICATE_VERIFY_FAILED Error in a flutter.

Error:

Unhandled Exception: HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: certificate has expired(handshake.cc:393))

 

Cause of Error:

We can consider many possibilities of this error  CERTIFICATE_VERIFY_FAILED like due to the certificate issue like the certificate expired of the server or service, maybe not installed certificate in the server, etc.

Solution:

I am sharing with you a simple solution to this error step by step.

The first step is to make a class ErrorGramHttpOverrides or whatever you want to give a name.

import 'dart:io';
class ErrorGramHttpOverrides extends HttpOverrides{
  @override
  HttpClient createHttpClient(SecurityContext? context){
    return super.createHttpClient(context)
      ..badCertificateCallback = ((X509Certificate cert, String host, int port) {
        final isValidHost = ["103.209.67.2"].contains(host); // Define your host
        return isValidHost;
      });
  }
}

 

The last step is to put the below piece of code inside the main()‚Äč function to apply it globally.

 

void main(){
WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  ErrorGramHttpOverrides.global = new ErrorGramHttpOverrides();//Add this line
  runApp(MyApp());
}

 

.Finally, restart your app and hit the API now it's working.

 

Conclusion:

We saw in this article How to Solve CERTIFICATE_VERIFY_FAILED Error in flutter step by step when we deal with the API. I hope this post may help you.

Tags: