1

I've built a Scaffold screen with a PageView in the body and a bottomNavigationBar.

I've also built a Cubit + State manager for this page.

When the screen first opens up I want an API call to be triggered. I also want tab 1 to be selected (on both the PageView and the bottomNavigationBar). When the API returns a response, I want an event listener to update the screen and select tab 0.

This works well for the bottomNavigationBar but I'm having issues updating my PageView. Here is my code:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _page = 1;
  PageController _c;
  double iconSize = 32;
  bool forceCourseEnrolment = true;

  @override
  void initState() {
    _c = new PageController(
      initialPage: 1,
      keepPage: false,
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<HomeScreenCubit, HomeScreenState>(
        listener: (context, state) {
      debugPrint("listener received something");
      if (state is DataRetrieved) {
        state.enrolledCourses.length > 0
            ? forceCourseEnrolment = false
            : forceCourseEnrolment = true;
        state.enrolledCourses.length > 0 ? _page = 0 : _page = 1;
        var hasClients = this._c.hasClients;
        debugPrint("this._c.hasClients $hasClients");
        // This prints: this._c.hasClients false
        // Enabling this line:
        // this._c.jumpToPage(_page);
        // leads to:
        // [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:flutter/src/widgets/scroll_controller.dart': Failed assertion: line 112 pos 12: '_positions.isNotEmpty': ScrollController not attached to any scroll views.
      } 
    }, builder: (context, state) {
      if (state is HomeScreenInitial) {
        context.bloc<HomeScreenCubit>().retrieveData();
        return Scaffold(
            body: SpinKitChasingDots(
          color: COLOR_main_purple,
          size: 50.0,
        ));
      }
      return Scaffold(
          body: PageView(
            controller: _c,
            onPageChanged: (newPage) {
              setState(() {
                this._page = newPage;
              });
            },
            physics: NeverScrollableScrollPhysics(),
            children: [
              PurchasedCoursesTab(),
              ElearningTab(),
              MyPracticeTab(),
              ProfileTab(),
            ],
          ),
          bottomNavigationBar: SizedBox(
            height: 80,
            child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(30),
                      topLeft: Radius.circular(30)),
                  boxShadow: [
                    BoxShadow(
                        color: Colors.black38.withOpacity(0.1),
                        spreadRadius: 0,
                        blurRadius: 25),
                  ],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30.0),
                    topRight: Radius.circular(30.0),
                  ),
                  child: BottomNavigationBar(
                    currentIndex: _page,
                    onTap: (index) {
                      if (forceCourseEnrolment == false) {
                        this._c.animateToPage(index,
                            duration: const Duration(milliseconds: 250),
                            curve: Curves.easeInOut);
                      }
                    },
                    type: BottomNavigationBarType.fixed,
                    backgroundColor: Colors.white,
                    items: <BottomNavigationBarItem>[
                      BottomNavigationBarItem(
                          // title: Text(""),
                          title: showIndicator(_page == 0),
                          icon: Container(
                            width: iconSize,
                            height: iconSize,
                            child: SvgPicture.asset('assets/images/ic_run.svg',
                                color: _page == 0
                                    ? COLOR_main_purple
                                    : forceCourseEnrolment == false
                                        ? Colors.black
                                        : COLOR_main_text_grey_with_opacity),
                          )),
                      BottomNavigationBarItem(
                          title: showIndicator(_page == 1),
                          icon: Container(
                            width: iconSize,
                            height: iconSize,
                            child: SvgPicture.asset(
                                'assets/images/ic_e_learning.svg',
                                color: _page == 1
                                    ? COLOR_main_purple
                                    : Colors.black),
                          )),
                      BottomNavigationBarItem(
                          title: showIndicator(_page == 2),
                          icon: Container(
                            width: iconSize,
                            height: iconSize,
                            child: SvgPicture.asset(
                                'assets/images/ic_journal.svg',
                                color: _page == 2
                                    ? COLOR_main_purple
                                    : forceCourseEnrolment == false
                                        ? Colors.black
                                        : COLOR_main_text_grey_with_opacity),
                          )),
                      BottomNavigationBarItem(
                          title: showIndicator(_page == 3),
                          // title: Text(_page == 3 ? "•" : "", style: TextStyle(
                          //     color: COLOR_main_purple, fontSize: 24.0)),
                          icon: Container(
                            width: iconSize,
                            height: iconSize,
                            child: SvgPicture.asset(
                                'assets/images/ic_gamification.svg',
                                color: _page == 3
                                    ? COLOR_main_purple
                                    : forceCourseEnrolment == false
                                        ? Colors.black
                                        : COLOR_main_text_grey_with_opacity),
                          )),
                    ],
                  ),
                )),
          ));
    });
  }
}

The error that I'm facing when I try to change page in the listener of the BlocConsumer:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:flutter/src/widgets/scroll_controller.dart': Failed assertion: line 112 pos 12: '_positions.isNotEmpty': ScrollController not attached to any scroll views.

Rutger Huijsmans
  • 2,330
  • 2
  • 30
  • 67

2 Answers2

0

Found out I can make it work by adding the following to the listener:

  if (state is DataRetrieved) {
    state.enrolledCourses.length > 0
        ? forceCourseEnrolment = false
        : forceCourseEnrolment = true;
    state.enrolledCourses.length > 0 ? _page = 0 : _page = 1;
    Future.delayed(Duration(milliseconds: 50), () {
      if (this._c.hasClients) {
        this._c.jumpToPage(_page);
      }
    });
  } 

I find this an ugly solution so I won't mark this as the answer. Please let me know if you know a better way to handle this.

Rutger Huijsmans
  • 2,330
  • 2
  • 30
  • 67
0

You can try remove this code ? If you need show a loading, you can try add it inside PurchasedCoursesTab.

      if (state is HomeScreenInitial) {
        context.bloc<HomeScreenCubit>().retrieveData();
        return Scaffold(
            body: SpinKitChasingDots(
              color: COLOR_main_purple,
              size: 50.0,
            ));
      }

This issue happen because on this time your PageController is not attach to PageView.

dangngocduc
  • 1,588
  • 8
  • 13