Home > database >  How can i change theme of my widget in this situation?
How can i change theme of my widget in this situation?

Time:05-17

Im not sure that my code is correct for using themes and easylocalization together and im open for any help too, but my main goal is creating a custom navigation bar inside of MyApp. When i do it like example down below, i cant change my NavBarItem theme with my theme provider because of its outside of MaterialApp. How can i handle this situation ?

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  runApp(EasyLocalization(
      supportedLocales: [
        Locale('en'),
        Locale('tr'),
      ],
      path: 'assets/translations',
      saveLocale: true,
      fallbackLocale: Locale('en'),
      child: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CustomThemeData(),
      builder: (context, _) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,

          localizationsDelegates: context.localizationDelegates,
          supportedLocales: context.supportedLocales,
          locale: context.locale,
          theme: Provider.of<CustomThemeData>(context).getThemeData,
          home: Scaffold(
            body: _ActivePage,
            bottomNavigationBar: Container(child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  NavBarItem(),
                  NavBarItem(),
                  NavBarItem(),
                ],
              ),),
          ),
          //
        );
      },
    );
  }

  Widget NavBarItem(){}
}

CodePudding user response:

You can try this below codebase, I think you will get your solution.

main.dart

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:theme_changer/custom_theme_data.dart';

final callMenuTheme = ThemeData(
  primarySwatch: Colors.orange,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.orange),
  iconTheme: const IconThemeData(
    color: Colors.orange,
  ),
);

final cameraMenuTheme = ThemeData(
  primarySwatch: Colors.red,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.red),
  iconTheme: const IconThemeData(
    color: Colors.red,
  ),
);

final chatMenuTheme = ThemeData(
  primarySwatch: Colors.green,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.green),
  iconTheme: const IconThemeData(
    color: Colors.green,
  ),
);

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  runApp(EasyLocalization(
      supportedLocales: const [
        Locale('en'),
        Locale('tr'),
      ],
      path: 'assets/translations',
      saveLocale: true,
      fallbackLocale: const Locale('en'),
      child: ChangeNotifierProvider(
        create: (context) => CustomThemeData(0, callMenuTheme),
        builder: (context, _) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            localizationsDelegates: context.localizationDelegates,
            supportedLocales: context.supportedLocales,
            locale: context.locale,
            theme: Provider.of<CustomThemeData>(context).getThemeData(),
            home: const MyApp(),
            //
          );
        },
      )));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {

    var themeNotifier = Provider.of<CustomThemeData>(context,listen: false);

    List<Widget> _pages = <Widget>[
      const Icon(
        Icons.call,
        size: 150,
      ),
      const Icon(
        Icons.camera,
        size: 150,
      ),
      const Icon(
        Icons.chat,
        size: 150,
      ),
    ];


    void _onItemTapped(int index) async{
      setState(() {
        switch(index) {
          case 0:
            {
              themeNotifier.setNavigationIndexData(0);
              themeNotifier.setThemeData(callMenuTheme);
            }
            break;

          case 1:
            {
              themeNotifier.setNavigationIndexData(1);
              themeNotifier.setThemeData(cameraMenuTheme);
            }
            break;

          case 2:
            {
              themeNotifier.setNavigationIndexData(2);
              themeNotifier.setThemeData(chatMenuTheme);
            }
            break;

          default:
            {
              themeNotifier.setNavigationIndexData(0);
              themeNotifier.setThemeData(callMenuTheme);
            }
            break;
        }
      });
    }

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      theme: themeNotifier.getThemeData(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('BottomNavigationBar Demo'),
        ),
        body: Center(
          child: _pages.elementAt(themeNotifier.getNavigationIndexData()),
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.call),
              label: 'Calls',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.camera),
              label: 'Camera',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.chat),
              label: 'Chats',
            ),
          ],
          currentIndex: themeNotifier.getNavigationIndexData(),
          onTap: _onItemTapped,
        ),
      ),

    );

  }
}

custom_theme_data.dart

import 'package:flutter/material.dart';

class CustomThemeData with ChangeNotifier {
  ThemeData? _themeData;
  int? _navigationIndex;

  CustomThemeData(this._navigationIndex, this._themeData);

  getNavigationIndexData() => _navigationIndex;

  setNavigationIndexData(int navigationIndex) async {
    _navigationIndex = navigationIndex;
    notifyListeners();
  }

  getThemeData() => _themeData;

  setThemeData(ThemeData themeData) async {
    _themeData = themeData;
    notifyListeners();
  }
}

If you need a better idea about the project, here is the GitHub link to this project. Also, you will check the screenshots(1,2,3) of this project.

  • Related