Connecting to a Local API from a Physical Device
This guide explains how to connect the mobile client running on a physical device to an API server running on your local machine.
The localhost Challenge
Section titled “The localhost Challenge”When the API server runs locally, it is accessible at http://localhost:8080 on your computer. However, a physical mobile device connected to the same network cannot access your computer using the localhost address, as localhost refers to the device itself.
To resolve this, your local API server must be made accessible over the network. A tunneling service like ngrok can accomplish this by creating a secure public URL that forwards traffic to your local server.
Configuration Steps
Section titled “Configuration Steps”-
Start Your Local API Server
Ensure your API server is running locally on the designated port.
- See the API Server Local Setup Guide for instructions.
-
Install and Run ngrok
You will need to install
ngrokand use it to expose your local server’s port (e.g.,8080). For detailed instructions on installation and usage, please refer to the official documentation.- Official Guide: ngrok Documentation
Once installed, run the following command to expose your local server:
Terminal window ngrok http 8080ngrok will provide a public forwarding URL (e.g.,
https://....ngrok-free.app). -
Run the Application
Now, run the mobile client on your physical device. You must pass two
--dart-defineflags:APP_ENVIRONMENT=development: To tell the app to run in development mode.BASE_URL: Set this to the public forwarding URL provided by ngrok.
Your command will look like this:
Terminal window flutter run --dart-define=APP_ENVIRONMENT=development --dart-define=BASE_URL=https://<your-ngrok-url>.ngrok-free.appThe application will launch on your device and connect to your local API server through the ngrok tunnel.