Flutter:如何避免 ListView 动态滚动(或改变其物理特性)

Flutter: How to avoid ListView to scroll (or change its physics) dynamically

我有一个 ListView 小部件,我想根据某些逻辑允许它滚动或不滚动。

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

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

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

更改 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,
                  ),
              ],
            ),
          ),
        ],
      );
    }
  }

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

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

然后当你需要的时候你可以改变状态修改你的变量的值。


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