Mo711
Mo711

Reputation: 639

Make text appear on click

I am trying to make some text appear, where there was no text before. It should happen on the click of a button. The button should change a bool variable too true so that something like an if statement can then validate if the button was clicked. The code for the button looks like this:

child: GestureDetector(
   onTap: () {
     ButtonPushed = true;
   }
 ...

But I have no idea how to create a statement, that checks if ButtonPushed equals true and only then execute the lines of code that display the text somewhere above the button on the screen.

Thanks in advance for your answers!

Upvotes: 0

Views: 1781

Answers (2)

Firas BENMBAREK
Firas BENMBAREK

Reputation: 310

Simply do :

bool myBool = false;
FlatButton(
  onPressed: () {
    setState(() {
      myBool = !myBool;
    });
  },
  child: Text(
    "Press me",
  ),
),
Visibility(
visible : myBool,
child: Text("Hello"),
    )

Here's a codepen of it working.

Upvotes: 0

TheMisir
TheMisir

Reputation: 4279

Create a StatefulWidget. Store _clicked state on state and change it when button is pressed. On build method show or hide based on value of _clicked.

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _clicked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            if (_clicked) Text('Button is clicked'),
            FlatButton(
              onPressed: () {
                setState(() {
                  _clicked = true;
                });
              },
              child: Text('Click me')
            ),
          ],
        ),
      ),
    );
  }
}

To show/hide Text I'm simply using if (condition) Widget(),. Because widget is placed inside Widget list (Column's children property accepts widget list). You could als use something like that:

child: _clicked ? Text('clicked') : null,

If this code crashes because of widget doesn't accepts null child you could try this:

child: _clicked ? Text('clicked') : SizedBox(),

Check flutter reference:

Upvotes: 1

Related Questions