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?

本文标签: