What is the way to change a property for several items at the same time with different values for one property, such as color, for example

huangapple go评论59阅读模式
英文:

What is the way to change a property for several items at the same time with different values for one property, such as color, for example

问题

我是一个在Filter中的初学者,我正在用Google翻译输入这些话,我的英语不太好,请帮助,非常感谢。
问题描述
我有四个可点击的容器。当用户点击它们时,我希望只有当前容器的背景颜色会变为红色,其余三个容器的背景颜色会变为蓝色。

我尝试了好几次,可惜五天来都没有成功...
我在哪里使用了一个变量来将col的值初始化为白色
这是问题的部分

GestureDetector(
   onTap: () {
     setState(() {
      (col == Colors.white) ? col = Colors.red : col = Colors.blue;
          });
   },
   child: Container(
     alignment: Alignment.topLeft,
     decoration: BoxDecoration(
       color: color,
     ),
     child: Text(
       'S',
     ),
   ),
),

我只是希望当点击容器时,它以与其他容器不同的特征更改颜色。

英文:

I am a beginner in Filter and I am typing these words with Google translator, my English is not good, please help and thank you very much.
Description of the problem
I have four clickable containers. I would like when the user clicks on them, only the background color of the current container will be changed to red, and the rest of the three containers will have their background color changed to blue.

I tried several times and for five days I couldn't do anything unfortunately..
Where I used a variable to set the col value to be white as an initial value
This is the problem part

GestureDetector(
   onTap: () {
     setState(() {
      (col == Colors. white) ?col = Colors. red:col = Colors. blue;
          });
   },
   child: Container(
     alignment: Alignment. topLeft,
     decoration: BoxDecoration(
       color: color,
     ),
     child: Text(
       'S',
     ),
   ),
),`

I just want when clicking on the container, it changes color with a characteristic that differs from other containers

答案1

得分: 0

(col == Colors.white) ? col = Colors.red : col = Colors.blue;

Or

col = col == Colors.white ? Colors.red : col = Colors.blue;

But if you are using a single variable for all three containers, it will change them all. Try using a List instead.

class CContainerChanged extends StatefulWidget {
  const CContainerChanged({super.key});

  @override
  State<CContainerChanged> createState() => _CContainerChangedState();
}

class _CContainerChangedState extends State<CContainerChanged> {
  List<Color> containerColors = [
    Colors.cyanAccent,
    Colors.deepPurpleAccent,
    Colors.deepOrangeAccent,
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          for (int i = 0; i < containerColors.length; i++)
            Container(
              width: 100,
              height: 100,
              color: containerColors[i],
              child: TextButton(
                onPressed: () {
                  setState(() {
                    containerColors[i] = Colors.red;
                  });
                },
                child: Text('Change color'),
              ),
            ),
        ],
      ),
    ));
  }
}

If it is about selecting a single container, it will

class CContainerChanged extends StatefulWidget {
  const CContainerChanged({super.key});

  @override
  State<CContainerChanged> createState() => _CContainerChangedState();
}

class _CContainerChangedState extends State<CContainerChanged> {
  List<Color> containerColors = [
    Colors.cyanAccent,
    Colors.deepPurpleAccent,
    Colors.deepOrangeAccent,
  ];

  int? selectedIndex;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          for (int i = 0; i < containerColors.length; i++)
            Container(
              width: 100,
              height: 100,
              color: selectedIndex == i ? Colors.red : containerColors[i],
              child: TextButton(
                onPressed: () {
                  setState(() {
                    selectedIndex = i;
                  });
                },
                child: Text('Change color'),
              ),
            ),
        ],
      ),
    ));
  }
}
英文:

You need to assign color with ternary operator like

(col == Colors.white) ? col = Colors.red:col : col = Colors.blue;

Or

col =  col == Colors.white? Colors.red:col : Colors.blue;

But if you are using single variable for all three container, it will change them all. Try using List instead.

class CContainerChanged extends StatefulWidget {
  const CContainerChanged({super.key});

  @override
  State&lt;CContainerChanged&gt; createState() =&gt; _CContainerChangedState();
}

class _CContainerChangedState extends State&lt;CContainerChanged&gt; {
  List&lt;Color&gt; containerColors = [
    Colors.cyanAccent,
    Colors.deepPurpleAccent,
    Colors.deepOrangeAccent,
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          for (int i = 0; i &lt; containerColors.length; i++)
            Container(
              width: 100,
              height: 100,
              color: containerColors[i],
              child: TextButton(
                onPressed: () {
                  setState(() {
                    containerColors[i] = Colors.red;
                  });
                },
                child: Text(&#39;Change color&#39;),
              ),
            ),
        ],
      ),
    ));
  }
}

If it is about selecting single container, it will


class CContainerChanged extends StatefulWidget {
  const CContainerChanged({super.key});

  @override
  State&lt;CContainerChanged&gt; createState() =&gt; _CContainerChangedState();
}

class _CContainerChangedState extends State&lt;CContainerChanged&gt; {
  List&lt;Color&gt; containerColors = [
    Colors.cyanAccent,
    Colors.deepPurpleAccent,
    Colors.deepOrangeAccent,
  ];

  int? selectedIndex;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          for (int i = 0; i &lt; containerColors.length; i++)
            Container(
              width: 100,
              height: 100,
              color:  selectedIndex == i ? Colors.red : containerColors[i],
              child: TextButton(
                onPressed: () {
                  setState(() {
                    selectedIndex = i;
                  });
                },
                child: Text(&#39;Change color&#39;),
              ),
            ),
        ],
      ),
    ));
  }
}

答案2

得分: 0

使用**列表视图**的解决方案。我有5个容器,当点击容器小部件时,会更新当前索引并更改颜色。

```dart
class _MyHomePageState extends State<MyHomePage> {
  int currentIndex = 0;  // 保存用户点击的索引
  bool firstClick = false; // 检查标志,用于首次构建并保持项目颜色为白色

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView.builder(
            itemCount: 5,
            itemBuilder: (context, index) {
              return InkWell(
                  onTap: () {
                    setState(() {
                      this.currentIndex = index;
                      this.firstClick = true;
                    });
                  },
                  child: firstClick
                      ? currentIndex == index
                          ? Container(
                              // 固定高度的子项。
                              color: const Color(0xffeeee00), // 黄色
                              height: 100.0,
                              alignment: Alignment.center,
                              child: Text("内容 ${index}"),
                            )
                          : Container(
                              // 固定高度的子项。
                              color: Colors.lightBlue, // 蓝色
                              height: 100.0,
                              alignment: Alignment.center,
                              child: Text('内容 ${index}'),
                            )
                      : Container(
                          // 固定高度的子项。
                          color: Colors.white, // 白色
                          height: 100.0,
                          alignment: Alignment.center,
                          child: Text("内容 ${index}"),
                        ));
            }),
      ),
    );
  }
}

