简体   繁体   中英

Flutter change text when button pressed

yo guys i'll try to change text at button when clicked on...

my code :

         bool pressGeoON = false;
         bool cmbscritta = false;
           RaisedButton(
                  shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red)),
                  color: pressGeoON ? Colors.blue: Colors.red,
                  textColor: Colors.white,
                  child:  cmbscritta ? Text("GeoOn"): Text("GeoOFF"),
                  //    style: TextStyle(fontSize: 14)

                  onPressed: () {
                    setState(() => pressGeoON = !pressGeoON);
                    setState(() => cmbscritta = !cmbscritta);
                  },
                )

No advice from dart Analisys but not work...help!

your class must be stateful to change state of activity

also the variable must be declared globally

class MyClass extends StatefulWidget {
  @override
  _MyClassState createState() => _MyClassState();
}

class _MyClassState extends State<MyClass> {
  bool pressGeoON = false;
  bool cmbscritta = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.red)),
          color: pressGeoON ? Colors.blue : Colors.red,
          textColor: Colors.white,
          child: cmbscritta ? Text("GeoOn") : Text("GeoOFF"),
          //    style: TextStyle(fontSize: 14)
            onPressed: () {
              setState(() {
                pressGeoON = !pressGeoON;
                cmbscritta = !cmbscritta;
              });
            }
        ),
      ),
    );
  }
}

For this bool pressGeoON = false; bool cmbscritta = false; should be global variable of your widget and it will start working.

You should simplify your onPressed as:

onPressed: () {
   setState(() {
     pressGeoON = !pressGeoON;
     cmbscritta = !cmbscritta;
  });
}

and make sure your widget class is StatefulWidget not StatelessWidget

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM