【发布时间】:2022-01-20 02:58:07
【问题描述】:
我一直在 Dart 和 Flutter 中尝试使用 ValueNotifier 并遇到了一个有趣的问题。
我定义了两个自定义主题并尝试使用 ValueListenableBuilder 从应用程序的两个不同部分访问它们
我能够在App 组件内的Container 中正确获取主题数据。但是,它不适用于MaterialApp。请说明为什么会这样。
PS:我知道有更好的方法来管理主题,我只是在尝试。
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _themeManager = ThemeManager();
return ValueListenableBuilder<ThemeData>(
valueListenable: _themeManager.theme,
builder: (context, theme, child) {
return MaterialApp(
title: 'Flutter Demo',
// theme not updating ❌
theme: theme,
home: const App(),
);
});
}
}
class Theme {
static ThemeData primaryTheme =
ThemeData(primarySwatch: Colors.amber, primaryColor: Colors.amber);
static ThemeData secondaryTheme =
ThemeData(primarySwatch: Colors.blue, primaryColor: Colors.blue);
}
class ThemeManager {
final ValueNotifier<ThemeData> _theme =
ValueNotifier<ThemeData>(Theme.primaryTheme);
ValueNotifier<ThemeData> get theme => _theme;
void changeTheme(ThemeData theme) {
_theme.value = theme;
}
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _themeManager = ThemeManager();
return Scaffold(
appBar: AppBar(
title: const Text('App'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<ThemeData>(
valueListenable: _themeManager.theme,
builder: (context, theme, child) {
return Container(
height: 100,
width: 100,
// theme updating correctly ✔️
color: theme.primaryColor,
);
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_themeManager.theme.value =
_themeManager.theme.value == Theme.primaryTheme
? Theme.secondaryTheme
: Theme.primaryTheme;
},
child: const Text('Toggle Theme')),
],
),
),
);
}
}
【问题讨论】: