Search code examples
flutterkeyboardflutter-providerflutter-pageview

Unusual bug due to keyboard in Flutter PageView


My Flutter Android app has a homepage that consists of a Scaffold with a PageView as its body. The PageView has two pages: page one some newsfeed, page two a calendar. Each page has its own custom FloatingActionButton. A ChangeNotifierProvider handles page changes, so that the FAB changes when the page index changes. The FAB on the second page is only shown if the user of the app has admin rights, something that is stored in a second ChangeNotifierProvider. In pseudo-code, the FAB handler looks something like this:

if (pageIndex == 0) {
  return NewsFeedFAB;
}
if (pageIndex == 1) {
  if (context.watch<UserDataModel>().currentUser.customClaims.admin) { // important line
    return CalendarFAB;
  } else {
    return null;
  }
}

Now comes my issue. When opening the app, I can swipe the pages without a problem. Everything works as intended. However, when I open the keyboard on the newsfeed page (which is possible since users can write comments on posts) and then try to swipe to the second page, I get an error: The getter 'admin' was called on null. (see 'important line' in the code). I should note that the pageIndexChangeHandler unfocuses the focusnode when the index changes to dismiss the keyboard. I thought this might be relevant to the issue, but if I let the keyboard appear and then dismiss it manually and then swipe after that, the same error happens.

It seems like activating the keyboard somehow messes up the ChangeNotifierProdiver UserDataModel. It is a very niche error it seems, so any help would be appreciated!


Solution

  • The error implies to me that

    context.watch<UserDataModel>().currentUser.customClaims
    

    can be null. Why might it be null? Can't say without seeing the code but there are different ways to address the issue.

    1. Make a member variable of the State, bool? _isAdmin, assign it from initState() and, if it is a changeable property, listen there for changes.

    2. Simply check for null before calling admin.

    Why this might be happening with keyboard is a hard one. I suspect that something about the rebuild process after the keyboard enters is not recalling customClaims and because the value is not saved in a member variable you end up with null.