即使更新了相应的变量后也无法在 Flutter 中获取上下文更新

Unable to get Context update in Flutter even after updating the respective variables

在下面的代码中,即使我的 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"));
    }
  }
}

请使用此 Code 更新 Statefull Class

中的小部件状态
setState(() {
   //your Code Here
});

要了解更多关于 StatelessStaefull Class 请 see this link 来自 flutter.

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

int counter = 0;

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

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

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