简体   繁体   English

Flutter - 如何在ListView.separated的顶部插入有状态小部件?

[英]Flutter - How to insert stateful widget at the top of a ListView.separated?

I have a ListView.separated which initially contains two stateful widgets that say: Hello 2 and Hello 3 . 我有一个ListView.separated ,它最初包含两个有状态的小部件: Hello 2Hello 3

After some time, I want to insert a stateful widget saying Hello 1 at the top of the ListView.separated . 一段时间后,我想在ListView.separated的顶部插入一个有状态的小部件,上面写着Hello 1

I expect the ListView.separated to show Hello 1 , Hello 2 , Hello 3 . 我希望ListView.separated显示Hello 1Hello 2Hello 3

Unfortunately, when I do this, Hello 3 gets duplicated instead of Hello 1 getting added to the top of the ListView.separated . 不幸的是,当我这样做时, Hello 3会被重复而不是Hello 1被添加到ListView.separated的顶部。 It now shows Hello 2 , Hello 3 , Hello 3 . 它现在显示Hello 2Hello 3Hello 3

All of this works fine if I use stateless widgets. 如果我使用无状态小部件,所有这一切都可以正常工作。 If I use StatefulWidget , the order gets messed up and widgets get duplicated. 如果我使用StatefulWidget ,则命令会搞砸,并且小部件会被复制。

You can try this. 你可以试试这个。

bool _condition = false;

Widget build(context) {
  return ListView(
    children: <Widget>[
      _condition ? yourNewWidget : Container(),
      ListView.separated(
        shrinkWrap: true, // needed 
        physics: ClampingScrollPhysics(), // needed 
        itemBuilder: (c, i) => Text("Text = ${i}"),
        separatorBuilder: (c, i) => Divider(),
        itemCount: 100,
      )
    ],
  )
}

When you have a newWidget up and ready make sure you call setState(()) to update build() method. 当你有一个newWidget并准备就绪时,请确保调用setState(())来更新build()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM