我面临着一个关于 Provider 包的恼人问题。我想实现夜间模式切换。我尝试在单独的屏幕中使用提供程序并且它可以工作,但是在我需要他的地方,它却不起作用:)
我的主题课
class MyTheme {
static ThemeData lightTheme = ThemeData(
//something very nice
);
static ThemeData nightTheme = ThemeData(
//something very nice
);
}
我的根页面
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ThemeProvider(),
builder: (context, child) {
final provider = Provider.of<ThemeProvider>(context);
return MaterialApp(
debugShowCheckedModeBanner: true,
initialRoute: LoginScreen.id,
onGenerateRoute: RouteGenerator.generateRoute,
theme: provider.themeData,
home: const HomeScreen(),
);
});
}
}
我的主页(其中有用于更改模式的按钮)
class _HomeScreenState extends State<HomeScreen> {
final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
key: _globalKey,
drawer: MyAppDrawer(
height: height,
width: width,
colore: MyTheme.coloreTesto,
),
body:
MyAppDrawer 小部件
class MyAppDrawer extends StatelessWidget {
const MyAppDrawer(
{super.key,
required this.height,
required this.width,
required this.colore});
final double height;
final double width;
final Color colore;
@override
Widget build(BuildContext context) {
final provider = Provider.of<ThemeProvider>(context);
return Drawer(
width: width * 0.7,
child: Container(
padding: EdgeInsets.only(
top: height * 0.1, left: width * 0.08, right: width * 0.08),
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.symmetric(vertical: height * 0.01),
child: Row(
children: [
Container(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.white),
elevation: MaterialStateProperty.all(0.0),
padding: MaterialStateProperty.all(EdgeInsets.zero),
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(width * 0.015))))),
onPressed: () {
debugPrint('nightModePremuto');
provider.toggleTheme;
},
child: Icon(
size: width * 0.06,
Icons.dark_mode,
color: colore,
),
),
),
Text(
'Night Mode',
style: TextStyle(
color: colore,
fontSize: width * 0.04,
),
),
],
),
),
提供者类
class ThemeProvider extends ChangeNotifier {
ThemeData _themeData = MyTheme.lightTheme;
ThemeData get themeData => _themeData;
void toggleTheme() {
debugPrint('Siamo entrati nel toggle');
final isLight = _themeData == MyTheme.lightTheme;
isLight ? _themeData = MyTheme.nightTheme : _themeData = MyTheme.lightTheme;
notifyListeners();
}
}
我尝试过调试模式,发现它甚至没有进入toggleTheme()方法(Provider类中的方法)。我真的不知道为什么。
主要问题似乎在于
MyAppDrawer widget
,您引用该方法而不实际调用它provider.toggleTheme
,而应该是provider.toggleTheme();