Gautham Nadar
Gautham Nadar

Reputation: 55

Flutter: setState not updating UI

onTap it prints value but setState doesnt makes any difference in UI and im using it in a stateful widget and inside build too, i couldnt get where im making mistake, and im using flutter beta.

Widget build(BuildContext context) {

String text = "HEY";

void bb(){
  print('Clicked Clicked');
  setState(() {
    text = "HEY2";
  });
}

return Scaffold(
  body: Container(
      decoration: BoxDecoration(
        image:  DecorationImage(image: new AssetImage("assets/floor.jpg"), fit: BoxFit.cover,),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: Text(
              'HELLO, WORLD!', 
              style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), 
              textScaleFactor: 6,),
          ),
          Divider(height: 80),
          GestureDetector(
            onTap: (){
              bb();
            },
            child: Text(text, style: TextStyle(color: Colors.red)),
          ),

        ],),
    )
);

}

Upvotes: 4

Views: 6791

Answers (2)

arthankamal
arthankamal

Reputation: 6413

You should not put the variable inside the build. It should be outside the build function.

class _YourPageState extends State<YourPage> {
    String text = "HEY";

    void bb() {
      print('Clicked Clicked');
      setState(() {
      text = "HEY2";
    }

    Widget build(BuildContext context) {
      ....
    }
}

Upvotes: 3

Your variable it's not part of the State of the page, its part of the build function. Everytime the state changes, the build function is triggered, changing back the value of the variable text.

You need to move this part:

  String text = "HEY";

    void bb(){
      print('Clicked Clicked');
      setState(() {
        text = "HEY2";
      });
    }

to outside the build function, becoming something like this:

class _MyHomePageState extends State<MyHomePage> {
    String text = "HEY";

    void bb(){
      print('Clicked Clicked');
      setState(() {
        text = "HEY2";
      });
    }
  @override
  Widget build(BuildContext context) {

    List<bool> _selections = List.generate(3, (index) => false);

Upvotes: 11

Related Questions