【问题标题】:Flutter: How to avoid ListView to scroll (or change its physics) dynamicallyFlutter:如何避免 ListView 动态滚动(或更改其物理特性)
【发布时间】:2019-10-10 23:20:45
【问题描述】:

我有一个ListView 小部件,我希望它可以根据某些逻辑滚动或不滚动。

NeverScrollableScrollPhysics 阻止滚动,但由于物理参数是最终的,我之后无法更改它。

我想使用状态来使用不同的物理来重建 ListView,但我想重建整个 ListView 是一个相当繁重的操作。

有谁知道或如何处理这种情况,即用户在完成其他用户操作之前不应滚动 ListView?

【问题讨论】:

  • 改变物理是一个好方法,但是如果你想使用不同的方法,那么你应该使用 ScrollController,它可能会起作用。您可以在其中设置偏移量为零。

标签: flutter flutter-animation


【解决方案1】:

更改physics 并使用setState 应该可以解决问题,如果您不想使用它,可以使用Stack 小部件并将Container 放在ListView 上方以避免交互,检查我制作的这个样本:

  class _MySampleWidgetState extends State<MySampleWidget> {
    bool scrollEnabled = true;

    @override
    Widget build(BuildContext context) {
      return Column(
        children: [
          Expanded(
            child: Center(
              child: RaisedButton(
                onPressed: () {
                  setState(() {
                    scrollEnabled = !scrollEnabled;
                  });
                },
                child: Text("Update"),
              ),
            ),
          ),
          Expanded(
            child: Stack(
              children: [
                ListView.builder(
                  shrinkWrap: true,
                  itemBuilder: (_, index) => ListTile(
                        title: Text("index: $index"),
                      ),
                ),
                if (!scrollEnabled)
                  Container(
                    color: Colors.transparent,
                  ),
              ],
            ),
          ),
        ],
      );
    }
  }

【讨论】:

【解决方案2】:

您可以在 ListView 中有条件地应用物理:

shrinkWrap: true,
physics: !isScrolable? const NeverScrollableScrollPhysics(): 
         const AlwaysScrollableScrollPhysics(),

然后,当您需要时,您可以更改状态以修改变量的值。


setState(() {
    isScrolable = !isScrolable;
}); 

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2019-12-31
    • 1970-01-01
    • 2023-02-15
    • 2018-06-03
    • 2019-09-30
    • 2021-12-26
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多