祝您有个愉快的一天 What is the way to change a property for several items at the same time with different values for one property, such as color, for example


<details>
<summary>英文:</summary>

my solution by using a **list view** I have 5 containers when clicking on the container widget will update the current Index and change color 

   

     class _MyHomePageState extends State&lt;MyHomePage&gt; {
      int currentIndex = 0;  // to save user click index 
      bool firstClick = false; // checking flag when first build and keep item color white 
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: ListView.builder(
                itemCount: 5,
                itemBuilder: (context, index) {
                  return InkWell(
                      onTap: () {
                        setState(() {
                          this.currentIndex = index;
                          this.firstClick = true;
                        });
                      },
                      child: firstClick
                          ? currentIndex == index
                              ? Container(
                                  // A fixed-height child.
                                  color: const Color(0xffeeee00), // Yellow
                                  height: 100.0,
                                  alignment: Alignment.center,
                                  child: Text(&quot;Content ${index}&quot;),
                                )
                              : Container(
                                  // A fixed-height child.
                                  color: Colors.lightBlue, // Yellow
                                  height: 100.0,
                                  alignment: Alignment.center,
                                  child: Text(&#39;Content ${index}&#39;),
                                )
                          : Container(
                              // A fixed-height child.
                              color: Colors.white, // Yellow
                              height: 100.0,
                              alignment: Alignment.center,
                              child: Text(&quot;Content ${index}&quot;),
                            ));
                }),
          ),
        );
      }
    }


Have Nice Day :)



</details>



huangapple
  • 本文由 发表于 2023年6月18日 21:35:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定