cabral279
cabral279

Reputation: 97

Declare variable outside Widget build in Flutter

I am trying to use a variable in other class, but it is not working. Why can't I declare orderChanged outside the Widget build?

The code:

class HomeButton extends StatefulWidget {

  static bool orderChanged;

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

class _HomeButtonState extends State<HomeButton> {

 
  @override
  Widget build(BuildContext context) {
    bool _orderChanged = false;
    bool orderChanged = _orderChanged;
    return
        .
        .
        .
       
  onPressed: () async {

     setState(() {
     _orderChanged = true;
    });
  }
   .
   .
   .
  
        

Thank you :)

Upvotes: 0

Views: 1483

Answers (1)

Monik
Monik

Reputation: 321

You should declare variable outside the build method as it builds again and again. Either you can declare _HomeButtonState class or HomeButton. if you want to declare variable(that is orderChanged) in HomeButton (stateful class) you can access that variable using

widget.orderChanged;

Upvotes: 1

Related Questions