我想使用开关和复选框在我的应用程序中实现暗/亮模式。我使用下面的代码实现了暗/亮模式。但是它不能正常工作。我怎样才能成功做到这一点?以下代码有什么问题?请帮助我解决这个问题
import 'package:dynamic_theme/dynamic_theme.dart';
import 'package:dynamic_theme/theme_switcher_widgets.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DynamicTheme(
defaultBrightness: Brightness.light,
data: (brightness) => ThemeData(
primarySwatch: Colors.indigo,
brightness: brightness,
),
themedWidgetBuilder: (context, theme) {
return MaterialApp(
title: 'Flutter Demo',
theme: theme,
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
});
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Easy Theme"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
Checkbox(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
});
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: showChooser,
child: const Icon(Icons.add),
),
);
}
void showChooser() {
showDialog<void>(
context: context,
builder: (context) {
return BrightnessSwitcherDialog(
onSelectedTheme: (brightness) {
DynamicTheme.of(context).setBrightness(brightness);
},
);
});
}
bool isSwitched = true;
void changeBrightness() {
DynamicTheme.of(context).setBrightness(
Theme
.of(context)
.brightness == Brightness.dark
? Brightness.light
: Brightness.dark);
}
}
我使用了动态主题包来实现这一目标。它可以很好地与按钮配合使用,但是我不知道如何使用Switch / checkbox
来实现它