如何在Dart中获取主机名?

450 阅读1分钟

有时,我们需要在dart和flutter应用程序中获得当前环境中正在运行的应用程序的主机名。

这篇文章展示了在dart和flutter项目中获得主机名的多种方法。

dart:io 包提供了平台类,它提供了一个运行环境的信息。

平台类有一个静态方法localHostname ,返回系统的主机名。

static String get localHostname => _localHostname;

下面是一个在dart中获取主机名的示例程序

import 'dart:io' show Platform, stdout;

void main() {
  final hostname = Platform.localHostname; // returns hostname as string
  print(hostname);
}

输出

localhost

dart:html 软件包提供了html窗口类,其中包含主机名属性 ,返回运行机器的主机名。html.window.location.hostname

import 'dart:html' as html;

void main() {
  final hostname = html.window.location.hostname;

  print(hostname);
}

输出

localhost

结论

学习了如何在dart和flutter应用程序中获得运行中的应用程序的主机名