简体   繁体   English

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

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

In the Below code even though My var Light and var Fan are updated on a regular intervals the overall text content var str on screen is not updated.在下面的代码中,即使 My var Lightvar Fan定期更新,屏幕上的整体文本内容var str也不会更新。 I am a beginner to flutter sorry if the question sounds too dumb I did keep in mind about the stateless and stateful widget stuff i am just unable to figure out why its not updating on screen.我是 flutter 的初学者,对不起,如果这个问题听起来太愚蠢,我确实记住了无状态和有状态小部件的东西,我只是无法弄清楚为什么它没有在屏幕上更新。

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"));
    }
  }
}

Please use this Code to update your state of widgets in Statefull Class请使用此CodeStatefull Class中更新您的 state 小部件

setState(() {
   //your Code Here
});

To know more about the Stateless and Staefull Class Please see this link from flutter .要了解有关StatelessStaefull Class 的更多信息,请参阅flutter此链接

For A simple Example, If I have a Statefull Class and have I am having a counter variable in that class set to 0:举一个简单的例子,如果我有一个StatefullClass并且我有一个counter变量,其中class设置为 0:

int counter = 0;

But, on some method call I want to increase that counter variable by 1, then I have to change the state for that counter variable and use this line of code to change its state .但是,在某些方法调用中,我想将该counter变量增加 1,然后我必须更改该counter变量的state并使用这行code来更改其state

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

Now, This state change of counter variable will effect on your UI too, and You will see that your UI is also updated with the changed counter value.现在, counter变量的 state 更改也会影响您的UI ,您会看到您的UI也随着更改的counter值更新。

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

相关问题 即使设置环境变量后也无法识别颤振 - flutter is not recognised even after setting environment variables 更新后无法登录我的 Flutter 应用程序 - Unable to Login into my flutter app after updating 即使在更新后,Play 商店仍要求我更新第三方库。 无法将应用上传到 Play 商店 - Play store asking me to update third party library even after updating. Unable to upload app to play store 即使在更新模型成功后更新 RecyclerView 也失败 - Update RecyclerView failed even after updating model success Flutter 更新Android Studio 后无法定位Java 运行时? - Flutter unable to locate Java Runtime after updating Android Studio? 更新google-play-services之后,即使安装了最新版本,Google Play仍需要更新 - after updating google-play-services, google play says update needed even though latest is installed Flutter `pubspec.lock` 在 `flutter pub get` 之后没有按照 `pubspec.yaml` 中的版本进行更新 - Flutter `pubspec.lock` Is Not Updating As Per Versions In `pubspec.yaml` After `flutter pub get` BadTokenException即使在引用Activity而不是应用程序上下文之后 - BadTokenException even after referring to Activity and not the application context 使用Android Studio更新2.2.0更新gradle 2.2后无法创建apk - Unable to create apk after updating gradle 2.2 using Android Studio update 2.2.0 无法从片段获取上下文 - Unable to get context from Fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM