6

I have a ListView widget and i would like to allow it to be scrollable or not based on some logic.

NeverScrollableScrollPhysics prevents scrolling, but since physics parameter is final i can't change it afterwards.

I thought to use state to rebuild the ListView using different physics, but i guess is a quite heavy operation to rebuild the entirely ListView.

Does anyone knows or how to deal with this situation, where the user should not scroll a ListView until other user action got accomplished?

lbodevan
  • 123
  • 1
  • 1
  • 9
  • 1
    Changing the Physics is a good way but If you want to use a different way then you should use ScrollController, it might work. where you can set offset zero. – satish May 24 '19 at 11:27

2 Answers2

7

You can apply the physics conditionally in your ListView:

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

Then when you need you can change the state modifying the value of your variable.


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

2

Changing physics and using setState should do the trick, in case you don't want to use that, you can use Stack widget and put a Container above your ListView to avoid interaction, check this sample I made:

  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,
                  ),
              ],
            ),
          ),
        ],
      );
    }
  }
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • @diegoverloper , could you please help me on this ? I'm new in flutter. https://stackoverflow.com/questions/69795503/flutter-nested-list-scroll-parent-when-reach-to-end-start-of-inner-list – Jamshed Alam Nov 10 '21 at 07:21