如何在Flutter Web中获取本地IP

3

我正在尝试在Flutter Web应用程序中获取本地IP地址。在搜索互联网时,我遇到了这个包:get_ip 0.4.0 - 它声称在Web下工作。

我有这个函数:

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");
  }

我在main.dartinitState方法中调用它。

控制台只输出了Test,没有输出IP或Exception

有人已经使用过这个包吗?是否有其他方法可以在web应用程序中获取本地IP?

(我正在使用MacOS)

2个回答

7

The get_ip package states that it supports Android/iOS. So,instead of using the package,you can directly interact with ipify endpoint. Check out their API documentation for more!

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;
  }
}


1
我正在使用ip_geolocation_api包获取IP地址,它正按预期工作。
  String text = '';
  GeolocationData geolocationData;

  @override
  void initState() {
    super.initState();
    this.getIp();
  }

  Future<void> getIp() async {
    geolocationData = await GeolocationAPI.getData();
    if (geolocationData != null) {
      setState(() {
        text = geolocationData.ip;
        print(text);
      });
    }
  }

现在,您在文本变量中拥有IP地址。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接