When working with Flutter and Django you will often need to test your app with a local server before shipping it to production, this seems like a simple task but it can be tricky to make it work with simulators.

In this article, I will show you how to use your Django local server for Flutter and how to make it work with simulators in IOS and Android.

The problem

When you are working with Flutter and you want to use your Django local server, you will often use localhost or 127.0.0.1 as the URL of your server, both of these URLs are pointing to your local machine and are the default.

Now let’s fire up a local server with Django.

python manage.py runserver

Let’s try to access it from our Flutter app, I assume you already have a Flutter app ready to go.

If I try to access my Django local server from my Flutter app, using an IOS simulator, I will get the following error:

I/flutter (  777): SocketException: OS Error: Connection refused, errno = 61, address =

Not very helpful… so let’s try to fix it.

The solution

When using Django the default hostname is usually http://127.0.0.1:8000/ or http://localhost:8000/, but when you are using a simulator it runs in a separate environment from your host machine and has its own network stack, so it can’t access your local server.

Solution 1

The first solution is to use your local IP address instead of localhost, you can find your local IP address by running the following command on MacOS:

ipconfig getifaddr en0

And replace localhost with your local IP address in your Flutter app (the port remains the same).

Solution 2

Alternatively you can use http://0.0.0.0:8000/ to make your local server accessible from any device on your network, including the iOS simulator.

How to make it work with MacOS

If you are using MacOS the solutions above will work for you, but you will also need to add the required entitlements to your app.

Step 1

Open your macos/Runner/DebugProfile.entitlements file in Xcode.

Step 2

Add the following lines to your ios/Runner/Info.plist file:

<key>com.apple.security.network.client</key>
<true/>

Step 3

Repeat the same steps for the macos/Runner/Release.entitlements file.

How to make it work with Android

If you are using Android you will need to add the following lines to your android/app/src/main/AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>

Conclusion

In this article, I showed you how to use your Django local server for Flutter and how to make it work with simulators in IOS and Android.


I hope this article was helpful, if you have any question or suggestion, feel free to reach out to me on :

You can use my articles with no cost or attribution, feel free to edit them and make them your own.