helmut1978
helmut1978

Reputation: 437

How to get local IP in Flutter Web

I'm trying to get the local IP address in a Flutter Web app. Searching the internet I came around this package: get_ip 0.4.0 - it states it is working under web.

I have this function:

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

and I call it in initState of main.dart.

The console just has the output Test, it does not output the IP or Exception.

Has someone already used this package? Would there be an other way for a web app to get the local IP?

(I'm using MacOS)

Upvotes: 4

Views: 6758

Answers (2)

Shailendra Rajput
Shailendra Rajput

Reputation: 2879

I'm Using ip_geolocation_api Package for getting an IP address and it is working as expected

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

Now You have IP in the text Variable.

Upvotes: 1

vasanth kumar
vasanth kumar

Reputation: 272

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

Upvotes: 8

Related Questions