Muhammet Aydın
2 min readApr 28, 2024

--

Fixing Flutter App’s Connection in Physical Device Issue with Local Backend

If you’re developing a Flutter application that connects to a local backend using a physical Android device and encounter the following error

SocketException (SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 54126)

Here’s a step-by-step guide to resolve this issue:

Problem Description

When attempting to connect your Flutter app running on a physical Android device to a local backend server, you receive a “Connection refused” error. This error typically occurs because the app is trying to connect to the localhost of the device itself (127.0.0.1), which is not where your backend server is hosted.

Solution Steps

  1. Identify your Local IP Address:
  • Open Command Prompt (Windows) or Terminal (Mac/Linux).
  • Type ipconfig (Windows) or ifconfig (Mac/Linux) and press Enter.
  • Look for your network adapter (e.g., Ethernet or Wi-Fi) and find the IPv4 Address. It should look something like 192.168.X.X or 10.X.X.X.
  1. Update Flutter App’s Base URL:
  • Open your Flutter project in your preferred code editor.
  • Locate the file where you define your backend’s base URL (e.g., api_service.dart).
  • Update the base URL to use your local IP address instead of 127.0.0.1 or localhost. For example:
  • final String baseUrl = 'http://192.168.X.X:PORT'; // Replace PORT with your backend's port number

ipv4 address

  1. Test the Connection:
  • Save your changes and run your Flutter app on your physical Android device.
  • Ensure that your local backend server is also running.
  • The app should now successfully connect to your local backend without the “Connection refused” error.

Additional Notes

  • Firewall Settings: If you still encounter connection issues, ensure that your firewall or antivirus software is not blocking the connection to the specified IP address and port.
  • Dynamic IP: If your local IP address changes frequently (e.g., dynamic IP assignment from your router), you may need to update the base URL in your app accordingly.

By following these steps, you should be able to resolve the “Connection refused” error and establish a successful connection between your Flutter app and local backend server.

Happy coding! 🚀

--

--