Flutter - Changing theme color (primarySwatch) using Provider + ChangeNotifier

Viewed 2930

I followed a tutorial on YouTube to change a Flutter MaterialApp from light mode to dark mode (and vice versa), and the creator used the Provider plugin along with ChangeNotifier and notifyListeners();

import 'package:flutter/material.dart';


class ThemeChanger with ChangeNotifier{

  ThemeData _themeData;

  ThemeChanger(this._themeData);

  getTheme() => _themeData;

  setTheme (ThemeData theme) {
    _themeData = theme;

    notifyListeners();
  }

}

Then, on the tap of a button on another page,

import 'package:flutter/material.dart';
import 'package:gatorblocks_rbt/utils/themeChanger.dart';
import 'package:provider/provider.dart';

class GeneralSettings extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ThemeChanger _themeChanger = Provider.of<ThemeChanger>(context);

    return new Scaffold(
      appBar: AppBar(
        title: Text('General'),
      ),
      body: ListView(
        children: <Widget>[
          Card(
            child: ListTile(
              leading: Icon(Icons.brightness_3, size: 50.0),
              title: Text("Dark Mode"),
              subtitle: Text("Change the app to a dark mode theme!"),
              onTap: () {
                _themeChanger.setTheme(ThemeData.dark());
              },
            )
          ),
          Card(
            child: ListTile(
              leading: Icon(Icons.brightness_5, size: 50.0),
              title: Text("Light Mode"),
              subtitle: Text("Change the app to a light mode theme!"),
              onTap: () {
                _themeChanger.setTheme(ThemeData.light());
              },
            )
          ),
        ],
      )
    );
  }
}

Does anyone know how to change the primarySwatch color from the default blue to a different colour?

Sorry, I'm new to programming and don't really know how to explain/know what to do.

1 Answers

At this line:

        _themeChanger.setTheme(ThemeData.light());

use:

            _themeChanger.setTheme(ThemeData(brightness: Brightness.Light,primarySwatch: Colors.Red,);
Related