简体   繁体   English

Flutter 变量在更改时不会更改背景颜色?

[英]Flutter variable doesn't change background color when changed?

I'm new to flutter and am trying to update the background color of a scaffold when a variable is changed.我是 flutter 的新手,正在尝试在更改变量时更新脚手架的背景颜色。 the variable is declared in another file.该变量在另一个文件中声明。 The reason why it needs to change?它需要改变的原因是什么? I am trying to change the background of the app to grey, a dark mode option.我正在尝试将应用程序的背景更改为灰色,这是一个暗模式选项。 Any advice on why the background doesn't change when the variable does?关于为什么背景在变量发生变化时不发生变化的任何建议? Any advice would be appreciated, thanks!任何建议将不胜感激,谢谢!

import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';

import './Widgets/DrawerSettings.dart';

void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
 ));
}
class FirstRoute extends StatefulWidget {
@override
_FirstRouteState createState() => _FirstRouteState();
}

class _FirstRouteState extends State<FirstRoute> {
@override
Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    drawer: Container(
      width: 70,
      child: ClipRRect(
        borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
        child: Drawer(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
            child: Column(
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.bookmark),
                  onPressed: () {
                    Navigator.push(
                        context,
                        PageTransition(
                            type: PageTransitionType.rightToLeft,
                            child: SavedRoute()));
                  },
                ),
                IconButton(
                  icon: Icon(Icons.rate_review),
                  onPressed: () {
                    Navigator.push(
                        context,
                        PageTransition(
                            type: PageTransitionType.rightToLeft,
                            child: ReviewRoute()));
                  },
                ),
                IconButton(
                  icon: Icon(Icons.share),
                  onPressed: () {
                    Share.share('Share');
                  },
                ),
                IconButton(
                  icon: Icon(Icons.settings),
                  onPressed: () {
                    Navigator.push(
                        context,
                        PageTransition(
                            type: PageTransitionType.rightToLeft,
                            child: SettingsRoute()));
                  },
                )
              ],
            ),
          ),
        ),
      ),
    ),
    appBar: AppBar(
      title: Text(
        'Explore',
      ),
      centerTitle: true,
      backgroundColor: Colors.cyan[500],
    ),
    body: Scaffold(
      backgroundColor: DarkMode ? Colors.grey[800] : Colors.white, //Here is the code to change the background color when variable change.
      body: Padding(
        padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
        child: Center(
          child: ListView(
            shrinkWrap: true,
            padding: EdgeInsets.all(5.0),
            children: <Widget>[
              Column(
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
                    height: 150,
                    width: double.maxFinite,
                    child: InkWell(
                      onTap: () {
                        Navigator.push(
                            context,
                            PageTransition(
                                type: PageTransitionType.rightToLeft,
                                child: SecondRoute()));
                      },
                      child: Card(
                        elevation: 5,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(15.0),
                          child: Image.network(
                            'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
                            fit: BoxFit.cover,
                            height: 150.0,
                            width: 100.0,
                          ),
                        ),
                      ),
                    ),
                  ),
               ],
          ),
        ),
      ),
    ),
  ),
);
}
}

Here is the second file这是第二个文件

import 'package:flutter/material.dart';

class SettingsRoute extends StatefulWidget {
@override
_SettingsRouteState createState() => _SettingsRouteState();
}

bool DarkMode = false;

class _SettingsRouteState extends State<SettingsRoute> {
@override
Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
    appBar: AppBar(
      title: Text(
        'Settings',
      ),
      centerTitle: true,
    ),
    body: ListView(
      children: <Widget>[
        Container(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
            child: SwitchListTile(
              title: Text(
                'Dark Mode',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w400,
                  color: DarkMode ? Colors.white : Colors.grey[800],
                ),
              ),
              value: DarkMode,
              activeColor: Colors.white,
              inactiveThumbColor: Colors.white,
              onChanged: (bool value) {
                setState(() {
                  DarkMode = !DarkMode;
                });
              },
            ),
          ),
        ),
      ],
    ),
  ),
);
}
}

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
You can pass callback refresh to SettingsRoute and call with widget.callback()您可以将回调refresh传递给SettingsRoute并使用widget.callback()调用
You can see working demo below您可以在下面看到工作演示
code snippet代码片段

