1

I would like to change the text inside ElevatedButton when I click. For example 'Fav' to 'Unfav' and the color of the button when I do this action change also. I tried with boolean and also to change the text in Button inside setState block, it didn't help.

Demontration what I want to change

Code where I try to do this

ElevatedButton(
    child: Text(title),
    onPressed: () async {

      String ref = ads.reference.id;
      String? favuid = user != null
          ? user?.uid
          : googleUser?.id;

      if (favuid != null) {
        setState(() {
          title = 'UnFav';
          if ((ads.data() as dynamic)['isfav$favuid'] == null || !(ads.data() as dynamic)['isfav$favuid']) {
            collectionads.doc(ref).update({
              'isfav$favuid': true

            });
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(
              duration: Duration(seconds: 2),
              content: Text("Add to Favourite list"),
            ));
          }
          else {
            title = 'Fav';
            collectionads.doc(ref).update({
              'isfav$favuid': false
            });
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(
              duration: Duration(seconds: 2),
              content: Text(
                  "Deleted from Favourite list"),
            ));

          }
        });
        setState(() {
          !(ads.data() as dynamic)['isfav$favuid'] == (ads.data() as dynamic)['isfav$favuid'];
        });
      }
    },
    
  )

4 Answers 4

3
  bool fav = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            if(fav)
              setState(() => fav=false);
            else
              setState(() => fav=true);
          },
          child: Text(fav ? 'Fav' : 'Unfav'),
          style: ElevatedButton.styleFrom(
            primary: fav? Colors.blue : Colors.black12,
          ),
        ),
      ),
    );
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for taking part of my question! Your all suggestion works, so i will choose correct answer who is have smallest reputation score)
No problem, if its work you are invited for vote
1

The title variable needs to be a part of a StatefulWidget's state class, and setState will then change the text

class MyWidget extends StatefulWidget {
  const MyWidget({ Key? key }) : super(key: key);

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

class _MyWidgetState extends State<MyWidget> {
  String title = 'Fav';
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(onPressed: () {
        setState(() {
          title = 'UnFav';
        });
      }, child: Text(title))
    );
  }
}

Comments

0

This can be achieved using a combination of single bool variable and setState to set the button state from isFav to !isFav. Now you can change anything inside your method setState similarly as we changed text and color.

@anderson48 Try the code below it this way its easiest to achieve what you want to, try to run this code in dartpad

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isFav = true;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold( appBar: new AppBar(
          title: Text("Sample"),
        ),
    body: Column(
       mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: <Widget>[
    isFav
        ? MaterialButton(
            child: Text("button 1" , style: TextStyle(
                        color: Colors.red,
                        fontSize: 32)), // fav
            onPressed: () {
               setState(() {
     isFav = !isFav;
            });
            },
          )
        : Container(),
    !(isFav)
        ? MaterialButton(
            child: Text("Button 2" , style: TextStyle(
                        color: Colors.blue,
                        fontSize: 50)),  // not fav
            onPressed: () {
               setState(() {
     isFav = !isFav;
            });
            },
          )
        : Container(),
  ],
)));
  }
}

3 Comments

Thanks for taking part of my question! Your all suggestion works, so i will choose correct answer who is have smallest reputation score)
@anderson48 np but if you do want to help me you can jut upvote my answer, it would mean a lot to me...
well it seems your are new to Stackoverflow there is difference in accepting answer and upvoting question. You upvote the answer by clicking on up button next to the answer if you find the post helpful it helps people gain trust over the person and makes easy for other developers to check which answer is more useful by votes and accepted answer.... no worries
0

setState() will not work inside build() in flutter new releases.

Describe function in class and you can write all code in this function.

    void yourFunction(){
      setState(() {
       isFav = !isFav;
       });
    }

and After

onPressed: yourFunction,

1 Comment

Thanks for taking part of my question! Your all suggestion works, so i will choose correct answer who is have smallest reputation score)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.