即使更新了各自的变量,也无法在 Flutter 中更新上下文

Posted

技术标签:

【中文标题】即使更新了各自的变量,也无法在 Flutter 中更新上下文【英文标题】:Unable to get Context update in Flutter even after updating the respective variables 【发布时间】:2021-04-10 22:26:58 【问题描述】:

在下面的代码中,即使我的 var Lightvar Fan 定期更新屏幕上的整体文本内容 var str没有更新。如果这个问题听起来太愚蠢,我是一个初学者,很抱歉????我确实记住了无状态和有状态小部件的东西,我只是无法弄清楚为什么它没有在屏幕上更新。

class _MyHomePageState extends State<MyHomePage> 
var Fan = "Off";
var Light = "Off";
var str = "";
int fanState, lightState;
final firestoreInstance = Firestore.instance;
final databaseReference = Firestore.instance;
@override
void initState() 
// TODO: implement initState
   super.initState();
   getData();


@override
  Widget build(BuildContext context) 
    return ThemeSwitchingArea(
      child: Scaffold(
        drawer: Drawer(
          child: SafeArea(
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.topRight,
                  child: ThemeSwitcher(
                    builder: (context) 
                      return IconButton(
                        onPressed: () 
                          ThemeSwitcher.of(context).changeTheme(
                            theme: ThemeProvider.of(context).brightness ==
                                    Brightness.light
                                ? darkTheme
                                : lightTheme,
                          );
                        ,
                        icon: Icon(Icons.brightness_3, size: 25),
                      );
                    ,
                  ),
                ),
              ],
            ),
          ),
        ),
        appBar: AppBar(
          title: Text(
            'Home Control',
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Text(
                str,
                style: TextStyle(fontSize: 30),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  ThemeSwitcher(
                    builder: (context) 
                      return Checkbox(
                        value: ThemeProvider.of(context) == darkBlueTheme,
                        onChanged: (needDarkBlue) 
                          ThemeSwitcher.of(context).changeTheme(
                            theme: needDarkBlue ? darkBlueTheme : lightTheme,
                          );
                          triggerLight();
                        ,
                      );
                    ,
                  ),
                  ThemeSwitcher(
                    builder: (context) 
                      return Checkbox(
                        value: ThemeProvider.of(context) == halloweenTheme,
                        onChanged: (needBlue) 
                          ThemeSwitcher.of(context).changeTheme(
                            theme: needBlue ? halloweenTheme : lightTheme,
                          );
                          triggerFan();
                        ,
                      );
                    ,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  

  void getData() 
    databaseReference
        .collection("Home")
        .getDocuments()
        .then((QuerySnapshot snapshot) 
      snapshot.documents.forEach((f) 
        fanState = f.data['Fan'];
        lightState = f.data['Light'];
        if ((fanState == 1) && (lightState == 1)) 
          Fan = "On";
          Light = "On";
         else if ((fanState == 0) && (lightState == 1)) 
          Fan = "Off";
          Light = "On";
         else if ((fanState == 1) && (lightState == 0)) 
          Fan = "On";
          Light = "Off";
         else 
          Fan = "Off";
          Light = "Off";
        
        str = "Fan Status: $Fan" + "\n" + "Light Status: $Light";
      );
    );
  

  void triggerFan() 
    print("Fan Triggered");
    if (fanState == 1) 
      databaseReference
          .collection("Home")
          .document("myroom")
          .updateData('Fan': 0).then((value) 
        print("Status Updated Off");
        Fan = "Off";
        fanState = 0;
        getData();
      ).catchError((error) => print("Failed to add user: $error"));
     else 
      databaseReference
          .collection("Home")
          .document("myroom")
          .updateData('Fan': 1).then((value) 
        print("Status Updated On");
        Fan = "On";
        fanState = 1;
        getData();
      ).catchError((error) => print("Failed to add user: $error"));
    
  

  void triggerLight() 
    print("Light Triggered");
    if (lightState == 1) 
      databaseReference
          .collection("Home")
          .document("myroom")
          .updateData('Light': 0).then((value) 
        print("Status Updated to Off");
        Light = "Off";
        lightState = 0;
        getData();
      ).catchError((error) => print("Failed to add user: $error"));
     else 
      databaseReference
          .collection("Home")
          .document("myroom")
          .updateData('Light': 1).then((value) 
        print("Status Updated to On");
        Light = "On";
        lightState = 1;
        getData();
      ).catchError((error) => print("Failed to add user: $error"));
    
  

【问题讨论】:

【参考方案1】:

请使用此Code 更新您在Statefull Class 中的小部件状态

setState(() 
   //your Code Here
);

要了解更多关于 StatelessStaefull 类的信息,请来自 flutter 的 see this link。

举个简单的例子,如果我有一个Statefull Class 并且我在那个class 中有一个counter 变量设置为0:

int counter = 0;

但是,在某些方法调用中,我想将 counter 变量增加 1,然后我必须为 counter 变量更改 state 并使用 code 的这一行来更改其 state .

setState(() 
   counter = counter + 1;
);

现在,counter 变量的这种状态更改也会影响您的 UI,您会看到您的 UI 也随着更改后的 counter 值更新。

【讨论】:

以上是关于即使更新了各自的变量,也无法在 Flutter 中更新上下文的主要内容,如果未能解决你的问题,请参考以下文章

为啥即使在有状态小部件中使用 setstate 也无法获取更新的变量。因为我想在新的 TabBar 选项上更新我的 Container

即使在 Flutter 中使用正确的 SHA1 密钥,Google 地图也无法在发布版本中工作

即使收到更新的数据,Flutter ListView.builder 的 UI 也不会被 getx 更新

即使更新 Flutter,Dart 版本仍然相同

即使设置了解决方案,也无法在更新 Swift 后使用 withMemoryRebound

即使已经定义了变量,所需的代码也无法找到它们