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

时间:2019-11-13 12:43:13

标签: flutter flutter-layout gesturedetector

我连续有两个容器,我要做的是,当我单击第一个容器时,它会更改其颜色以及第二个容器

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

反正有这样做吗?

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

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法。这将使用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"),
          ),
        ),
      ],
    );
  }
}