Flutter: 如何在初始化的小部件列表中动态更改颜色

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

Flutter: How to change dynamically the color in initialized widget list

问题

如何在初始化的小部件列表中动态更改颜色?

我有一个预先初始化的Widgetlist,并且我想在用户按下它时更改其背景颜色。
使用_counter % 2 == 1 ? Colors.green : Colors.red 不起作用。
通过函数来改变颜色会导致相同的问题。

我的完整代码:查看 _initMyList()

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Widget> _aMyList = [];

  _initMyList() {
    for (int i = 0; i < 5; i++) {
      Text text = new Text("Item " + i.toString());
      GestureDetector gestureDetector = new GestureDetector(onTap: () => {_callback()}, child: text);
      // ======== 如何更改颜色?
      Container container = new Container(alignment: Alignment.center, child: gestureDetector, color: _counter % 2 == 1 ? Colors.green : Colors.red);
      SizedBox sizedBox = new SizedBox(width: 60, height: 40, child: container);
      _aMyList.add(sizedBox);
    }
  }

  void _callback() {
    setState(() {
      _counter++;
    });
  }

  void initState() {
    super.initState();
    _initMyList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: _aMyList
        ),
      ),
    );
  }
}
英文:

How to change dynamically the color in initialized widget list?<br/>
<br/>
I have a pre initialized Widgetlist, and I want to change its background color while the user is pressing it<br/>
To use the _counter % 2 == 1 ? Colors.green : Colors.red dosn't function.<br/>
To change the color over a function is resulting in the same problem.<br/>
<br/>
My complete code: see _initMyList()<br/>
<br/>
<br/>

import &#39;package:flutter/material.dart&#39;;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: &#39;Flutter Demo&#39;,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  int _counter = 0;
  List&lt;Widget&gt; _aMyList = [];

  _initMyList() {
    for (int i = 0; i &lt; 5; i++) {
      Text text = new Text(&quot;Item &quot; + i.toString());
      GestureDetector gestureDetector = new GestureDetector(onTap: () =&gt; {_callback()}, child: text);
      // ======== How to change the color ?
      Container container = new Container(alignment: Alignment.center, child: gestureDetector, color: _counter % 2 == 1 ? Colors.green : Colors.red);
      SizedBox sizedBox = new SizedBox(width: 60, height: 40, child: container);
      _aMyList.add(sizedBox);
    }
  }

  void _callback() {
    setState(() {
      _counter++;
    });
  }

  void initState() {
    super.initState();
    _initMyList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: _aMyList
        ),
      ),
    );
  }
}

答案1

得分: 1

为什么要为此创建如此复杂的逻辑?

只需简单地添加List.generate以生成列表的动态长度。

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  mainAxisSize: MainAxisSize.min,
  children: List.generate(
    5,
    (index) => SizedBox(
      width: 60,
      height: 40,
      child: GestureDetector(
        onTap: () {
          setState(() {
            _counter++;
          });
        },
        child: Container(
          alignment: Alignment.center,
          color: _counter % 2 == 1 ? Colors.green : Colors.red,
        ),
      ),
    ),
  ),
)

请用您的Column小部件替换上述片段。

英文:

Why are you creating such complex logic for it?

Need to simply add List.generate for generating the dynamic length of the list.

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: List.generate(
            5,
            (index) =&gt; SizedBox(
              width: 60,
              height: 40,
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _counter++;
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  color: _counter % 2 == 1 ? Colors.green : Colors.red,
                ),
              ),
            ),
          ),
        )

Replace the Above snippet with your Column widget.

huangapple
  • 本文由 发表于 2023年5月29日 21:48:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357918.html
匿名

发表评论

匿名网友

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

确定