Flutter change theme and icon of a iconbutton with Getx

Issue

I have the following example to change from dark to light mode using Getx. So far it is working. But i would also that the IconButton who change the Theme, would also change is own icon.
What im doing wrong?

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Change Theme',
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.system,
      home: HomeScreen(),
    );
  }
}

// Home Screen
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
      var selected = true;
    return Scaffold(
      appBar: AppBar(
        title: Text('Change Theme'),
        actions: [
          IconButton(
              icon: Icon(
                selected ? Icons.dark_mode : Icons.light_mode,
              ),
              onPressed: () {
                Get.isDarkMode
                    ? Get.changeTheme(ThemeData.light())
                    : Get.changeTheme(ThemeData.dark());
              })
        ],
      ),
    );
  }
}


Solution

You need to wrap the icon in a GetX widget that rebuilds based on a variable that lives in a GetX class.

Create a Getx class with a function that changes the theme based on the value of the local boolean.

class ThemeController extends GetxController {

bool isDarkMode = true; 

void toggleDarkMode() {
  isDarkMode = !isDarkMode;
  if (isDarkMode) {
   Get.changeTheme(ThemeData.dark());
  } else {
   Get.changeTheme(ThemeData.light());
  }
  update();
}

Then wrap your icon in a GetBuilder<ThemeController>

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Get.put(ThemeController());
    return Scaffold(
      appBar: AppBar(
        title: Text('Change Theme'),
        actions: [
         GetBuilder<ThemeController>(
          builder: (controller) =>  IconButton(
              icon: Icon(
                controller.isDarkMode ? Icons.dark_mode : Icons.light_mode,
              ),
           onPressed: () => controller.toggleDarkMode()
          
        ],
      ),
    );
  }
}

My VsCode is outta commission because I’m traveling with painfully slow internet and I’m in the middle of a multi hour flutter upgrade. So there might be some syntax or minor formatting errors but besides that this should work.

Answered By – Loren.A

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *