我正在尝试为我的 flutter 项目设置一个主题,如果您能告诉我另一种方法,我将不胜感激。
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:picpuzzle/routes/route_name.dart';
import 'package:picpuzzle/widgets/login/login_screen.dart';
import 'package:picpuzzle/widgets/main/main_page.dart';
import 'package:picpuzzle/widgets/puzzle/puzzle_list_page.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'common/constants.dart';
/// use for DarkMode,not sync with system
final DarkModeProvider = StateProvider((ref) => false);
class MyApp extends StatelessWidget {
// This widget is the root of your application.
static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
static FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
void initApp(BuildContext context) {}
@override
Widget build(BuildContext context) {
/// init
initApp(context);
return Consumer(
builder: (context, watch, _) {
return MaterialApp(
debugShowCheckedModeBanner: false,
localizationsDelegates: [
AppLocalizations.delegate, // Add this line
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''), // English, no country code
const Locale('ja', ''), // Japanese, no country code
],
title: 'Pic Puzzle',
initialRoute: RouteName.Login,
routes: {
RouteName.Login: (context) => LoginScreen(),
RouteName.Main: (context) => MainPage(),
RouteName.Home: (context) => PuzzleListPage(),
},
theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
// darkTheme: darkTheme,
);
},
);
}
}
但是因为这个,它无法做到这一点
lib/my_app.dart:49:23: Error: The method 'call' isn't defined for the class 'WidgetRef'. - 'WidgetRef' is from 'package:flutter_riverpod/src/consumer.dart' ('../Documents/flutter_windows_2.8.1-stable/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_riverpod-1.0.3/lib/src/consumer.dart'). Try correcting the name to the name of an existing method, or defining a method named 'call'. theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
最佳答案
这部分
theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
应该改为:
theme: watch.watch(DarkModeProvider.state).state ? darkTheme : lightTheme,
关于flutter - (watch)表达式没有计算出一个函数,所以它不能被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71049991/