问题描述
Dart?flutter似乎不允许在创建DateTime对象时指定时区(例如:澳大利亚/悉尼或美国/底特律)。要么使用本地时区,要么可以指定UT。
Dart?flutter does not appear to allow a timezone (eg: "Australia/Sydney" or "America/Detroit") to be specified when creating a DateTime object. Either the local timezone will be used, or UT may be specified.
有人知道解决方法吗?
有Dart包TimeZone,但在flutter应用程序中似乎无法使用。
There's the Dart package TimeZone, but it appears to be unusable within a flutter app.
请参见作为我要引用的软件包。
See https://pub.dartlang.org/packages/timezone for the package I'm referring to.
编辑:时区包确实在Flutter中工作,并进行了一些设置。
The timezone package does work in Flutter, with some setup. See Richard Heap's answer below.
推荐答案
要获得 package:timezone,您必须做一点魔术
可以工作。
提取所需的任何数据文件(共有3个:默认,全部和2010-2020年)并将其移至您的颤动资产文件夹。 (我使用 2018c_2010-2020.tzf
,可在分支机构中使用。)
Extract whichever data file you need (there are 3: default, all and 2010-2020) and move it to your flutter assets folder. (I use 2018c_2010-2020.tzf
, which is available in a branch.)
将其添加为资产在 pubspec.yaml
中:
assets:
- assets/2018c_2010-2020.tzf
然后在启动时加载该文件(例如从顶级StatefulWidget的> initState
并使用它来初始化数据库。
Then load that file on startup (e.g. from the initState
of a top level StatefulWidget) and use it to initialise the database.
ByteData tzf = await rootBundle.load('assets/2018c_2010-2020.tzf');
initializeDatabase(tzf.buffer.asUint8List());
...
Location newYork = getLocation('US/Eastern');
我没有尝试过,但是您甚至可以从 main ,如果您将其标记为异步。
I haven't tried, but you may even be able to load it from main
if you mark it async.
我还注意到我必须克隆了最新的分支,正如我在pubspec中看到的那样
I also notice that I must have cloned the latest branch, as I see this in my pubspec
timezone:
path: ../../dart/source/timezone
...但是看起来您只需要从酒吧获取0.5.0-dev-2
... but looks like you just need to grab 0.5.0-dev-2 from pub
dependencies:
timezone: "^0.5.0-dev-2"
这篇关于在Dart / Flutter中创建DateTime对象时如何指定TimeZone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!