如何在Android上获取IP地址?

发布于 2025-01-22 01:48:34 字数 1293 浏览 3 评论 0原文

我正在尝试获取IP地址以显示,但我的IP地址却无效。 当我模拟它时,这也有效,但是当我在Android设备上尝试它时,这也不行。 这里有什么问题? 任何帮助将不胜感激! 这是我的代码:

[import 'package:bottom_navigation_test/sidemenu.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as https;
import 'widget/info_widget.dart';

class MyIP extends StatefulWidget {
  @override
  _MyIP createState() => _MyIP();
}

class _MyIP extends State<MyIP> {
  Map<String, dynamic> map = {};

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

  Future init() async {
    final ipAddress = await MyIPInfo.getIPAddress();

    if (!mounted) return;
    setState(() => map = {
          'IP Address:': ipAddress,
        });
  }

  Widget build(BuildContext context) => Scaffold(
        drawer: SideMenu(),
        appBar: AppBar(
          backgroundColor: const Color.fromARGB(255, 89, 137, 199),
          title: const Text('My IP'),
        ),
        body: InfoWidget(map: map),
      );
}

class MyIPInfo {
  static Future<String?> getIPAddress() async {
    try {
      final url = Uri.parse('https://api.ipify.org');
      final response = await https.get(url);

      return response.statusCode == 200 ? response.body : null;
    } catch (e) {
      return null;
    }
  }
}][1]

I am trying to get the IP Address to show but I am getting null.
Also this works when I simulate it, but not when I am trying it on an android device.
What could be the issue here?
Any help would be appreciated!
Here is my code:

[import 'package:bottom_navigation_test/sidemenu.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as https;
import 'widget/info_widget.dart';

class MyIP extends StatefulWidget {
  @override
  _MyIP createState() => _MyIP();
}

class _MyIP extends State<MyIP> {
  Map<String, dynamic> map = {};

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

  Future init() async {
    final ipAddress = await MyIPInfo.getIPAddress();

    if (!mounted) return;
    setState(() => map = {
          'IP Address:': ipAddress,
        });
  }

  Widget build(BuildContext context) => Scaffold(
        drawer: SideMenu(),
        appBar: AppBar(
          backgroundColor: const Color.fromARGB(255, 89, 137, 199),
          title: const Text('My IP'),
        ),
        body: InfoWidget(map: map),
      );
}

class MyIPInfo {
  static Future<String?> getIPAddress() async {
    try {
      final url = Uri.parse('https://api.ipify.org');
      final response = await https.get(url);

      return response.statusCode == 200 ? response.body : null;
    } catch (e) {
      return null;
    }
  }
}][1]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文