class _FirstRouteState extends State<FirstRoute> {
  refresh() {
    setState(() {});
  }
...  
onPressed: () {
      Navigator.push(
          context,
          PageTransition(
              type: PageTransitionType.rightToLeft,
              child: SettingsRoute(
                callback: refresh,
              )));
    },  
... 
class SettingsRoute extends StatefulWidget {
  final VoidCallback callback;
  SettingsRoute({this.callback});   
...  
 onChanged: (bool value) {
        setState(() {
          DarkMode = !DarkMode;
        });

        widget.callback();
      },  

working demo工作演示

在此处输入图像描述

full code完整代码

import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';

void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: FirstRoute(),
  ));
}

class FirstRoute extends StatefulWidget {
  @override
  _FirstRouteState createState() => _FirstRouteState();
}

class _FirstRouteState extends State<FirstRoute> {
  refresh() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      drawer: Container(
        width: 70,
        child: ClipRRect(
          borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
          child: Drawer(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
              child: Column(
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.bookmark),
                    onPressed: () {
                      /* Navigator.push(
                            context,
                            PageTransition(
                                type: PageTransitionType.rightToLeft,
                                child: SavedRoute()));*/
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.rate_review),
                    onPressed: () {
                      /* Navigator.push(
                            context,
                            PageTransition(
                                type: PageTransitionType.rightToLeft,
                                child: ReviewRoute()));*/
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.share),
                    onPressed: () {
                      Share.share('Share');
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.settings),
                    onPressed: () {
                      Navigator.push(
                          context,
                          PageTransition(
                              type: PageTransitionType.rightToLeft,
                              child: SettingsRoute(
                                callback: refresh,
                              )));
                    },
                  )
                ],
              ),
            ),
          ),
        ),
      ),
      appBar: AppBar(
        title: Text(
          'Explore',
        ),
        centerTitle: true,
        backgroundColor: Colors.cyan[500],
      ),
      body: Scaffold(
        backgroundColor: DarkMode
            ? Colors.grey[800]
            : Colors
                .white, //Here is the code to change the background color when variable change.
        body: Padding(
          padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
          child: Center(
            child: ListView(
                shrinkWrap: true,
                padding: EdgeInsets.all(5.0),
                children: <Widget>[
                  Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
                        height: 150,
                        width: double.maxFinite,
                        child: InkWell(
                          onTap: () {
                            /* Navigator.push(
                      context,
                      PageTransition(
                          type: PageTransitionType.rightToLeft,
                          child: SecondRoute()));*/
                          },
                          child: Card(
                            elevation: 5,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(15.0),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(15.0),
                              child: Image.network(
                                'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
                                fit: BoxFit.cover,
                                height: 150.0,
                                width: 100.0,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ]),
          ),
        ),
      ),
    ));
  }
}

class SettingsRoute extends StatefulWidget {
  final VoidCallback callback;
  SettingsRoute({this.callback});
  @override
  _SettingsRouteState createState() => _SettingsRouteState();
}

bool DarkMode = false;

class _SettingsRouteState extends State<SettingsRoute> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
        appBar: AppBar(
          title: Text(
            'Settings',
          ),
          centerTitle: true,
        ),
        body: ListView(
          children: <Widget>[
            Container(
              child: Padding(
                padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
                child: SwitchListTile(
                  title: Text(
                    'Dark Mode',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w400,
                      color: DarkMode ? Colors.white : Colors.grey[800],
                    ),
                  ),
                  value: DarkMode,
                  activeColor: Colors.white,
                  inactiveThumbColor: Colors.white,
                  onChanged: (bool value) {
                    setState(() {
                      DarkMode = !DarkMode;
                    });

                    widget.callback();
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

You need to get the value of the DarkMode variable from a global variable like using an app state provider.您需要从全局变量中获取 DarkMode 变量的值,例如使用应用程序 state 提供程序。 Or you can send the DarkMode value as a parameter to the next page.或者您可以将 DarkMode 值作为参数发送到下一页。 The first one is a better use-case.第一个是更好的用例。

Your provider will look like this:您的提供商将如下所示:


import 'package:flutter/material.dart';

class AppStateProvider with ChangeNotifier {

  bool _darkMode = false;

  bool get darkMode => this._darkMode;

  void setDarkMode(bool value) {
    this._darkMode = value;
  }
}

You can read more from here .您可以从这里阅读更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM