Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

flutter - How to pass a boolean value from one class to another and back?

I am trying to use the Visibility widget to show and hide my page. Here is my logic when at the first page the booean isVisible is true showing the Container widget but as I go to another screen I set the boolean isVisiblevis to false such that my container hides and maintains it state. When I come back from the second screen I want to set the boolean back to true hence showing my container.

First page

class MainScreen extends StatefulWidget {
 bool isVisible = true;

  MainScreen({this.isVisible});

 ...
 @override
  Widget build(BuildContext context) {
  body: Container(
            //change the margin
            margin: EdgeInsets.fromLTRB(0, 0, 0, 300),
            child: isVisible ?
            Visibility(
                maintainAnimation: true,
                maintainState: true,
                child: (Container(
                        Text ('first page')
                 ): Container ()

                 .....
                 GestureDetector(
                      onTap: () {
                        isVisible= false; //set the visibility false
                        Navigator.push(
                            //send to search screen
                            context,
                            MaterialPageRoute(
                                builder: (context) => (SecondScreen())));
                       
                      },

Now on the second page when I pop how do I set the boolean isVisible back to true on first page ?

  GestureDetector(
        onTap: () {
            Navigator.pop(
                //send back data
                context,
                dropOffTextEditingController.text,
            );
            MainScreen(mapVisible: true,); //doesn't work
        },
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See what is happening here, when you are setting the isVisible to false you have to use it on the second page means that you have to pass the isVisible data from one page to another. You can refer here:

first.dart

class MainScreen extends StatefulWidget {
  bool isVisible = true;

  MainScreen({this.isVisible});

}

Navigator.push(context,MaterialPageRoute(builder: (context) => Second(data: isVisible)));

second.dart

class Second extends StatefulWidget {
  final String data;

  MyPosts({this.data});
}

you can use as widget.data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...