为什么在Flutter中对小部件列表使用setState不起作用

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

why setState not working for List of widgets in flutter

问题

我是Flutter新手,尝试使用Widget列表进行实验。我尝试在Widget列表内部更改状态,即在`initState`中初始化。我创建了一个示例来说明我的目标。

```dart
class Testing extends StatefulWidget {
  const Testing({super.key});

  @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  bool isChanged = false;
  List<Widget> simpleWidget = [];

  @override
  void initState() {
    simpleWidget = [_someComplexWidget(), _someComplexWidget()];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:const Text("Test"),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              child: Column(
                children: simpleWidget,
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    isChanged = !isChanged;
                  });
                },
                child: const Text("Click"))
          ],
        ),
      ),
    );
  }

  Widget _someComplexWidget() {
    return Text(
        "Hello",
        style: TextStyle(color: isChanged ? Colors.red : Colors.blue),
      );
  }
}

我也尝试使用了key,但在这个示例代码中没有起作用。何时使用Keys

这个代码不起作用的原因是什么。

英文:

I am new in flutter I try to experiment with List of Widget . I try to change state inside the list of widget i.e. initialized in initState . I create sample example to what I want to achieve.

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

  @override
  State&lt;Testing&gt; createState() =&gt; _TestingState();
}

class _TestingState extends State&lt;Testing&gt; {
  bool isChanged = false;
  List&lt;Widget&gt; simpleWidget = [];

  @override
  void initState() {
    simpleWidget = [_someComplexWidget(), _someComplexWidget()];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:const Text(&quot;Test&quot;),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              child: Column(
                children: simpleWidget,
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    isChanged = !isChanged;
                  });
                },
                child: const Text(&quot;Click&quot;))
          ],
        ),
      ),
    );
  }

  Widget _someComplexWidget() {
    return Text(
        &quot;Hello&quot;,
        style: TextStyle(color: isChanged ? Colors.red : Colors.blue),
      );
  }
}

I also try with keys but it did not work in this sample code. When to Use Keys

What is the reason behind not working this code.

答案1

得分: 1

因为你的simpleWidget是在initState中创建的,它在重建时不会改变。

你应该在build方法中添加[_someComplexWidget(), _someComplexWidget()],以便根据当前状态动态更改它。

class Testing extends StatefulWidget {
  const Testing({Key? key});

  @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  bool isChanged = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Test"),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              child: Column(
                children: [_someComplexWidget(), _someComplexWidget()], // 在这里
              ),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  isChanged = !isChanged;
                });
                print(isChanged);
              },
              child: const Text("Click"),
            ),
          ],
        ),
      ),
    );
  }

  Widget _someComplexWidget() {
    return Text(
      "Hello",
      style: TextStyle(color: isChanged ? Colors.red : Colors.blue),
    );
  }
}
英文:

Because your simpleWidget is created at initState & it will not change on rebuild.

You should add [_someComplexWidget(), _someComplexWidget()] under build for it to change dynamically based on the current state.

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

  @override
  State&lt;Testing&gt; createState() =&gt; _TestingState();
}

class _TestingState extends State&lt;Testing&gt; {
  bool isChanged = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(&quot;Test&quot;),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              child: Column(
                children: [_someComplexWidget(), _someComplexWidget()], // HERE
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    isChanged = !isChanged;
                  });
                  print(isChanged);
                },
                child: const Text(&quot;Click&quot;))
          ],
        ),
      ),
    );
  }

  Widget _someComplexWidget() {
    return Text(
      &quot;Hello&quot;,
      style: TextStyle(color: isChanged ? Colors.red : Colors.blue),
    );
  }
}

huangapple
  • 本文由 发表于 2023年2月8日 12:21:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381354.html
匿名

发表评论

匿名网友

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

确定