简体   繁体   中英

I need to change background color of a particular raised button from dynamic raised button when it is pressed?

i need to change background color of dynamic raised button when it is pressed?

List<String> wordList=[i,r,o,n,m,a,n];

SizedBox(
  width: double.infinity,
  height: 300,
  child: GridView.count(
    crossAxisCount: 3,
    childAspectRatio: 2.5,
    padding: const EdgeInsets.all(10.0),
    mainAxisSpacing: 15.0,
    crossAxisSpacing: 15.0,
    children: wordList.map((String data) {
      return RaisedButton(
        color:Colors.blueAccent,
        child: Text(data),
        onPressed: () {
          print(data);
          setState(() {
            print("btnPressed ${btnPressed}");
            // listBool.insert(  , true);
            print("data $data");
            buttonPressed(data, btnPressed);
           });
        },
      );
    }).toList(),
  ))[![enter image description here][1]][1]

在此处输入图片说明

The following works for me

  List<String> wordList = ['i', 'r', 'o', 'n', 'm', 'a', 'n'];
  List<Color> colorList;

  @override
  void initState() {
    super.initState();

    colorList = List(wordList.length);
    colorList.fillRange(0, wordList.length, Colors.blueAccent);
  }


     SizedBox(
          width: double.infinity,
          height: 300,
          child: GridView.count(
            crossAxisCount: 3,
            childAspectRatio: 2.5,
            padding: const EdgeInsets.all(10.0),
            mainAxisSpacing: 15.0,
            crossAxisSpacing: 15.0,
            children: [
              for (int i = 0; i < wordList.length; i++)
                RaisedButton(
                  color: colorList[i],
                  child: Text(wordList[i]),
                  onPressed: () {
                    print(wordList[i]);
                    setState(() {
                      colorList[i] = Colors.black;
                      // listBool.insert(  , true);
                    });
                  },
                )
            ],
          ),
        ),

Try creating a Stateful Widget for your RaisedButton(s):

  • define a color variable (Color buttonColor)
  • in your initState, set the color to the initial color (buttonColor = Colors.blueAccent) and use it in the widget (color: buttonColor)
  • in your onPressed method, change the color of the button to another color:

    setState(() { buttonColor = Colors.amber; });

That should work.

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