6
5

More than 1 year has passed since last update.

Flutter WebのdubugでApiを呼ぶとCORSでエラーになる対処法

Last updated at Posted at 2022-04-10

Flutter Webを開発しています。
開発PC上で他のWebApiを実行するとCORSでエラーになります。
その対処法を紹介します。

手順

(1) flutter_tools.stamp を削除

...\FlutterSDK\bin\cache
flutter_tools.stamp を削除します。
このファイルはビルドすると再作成されます。
'FlutterSDK' はプロジェクトが参照しているFlutterのSDKです。

(2) chrome.dart に --disable-web-security を追加

...\FlutterSDK\packages\flutter_tools\lib\src\web
chrome.dart を編集します。
--disable-extensions を削除
--disable-web-security を追加

193行目
  final int port = debugPort ?? await _operatingSystemUtils.findFreePort();
  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',
    '--bwsi',
    '--no-first-run',
    '--no-default-browser-check',
    '--disable-default-apps',
    '--disable-translate',

(3) 実行

flutter run -d chrome

実行すると localhost の chrome に以下のような警告が表示されました。

コマンドラインフラグ --disable-web-security を使用しています。これにより、安全性とセキュリティが損なわれます。

ポイント

  • FlutterSDK はFlutterのSDKの場所です。プロジェクトのことではありません。
  • 実行するのは flutter run -d chrome のままです。ここにオプションは不要です。

あとがき

Flutter Webは流行るのでしょうか。今回の記事のようにWebApiを使い出すと心配になってきました。GoogleはChromeも出していますし期待しています。
FlutterはアプリとウェブでUIが使いまわせるのが魅力ですよね。それほど流行ってないのがむしろ不思議です。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5