skip to Main Content

I have a scroll controller in my provider. I want to know if I make the provider ‘autoDispose’, When the provider eventually gets auto disposed, does this dispose the controller within the provider to ? Or do I still need to dispose the scrollController.

Sample code:

import 'package:flutter_riverpod/flutter_riverpod.dart';

final myProvider = Provider.autoDispose(
  (ref) {
    return MyNotifier();
  },
);

class MyNotifier{
  final scrollController = ScrollController(initialScrollOffset: 5.0);
}

2

Answers


  1. To make the scrollcontroller disposed when the provider is disposed you should use the provider onDispose method.

    The function inside autoDispose is called when the provider is disposed of. Inside the function then you can dispose your controller

        final myProvider = Provider.autoDispose(
          (ref) {
            final controller = ScrollController(initialScrollOffset: 5.0);
    
            ref.onDispose(() {
              controller.dispose();
            });
    
            return MyNotifier(scrollController: controller);
          },
        );
    
        class MyNotifier {
          final ScrollController scrollController;
    
          MyNotifier({required this.scrollController});
        }
    
    Login or Signup to reply.
  2. You should not be placing anything to do with the view layer into Riverpod providers. Riverpod is for the data layer and the control layer, not the view layer, and a ScrollController or TextEditingController should never be in a Riverpod provider. Those controllers belong in single-widget state, either via a StatefulWidget, or by using flutter_hooks to create a hidden StatefulElement to observe widget lifecycles.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search