我如何在 FLUTTER 的 onTap 事件中更改 Container 的颜色和文本

How do i change the color and text of Container at onTap event in FLUTTER

我有两个连续的容器,我想做的是当我点击第一个容器时它会改变颜色,第二个容器也会改变颜色

即-当我点击第一个容器时,它看起来像被选中,而另一个被取消选择,与第二个容器相同。

有办法吗?

GestureDetector(
                    onTap: () {
                      print('its getting pressed');

                    },
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            height: screenHeight * 0.057,
                            width: double.infinity,
                            color: greyf1,
                            child: Center(
                              child: Text(
                                'Borrower',
                                style: hintTextTextStyle,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Expanded(
                          child: Container(
                            height: screenHeight * 0.057,
                            width: double.infinity,
                            color: greyf1,
                            child: Padding(
                              padding: const EdgeInsets.only(left: 15),
                              child: Center(
                                child: Text(
                                  'Lender',
                                  style: hintTextTextStyle,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

您可以尝试以下方法。这将使用 selected 属性 来决定哪个容器应该是蓝色的。

没有测试代码

class _TestState extends State<Test> {
  String selected = "first";

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        GestureDetector(
          onTap: () {
            setState(() {
              selected = 'first';
            });
          },
          child: Container(
            height: 200,
            width: 200,
            color: selected == 'first' ? Colors.blue : Colors.transparent,
            child: Text("First"),
          ),
        ),
        GestureDetector(
          onTap: () {
            setState(() {
              selected = 'second';
            });
          },
          child: Container(
            height: 200,
            width: 200,
            color: selected == 'second' ? Colors.blue : Colors.transparent,
            child: Text("Second"),
          ),
        ),
      ],
    );
  }
}