Flutter - http.get fails on macos build target: Co

2020-08-24 17:47发布

问题:

I started porting my Flutter app to macos Desktop. The UI started fine. However, as soon as the app makes a network call, it fails instantly with Connection failed (OS Error: Operation not permitted).

Running a one-liner:

final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');

fails with:

Unhandled Exception: SocketException: Connection failed (OS Error: 
    Operation not permitted, errno = 1),
         address = jsonplaceholder.typicode.com, port = 443
#0      IOClient.send (package:http/src/io_client.dart:33:23)

The macos build target comes from Google's sample here.

Flutter (Channel master, v1.9.8-pre.108)

回答1:

Your macOS XCode project lacks Internet permission called "Outgoing Connections (Client)".

Open your macos xcode project - [root]/macos/Runner.xcworkspace

Click "Runner" in Project navigator - general settings will show up. Select "Capabilities" from tabbar and tick option "Outgoing Connections (Client)".

Rebuild your application inside XCode and launch the project.



回答2:

Per my comment on the other answer, you should not use the Xcode capabilities UI for this. It will not correctly handle the two separate entitlement files in a Flutter project.

You need to add:

<key>com.apple.security.network.client</key>
<true/>

to macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements.

This is documented here.