🐈

localhostにつなぐ - Flutter Android Emulator

に公開

問題

FlutterでAndroid Emulatorからlocalhostにつながらない。

W/WindowOnBackDispatcher(12642): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
I/flutter (12642): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (12642): │ #0   checkUserExist (package:whack_a_cat/services/user_id.dart:49:12)
user_id.dart:49
I/flutter (12642): │ #1   <asynchronous suspension>
I/flutter (12642): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
I/flutter (12642): │ ⛔ ClientException with SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 35200, uri=http://localhost:8787/api/users/5d8a878e-7c96-434b-9af2-4e22f696b367
I/flutter (12642): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

解決方法

  1. AndroidManifest.xmlを修正する
  2. localhostの代わりに 10.0.2.2:8787 を使う。

1. AndroidManifest.xml

  1. <uses-permission android:name="android.permission.INTERNET"/> タグを追加する
  2. android:usesCleartextTraffic="true" をapplicationタグに追加する
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 288a582..3541603 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -1,8 +1,11 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android">
+    <uses-permission android:name="android.permission.INTERNET"/>
     <application
         android:label="にゃんぽこぽん"
         android:name="${applicationName}"
-        android:icon="@mipmap/ic_launcher">
+        android:icon="@mipmap/ic_launcher"
+        android:usesCleartextTraffic="true"
+        >
         <activity
             android:name=".MainActivity"
             android:exported="true"

2. localhostの代わりに 10.0.2.2:8787 を使う。

-API_BASE_URL=http://localhost/api
+API_BASE_URL=http://10.0.2.2:8787/api

Discussion