我需要在按下动态凸起按钮时更改特定凸起按钮的背景颜色吗?

时间:2019-07-22 06:08:17

标签: flutter

我需要在按下动态凸起按钮时更改其背景颜色吗?

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]

enter image description here

2 个答案:

答案 0 :(得分:1)

以下对我有用的

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

答案 1 :(得分:0)

尝试为您的RaisedButton创建一个有状态的小部件:

  • 定义颜色变量(颜色buttonColor)
  • 在您的initState中,将颜色设置为初始颜色(buttonColor = Colors.blueAccent),然后在小部件中使用它(颜色:buttonColor)
  • 在onPressed方法中,将按钮的颜色更改为另一种颜色:

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

应该可以。