Flutter: How I Can Change Theme Using Switch in Flutter - 我已经使用 Provider 实现了这个明暗主题,但是不能用 switch 改变

Flutter: How I Can Change Theme Using Switch in Flutter - I have Implemented this Light and Dark Theme Using Provider, But can not change with switch

我已经使用了更改主题的提供程序,这是浅色和深色主题的代码。我的问题的主要目的是通过开关而不是按钮来更改主题。 可以使用“int 模式”正确地通过按钮更改主题。 但是当我因为一个开关而使用“布尔模式”时。开关需要值为 true 或 false。

如何实现这个改变明暗主题的开关?我需要一个开关,而不是按钮。

import 'package:flutter/material.dart';

class AppStyleModeNotifier extends ChangeNotifier {
  bool mode = true; //0 for light and 1 for dark
  Color primaryBackgroundColor = Colors.white;
  Color appBarBackgroundColor = Colors.cyan[200];
  Color boxColor = Colors.blue[50];
  Color boxTextColor = Colors.indigo;
  Color primaryTextColor = Colors.white;
  Color dashboardColor = Colors.cyan;
  Color dashboardTextColor = Colors.red[600];
  Color dashboardIconColor = Colors.yellow[200];
  //Color typeMessageBoxColor = Colors.grey[200];

  switchMode() {
    if (mode == true) {
      //if it is light mode currently switch to dark
      primaryBackgroundColor = Colors.grey[900];
      appBarBackgroundColor = Colors.grey[800];
      // boxColor = Colors.grey[600];
      boxColor = Colors.black;
      boxTextColor = Colors.grey[100];
      primaryTextColor = Colors.black;
      dashboardColor = Colors.grey[900];
      dashboardTextColor = Colors.grey[400];
      dashboardIconColor = Colors.white;
      //typeMessageBoxColor = Colors.grey[800];
      mode = false;
    } else {
      //if it is dark mode currently switch to light
      primaryBackgroundColor = Colors.white;
      appBarBackgroundColor = Colors.cyan[200];
      boxColor = Colors.tealAccent;
      boxTextColor = Colors.indigo;
      primaryTextColor = Colors.white;
      dashboardColor = Colors.cyan;
      dashboardTextColor = Colors.red[600];
      dashboardIconColor = Colors.yellow[200];
      //typeMessageBoxColor = Colors.grey[200];
      mode = true;
    }

    notifyListeners();
  }
}

以下是切换明暗主题的开关。这个开关没有正常工作,代码中是否有错误。而不是使用按钮的开关,它工作正常。

import 'package:provider/provider.dart';
import '../FreelanceTheme/AppStyleModeNotifier.dart';

class HomePage extends StatelessWidget with NavigationStates {

  const HomePage({Key key, this.onMenuTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final appStyleMode = Provider.of<AppStyleModeNotifier>(context);
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xffE5E5E5),
        appBar: AppBar(
          elevation: 0,
          backgroundColor: appStyleMode.appBarBackgroundColor,
          actions: <Widget>[
            Switch(
              value: appStyleMode.mode,
              onChanged: appStyleMode.switchMode(),
            ),

将你的代码改成这样,它会起作用。

Switch(
  value: appStyleMode.mode,
  onChanged: (value)=> appStyleMode.switchMode(),
),