skip to Main Content

I have a provider value like below:

var book = Provider.of<Books>(context, listen: false);

And an upload button like the following:

              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: book['imageUrl'] == ""
                      ? Theme.of(context).highlightColor
                      : Theme.of(context).primaryColor,
                  ),
                ),
                onPressed: () async {
                    setState(() {
                      book['imageUrl'] =
                          uploadURL!;
                    });
                  }
                },

What I want to do is changing the background color of the button when the image uploaded and book['imageUrl'] will be set inside the setState() function. But the above solution doesn’t work!

How can I do that?

2

Answers


  1. Call notifyListeners() to change the state of book

    Login or Signup to reply.
  2. You can have Consumer like:

    Consumer<Books>(
      builder: (context, book, _) => ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: book.imageUrl == "" ? Theme.of(context).highlightColor : Theme.of(context).primaryColor,
        ),
        onPressed: () async {
          setState(() {
            book.imageUrl = uploadURL!;
          });
        },
      ),
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search