【问题标题】:World time in flutter颤动的世界时间
【发布时间】:2020-09-03 07:53:08
【问题描述】:

我正在尝试构建一个具有不同国家时区的世界应用程序。我可以使用 api 获取时间,但是当调用 api 时,会显示该特定实例的时间,并且不会每分钟更新一次。有什么特别的方法可以实现吗?

  void getTime() async{
    Response response =
    await get('http://worldtimeapi.org/api/timezone/Australia/Sydney');
    Map dataAus = jsonDecode(response.body);
    String dateTimeAus = dataAus['datetime'];
    String offsetAus = dataAus['utc_offset'].substring(1, 3);
    DateTime nowAus = DateTime.parse(dateTimeAus);
    nowAus = nowAus.add(Duration(hours: int.parse(offsetAus)));
  }

【问题讨论】:

  • 不能使用带 intl 的语言环境?而不是 API 调用?
  • 是否也可以获取其他国家的时间?使用国际?
  • 我猜是这样,可能使用 Locale

标签: api flutter dart


【解决方案1】:

我想出了解决方案,无论如何我的工作已经完成,可能还有许多其他有效的方法。使用 Timer 每秒调用一次 api。

getTime(String country, continent) async {
    Response response =
        await get('http://worldtimeapi.org/api/timezone/$continent/$country');
    Map data = jsonDecode(response.body);
    String dateTime = data['datetime'];
    String offset = data['utc_offset'].substring(1, 3);
    DateTime time = DateTime.parse(dateTime);
    time = time.add(Duration(hours: int.parse(offset)));
    final timeStr = DateFormat('hh : mm a').format(time);
    return timeStr.substring(0, 10);
  }

  Timer timer;

  @override
  void initState() {
    super.initState();
    setState(() {
      Timer(
        Duration(seconds: 1) - Duration(milliseconds: _localDateTime.second),
        _updateTime,
      );
    });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2021-07-12
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多