Flutter-在一个调用setState()之后更新同级小部件

时间:2019-12-11 19:55:25

标签: android flutter dart

我有一个Dialog Widget,那里有一个Button和Text字段。按下按钮后,将具有setState()和变量更改功能。我没有在文本字段的屏幕上立即看到这些更改,我需要再次关闭并打开Dialog。为什么以及如何实现它(这样将重建整个班级/家长?(关于“获取位置”按钮和下一个字段)

class MyDialog extends StatefulWidget {
  MyDialogState createState() => MyDialogState();
}

class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30)
                  ),
                  elevation: 20,
                  child: ListView(
                    children: <Widget>[
                      FlatButton(
                        child: Text("Get location $userLocation"),
                        onPressed: () {
                          final Geolocator geolocator = Geolocator();
                          geolocator
                            .getCurrentPosition()
                            .then((Position position) async {
                              List<Placemark> place = await geolocator
                                .placemarkFromCoordinates(position.latitude, position.longitude);
                              Placemark p = place[0];

                              setState(() {
                                //userLocation = "${p.locality}, ${p.country}";
                                userLocation = Random().nextInt(10).toString();
                                print("A");

                              });

                          }).catchError((e) {
                            print("------------");
                            print(e);
                            print("------------");
                          });
                        },
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Center(child: Text("$userLocation"))
                      ),
                      Divider(),
                      FlatButton(
                        child: Text("Set sleep length"),
                        onPressed: () {
                          //TODO
                        },
                      ),
                      Padding(
                          padding: EdgeInsets.all(10),
                          child: Center(child: Text("$sleepLength"))
                      ),
                      Divider(),
                    ],
                  )
              );
            }
        );
      },
      child: Icon(
          Icons.settings
      ),
      backgroundColor: Colors.black12,
    );
  }
}

enter image description here

3 个答案:

答案 0 :(得分:2)

在我的情况下,StatefulBuilder有效。 StatefulBuilder最适用于您拥有中型/大型窗口小部件树并且需要为该树的一小部分引入状态的情况。

StatefulBuilder包裹您的孩子,希望对您有帮助。

答案 1 :(得分:1)

您必须用return StatefulBuilder builder: ...包装Dialog
并仔细考虑});,因为在这种情况下,它是一个长字符串

代码段

 builder: (BuildContext context) {
      return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {

          return Dialog(
              ...
          );

        },
      );

您的带有StatefulBuilder的代码

class MyDialog extends StatefulWidget {
  MyDialogState createState() => MyDialogState();
}

class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return StatefulBuilder(
                  builder: (BuildContext context, StateSetter setState) {
                return Dialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30)),
                    elevation: 20,
                    child: ListView(
                      children: <Widget>[
                        FlatButton(
                          child: Text("Get location $userLocation"),
                          onPressed: () {
                            final Geolocator geolocator = Geolocator();
                            geolocator
                                .getCurrentPosition()
                                .then((Position position) async {
                              List<Placemark> place =
                                  await geolocator.placemarkFromCoordinates(
                                      position.latitude, position.longitude);
                              Placemark p = place[0];

                              setState(() {
                                //userLocation = "${p.locality}, ${p.country}";
                                userLocation = Random().nextInt(10).toString();
                                print("A");
                              });
                            }).catchError((e) {
                              print("------------");
                              print(e);
                              print("------------");
                            });
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$userLocation"))),
                        Divider(),
                        FlatButton(
                          child: Text("Set sleep length"),
                          onPressed: () {
                            //TODO
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$sleepLength"))),
                        Divider(),
                      ],
                    ));
              });
            });
      },
      child: Icon(Icons.settings),
      backgroundColor: Colors.black12,
    );
  }
}

答案 2 :(得分:1)

使用StatefulBuilder可以解决此问题

将您的MyDialogState替换为:

class MyDialogState extends State<MyDialog> {
  String userLocation;
  double sleepLength;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30)
                  ),
                  elevation: 20,
                  child: StatefulBuilder(
                    builder: (BuildContext context, StateSetter setState) {
                      return ListView(
                      children: <Widget>[
                        FlatButton(
                          child: Text("Get location $userLocation"),
                          onPressed: () {
                            final Geolocator geolocator = Geolocator();
                            geolocator
                              .getCurrentPosition()
                              .then((Position position) async {
                                List<Placemark> place = await geolocator
                                  .placemarkFromCoordinates(position.latitude, position.longitude);
                                Placemark p = place[0];

                                setState(() {
                                  //userLocation = "${p.locality}, ${p.country}";
                                  userLocation = Random().nextInt(10).toString();
                                  print("A");

                                });

                            }).catchError((e) {
                              print("------------");
                              print(e);
                              print("------------");
                            });
                          },
                        ),
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Center(child: Text("$userLocation"))
                        ),
                        Divider(),
                        FlatButton(
                          child: Text("Set sleep length"),
                          onPressed: () {
                            //TODO
                          },
                        ),
                        Padding(
                            padding: EdgeInsets.all(10),
                            child: Center(child: Text("$sleepLength"))
                        ),
                        Divider(),
                      ],
                    );
                    },
                  )
              );
            }
        );
      },
      child: Icon(
          Icons.settings
      ),
      backgroundColor: Colors.black12,
    );
  }
}