Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart getter中的未来对象_Dart_Flutter - Fatal编程技术网

Dart getter中的未来对象

Dart getter中的未来对象,dart,flutter,Dart,Flutter,我正在为我的语言环境变量调用getter中的future对象 如何让返回值等待它 class ChangeLocale with ChangeNotifier { Locale _locale; Locale get locale { getLanguage().then((Locale prefLocale) { _locale = prefLocale; }); return _locale; } set locale(Locale

我正在为我的语言环境变量调用getter中的future对象

如何让返回值等待它

class ChangeLocale with ChangeNotifier {

  Locale _locale;

  Locale get locale {
    getLanguage().then((Locale prefLocale) {
      _locale = prefLocale;
    });
    return _locale;
  }

  set locale(Locale newValue) {
    print(newValue);
    _locale = newValue;
    notifyListeners();
  }
}

返回
之前的值,然后执行
的回调,因此如果
\u locale
的初始值为
null
,则getter将返回
null

一旦
getLanguage()
Future
得到解决,
\u locale
值将被更新,但此时就太晚了

相反,您必须执行以下操作:

Locale\u Locale;
语言环境获取语言环境异步{
return _locale=wait getLanguage();
}
但我更愿意创建一个方法,让它清楚地表明您正在执行异步操作:

Future<Locale> fetchLocale() async {
  _locale = await getLanguage();
  return _locale;
}
Future fetchLocale()异步{
_locale=wait getLanguage();
返回语言环境;
}

谢谢您的回复。但是我该怎么处理getter呢?基本上,当我使用
locale:Provider.of(context.locale
在MaterialApp小部件中启动应用程序时,我想获取使用共享首选项保存的区域设置。如果您将其保存为共享首选项,为什么要使用Provider?为什么不直接从共享首选项获取区域设置?这样,当我在“设置”页面上切换语言时,应用程序可以直接应用更改。我现在有了一个有效的解决方案——完全不同的方法。但再次感谢:)