Flutter Web中如何获取本地IP

hel*_*978 3 ip-address flutter flutter-web

我正在尝试在 Flutter Web 应用程序中获取本地 IP 地址。在互联网上搜索我发现了这个包:get_ip0.4.0 - 它声明它在网络下工作。

我有这个功能:

Future<void> initPlatformState() async {
    print("Test");
    String ipAddress;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      ipAddress = await GetIp.ipAddress;
    } on PlatformException {
      ipAddress = 'Failed to get ipAddress.';
    } on Exception {
      print("Exception");
    }

    print("Ip: $ipAddress");
  }
Run Code Online (Sandbox Code Playgroud)

我把它initState称为main.dart

控制台只有输出Test,不输出IP或Exception.

有人已经用过这个包了吗?Web 应用程序是否有其他方式获取本地 IP?

(我使用的是MacOS)

vas*_*mar 7

get_ip声明它支持 Android/iOS。因此,您可以直接与ipify端点交互,而不是使用该包。查看他们的 API 文档了解更多信息!

Future<String> getIP() async {
  try {
    const url = 'https://api.ipify.org';
    var response = await http.get(url);
    if (response.statusCode == 200) { 
      print(response.body);
      return response.body;
    } else {
      print(response.body);
      return null;
    }
  } catch (exception) {
    print(exception);
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)