エラーが出たコード
try {
final res = await http.get(Uri.parse('https://xxx.com/xxx'));
} on Exception catch (e) {
print('${e.toString()}'); ←XMLHttpRequest error.
}
Flutter Webで他のWebApiを実行するとエラーになります。原因はCORSです。
解決方法
とりあえずlocalhostでデバッグするには次の方法で解決します。
(1) FlutterのSDK(3.16.9とか)\bin\cache\flutter_tools.stamp
flutter_tools.stamp を削除します。
このファイルは削除してもビルドすると再作成されます。
(2) FlutterのSDK(3.16.9とか)\packages\flutter_tools\lib\src\web\chrome.dart
--disable-extensions の下に --disable-web-security を追加します。
200行目
final List<String> args = <String>[
chromeExecutable,
// Using a tmp directory ensures that a new instance of chrome launches
// allowing for the remote debug port to be enabled.
'--user-data-dir=${userDataDir.path}',
'--remote-debugging-port=$port',
// When the DevTools has focus we don't want to slow down the application.
'--disable-background-timer-throttling',
// Since we are using a temp profile, disable features that slow the
// Chrome launch.
'--disable-extensions',
'--disable-web-security', ←追加
'--disable-popup-blocking',
Flutter Web を流行らせよう
余談ですがFlutter Webって全然流行らないですね。スマホアプリの方は徐々に浸透しているように思えます。
メリット① androidとiosの両対応
一番の理由がこれです。特にUIの開発が一緒なのが大きいです。
両方開発できるのは、
Flutter
ReactNative
Unity
Xamarin
Kotlin,Swiftの人はFlutter。Webからの人はReactNativeが多い気がします。
スマホアプリを開発したい人はFlutterをお勧めします。KotlinやSwiftも必要になるのですが、まずはFlutterだけでリリースまでやってみるのがいいと思います。
メリット② Google が出している
会社 | OS | 環境 |
---|---|---|
android/chrome | Flutter/dart | |
Apple | ios/mac | Xcode/swift |
Microsoft | Windows | VisualStudio/C# |
Xcode/swift も VisualStudio/C# もずっとサポートが続いています。そのため Flutter もサポートが続くのではないかと期待できます。
メリット③ ネイティブとウェブの両方が開発可能
ネイティブがメインでWebはおまけの場合は効果ありです。毎日使う業務アプリで速さが求められる場合はスマホアプリがよいです。FlutterならあとからWebにも対応できます。
デメリット ウェブが遅い
まず初回のロードが遅いです。これが解決するなら一気に普及すると思います。バックエンドに関してはどのみち別環境+別言語になるので問題にはならないでしょう。