macosflutterhttpflutter-http

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


I have following code in my Flutter app where MyDataLoader is a widget which starts up from main.dart

Code:

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'),
    );
  }
}

Question:
Above code is inspired from https://flutter.dev/docs/cookbook/networking/fetch-data. I get the following error when MyDataLoader widget loads up:

[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

Above error is of course because of the following line of code called when my widget is loading.

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

But, if I open https://jsonplaceholder.typicode.com/albums/1 on my browser, I am able to to see that it has dummy json which I expect to receive in the response. This means I am well connected to internet.

I am running my app on macOS Big Sur version 11.1.

What am I doing wrong? Do I need to declare some permissions for my app to be able to access internet from a macOS environment?


Solution

  • macOS needs you to request a specific entitlement in order to access the network. To do that open macos/Runner/DebugProfile.entitlements and add the following key-value pair.

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

    Then do the same thing in macos/Runner/Release.entitlements.

    You need to stop and restart the app for the changes to take effect.

    See also Setting up entitlements in the documentation.