Connecting Flutter app with Node js localhost sever
Connecting flutter application a node js localhost server running locally on your machine or someone else's can really be such a big pain in the ass. It is really so frustrating and stressful and you will often run into different kinds of errors which the shows something like this:
Unhandled Exception: ClientException with SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 34954, uri=localhost:4000/api/v1/users/register
Here are the list of steps that assisted me in resolving the issue :
In your flutter file the url endpoint string must be running on port 10.0.2.2 instead of localhost or 127.0.0.1:
const String apiUrl = 'http://10.0.2.2:4000/api/v1/users/register';
And in your node js where the server is running your app should listen on the port number 127.0.0.1 instead of l**ocalhost
app.listen(PORT, "127.0.0.1", () => { console.log(`Server running on port ${PORT}`); });
Lastly in your androidManifest.xml file under the app>src>main folder in the flutter file you need to set the network permission and also set the android:usesCleartextTraffic="true" and android:networkSecurityConfig="@xml/network_security_config".
<uses-permission android:name="android.permission.INTERNET" /> <application android:label="your_application_label" android:name="${applicationName}" android:icon="@mipmap/ic_launcher" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config" >
I hope this solves the issue for others who encounter this type of error.