flutterflutter-animationriverpodflutter-riverpod

TabController and Riverpod?


I would like to display the AsyncValue result from a Riverpod StatenotifierProvider in a TabControl. In a StatefulWidget I would have implemented the TabController like so:

class Screen extends StatefulWidget {
  Screen({Key? key}) : super(key: key);

  @override
  State<Screen> createState() => _ScreenState();
}

class _ScreenState extends State<Screen> with TickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

If I convert this widget to a ConsumerWidget I can no longer mix in the TickerProvider and if I stick with the StatefulWidget I don't have access to the ref and therby the provider.

Would appreciate you help!


Solution

  • You can use ConsumerStatefulWidget to access ref (and use TickerProviderStateMixin mixin) in this way:

    class Screen extends ConsumerStatefulWidget {
      const Screen({super.key});
    
      @override
      _ScreenState createState() => _ScreenState();
    }
    
    class _ScreenState extends ConsumerState<Screen> with TickerProviderStateMixin {
    
      late final TabController _tabController;
    
      @override
      void initState() {
        super.initState();
    
        // "ref" can be used in all life-cycles of a StatefulWidget.
        ref.read(currentIndexProvider);
    
        _tabController = TabController(length: 2, vsync: this);
      }
    
      @override
      Widget build(BuildContext context) {
        final index = ref.watch(currentIndexProvider);
        return Text('$index');
      }
    
      @override
      void dispose() {
        _tabController.dispose();
        super.dispose();
      }
    }
    

    More info ConsumerStatefulWidget.