Home > Back-end >  Flutter - something in pageController is null inside a Consumer widget
Flutter - something in pageController is null inside a Consumer widget

Time:06-30

I am using hooks_riverpod package and am experiencing an error while trying to access pageController's methods from inside a Consumer widget.
The same method calls work from anywhere else in the file.

This is the error:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following TypeErrorImpl was thrown building Consumer(dirty, dependencies:
[UncontrolledProviderScope], state: _ConsumerState#bb6a0):
Unexpected null value.
The relevant error-causing widget was:
  Consumer
Consumer:file:///C:/Users/_/_/lib/src/_/test.dart:38:9

Here is a very simplified code that throws the same error:

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../providers/testProvider.dart';

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

  @override
  _TestScreenState createState() {
    return _TestScreenState();
  }
}

class _TestScreenState extends State<TestScreen> {
  final PageController pageController = PageController(
    initialPage: 0,
  );

  final testProvider = TestProvider.instance;

  @override
  Widget build(BuildContext context) {
    final _pages = [
      Container(),
      Container(),
    ];
    return Scaffold(
        body: Stack(
      children: <Widget>[
        Consumer(builder: (context, ref, child) {
          return PageView(
            children: _pages,
            scrollDirection: Axis.vertical,
            controller: pageController,
          );
        }),
        Consumer(builder: (context, ref, child) {
          final pageIndex = ref.watch(testProvider).getPageIndex;
          pageController.animateToPage(pageIndex,
              duration: Duration(microseconds: 100), curve: Curves.bounceIn);
          return GestureDetector(
            child: Column(
              children: [],
            ),
          );
        }),
      ],
    ));
  }
}

The problematic line here is the pageController.animateToPage(...) call on line 40, as it works fine without it.
And here is the provider:

import 'package:flutter/cupertino.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class TestProvider extends ChangeNotifier {
  static var instance = ChangeNotifierProvider(((ref) => TestProvider()));

  TestProvider({this.pageIndex = 1});

  int pageIndex;

  int get getPageIndex => pageIndex;

  void setPageIndex(int pageIndexInput) {
    pageIndex = pageIndexInput;
    notifyListeners();
  }
}

I am able to access the pageController.initialPage, but not any method and cannot figure out what is the unexpected null value, as it is not the pageController itself.

Any help would be greatly appreciated.

CodePudding user response:

You should not call animate method inside the build method of the Consumer. This may be triggering unwanted rebuilds and throwing some abnormal states and resulting in error.

Try calling the pageController.animateToPage method in the place where you call TestProvider.setPageIndex.

  • Related