Reaching a Local API From Flutter
When doing full-stack development, most times you'll be working with a front end client and some sort of API that the client will consume. For web development, this usually isn't a problem since your API runs on one port and the client is on another - everything can still talk.
When doing full-stack development, most times you'll be working with a front end client and some sort of API that the client will consume. For web development, this usually isn't a problem since your API runs on one port and the client is on another - everything can still talk.
Lately though, I've been getting into a bit more mobile development and was wondering why my Flutter app couldn't reach the API that was running on the same machine. Then it dawned on me that android was running in an emulator, so trying to reach the API running on "localhost" wouldn't quite work.
Resolving this is easy enough with a tool like ngrok, which lets you expose a local port to the internet. After that, rather than using "localhost" from the flutter app, you can point to the ngrok url and everything starts working again. Check out the steps below:
- Create an ngrok account and download the executable
- Add your authentication token to the ngrok config
ngrok config add-authtoken <TOKEN>
3. Create a tunnel for your local API
ngrok http --host-header=rewrite --scheme=https https://localhost:<PORT>
4. Update the api service in the flutter app to use the ngrok-generated URL
https://<IDENTIFIER>.ngrok-free.app
While this works well enough and is easy to do, there are a couple things that I don't care for:
- You have to expose a port and send traffic through the internet
- Every time you start development you have to perform steps 3 and 4
Have you addressed the issue differently? I'd love to know in the comments!