SocketException: Connection failed (OS Error: Operation not permitted, errno = 1) with flutter app on macOS

SocketException: Connection failed (OS Error: Operation not permitted, errno = 1) with flutter app on macOS

我的 Flutter 应用程序中有以下代码,其中 MyDataLoader 是一个从 main.dart

启动的小部件

代码:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class MyDataLoader extends StatefulWidget {
  @override
  _MyDataLoaderState createState() => _MyDataLoaderState();
}

class _MyDataLoaderState extends State<MyDataLoader> {
  void getData() async {
    final response = await http.get('https://jsonplaceholder.typicode.com/albums/1');
    print(response);
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('MyDataLoader screen'),
    );
  }
}

问题:
以上代码的灵感来自 https://flutter.dev/docs/cookbook/networking/fetch-dataMyDataLoader 小部件加载时出现以下错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: SocketException: Connection failed (OS Error: Operation not permitted, errno = 1), address = jsonplaceholder.typicode.com, port = 443

以上错误当然是因为我的小部件加载时调用了以下代码行。

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

但是,如果我在我的浏览器上打开 https://jsonplaceholder.typicode.com/albums/1,我可以看到它有我希望收到的虚拟 json响应。这意味着我可以很好地连接到互联网。

我 运行 我的应用程序 macOS Big Sur 版本 11.1

我做错了什么?我是否需要声明一些权限让我的应用程序能够从 macOS 环境访问互联网?

macOS 需要您请求特定的授权才能访问网络。为此,请打开 macos/Runner/DebugProfile.entitlements 并添加以下键值对。

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

然后在macos/Runner/Release.entitlements.

中做同样的事情

您可以在 Desktop support for Flutter 文档中阅读更多相关信息。