Daniele Angelini
Daniele Angelini

Reputation: 93

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!

Upvotes: 4

Views: 31820

Answers (4)

Safal Bhatia
Safal Bhatia

Reputation: 405

Simple You can make One variable

var name = "safal"

After that make one method

void changeName(){
 setState(() {
 name = "Sahil";
 });
}

Set text in your Text

Text(
 name,
 style: const TextStyle(
  fontSize: 14,
  fontFamily:
  "Roboto Font Family",
  fontWeight: FontWeight.w400,
  color: grey_color),
)

Upvotes: 0

Kalpesh Kundanani
Kalpesh Kundanani

Reputation: 5753

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

Upvotes: 6

Jay Gadariya
Jay Gadariya

Reputation: 1941

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;
              });
            }
        ),
      ),
    );
  }
}

Upvotes: 14

OMi Shah
OMi Shah

Reputation: 6186

You should simplify your onPressed as:

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

and make sure your widget class is StatefulWidget not StatelessWidget

Upvotes: 3

Related Questions