我需要根据用户偏好创建深色或浅色主题,但错误“无法将参数类型‘Future Function()’分配给参数类型‘ThemeMode’。” 发生。
代码是:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return NeumorphicApp(
themeMode:getThemeTypeFromSharedPreferencess ,
),
}}
作用是:
Future<ThemeMode> getThemeTypeFromSharedPreferencess()async{
if( await getThemeType.call() ==false){
return ThemeMode.light;
}else{
return ThemeMode.dark;
}
}
答案 0 :(得分:2)
或者你可以在你的 void main 中执行这个异步代码,如下所示:-
void main()async{
ThemeMode mode;
WidgetsFlutterBinding.ensureInitialized();
if( await getThemeType.call() ==false){
mode=ThemeMode.light;
}else{
mode=ThemeMode.dark;
}
runApp(MyApp(mode));//pass the mode to MyApp and then use it to show the theme
}
class MyApp extends StatelessWidget {
final ThemeMode mode;
MyApp(this.mode);
@override
Widget build(BuildContext context) {
return NeumorphicApp(
themeMode:mode,
),
}}
答案 1 :(得分:0)
发生这种情况是因为您的 getThemeTypeFromSharedPreferencess
函数返回一个 Future
,而 themeMode
需要 ThemeMode
而不是 Future
的 ThemeMode
。要解决此问题,您可以使用 FutureBuilder 并显示一个例如CircularProgressIndicator 直到 Future
返回 themeMode
,然后您可以在 NeumorphicApp
中设置它。