admin管理员组文章数量:1356784
Here is my code. Although I use BLoC
for state management (the same applies to GetX
), when I press the button (Change ThemeMode
), I find that the console prints multiple times:
flutter: >>>>> call build <<<<<<
If I remove the following code, it works perfectly:
Theme.of(context);
My code:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ThemeCubit extends Cubit<ThemeMode> {
ThemeCubit() : super(ThemeMode.light);
void toggleTheme() {
emit(state == ThemeMode.light ? ThemeMode.dark : ThemeMode.light);
}
}
void main() async {
runApp(BlocProvider(create: (_) => ThemeCubit(), child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<ThemeCubit, ThemeMode>(
builder: (context, themeMode) {
return MaterialApp(
home: const MyHomePage(),
themeMode: themeMode,
darkTheme: ThemeData(
brightness: Brightness.dark,
visualDensity: VisualDensity.standard,
),
theme: ThemeData(
visualDensity: VisualDensity.standard,
),
);
},
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
debugPrint(">>>>> call build <<<<<<");
return Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
// only calling Theme.of(context) will trigger multiple builds when changing the ThemeMode.
Theme.of(context);
context.read<ThemeCubit>().toggleTheme();
},
child: const Text("Change ThemeMode"),
),
],
),
);
}
}
Run result:
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
flutter: >>>>> call build <<<<<<
Does anyone know how to avoid multiple builds being called in the scenario above?
本文标签:
版权声明:本文标题:When updating the ThemeMode in a Flutter app, the build method of the Homepage is called multiple times - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744046247a2581577.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论