sooxt98 / google_nav_bar

A modern google style nav bar for flutter.
MIT License
749 stars 114 forks source link

Updating selectedIndex does not update the index #48

Closed JagandeepBrar closed 3 years ago

JagandeepBrar commented 3 years ago

Previously on 4.0.2, if I called setState() on a value passed to GNav, it would also animate the tab to the new index. This no longer works with 5.0.1.

A quick example where I use a PageController listener to update _index:

int _index;

@override
void initState() {
    _index = widget.pageController?.initialPage ?? 0;
    widget.pageController?.addListener(_pageControllerListener);
    super.initState();
}

@override
void dispose() {
    widget.pageController?.removeListener(_pageControllerListener);
    super.dispose();
}

void _pageControllerListener() {
    setState(() => _index = widget.pageController.page.round());
}

@override
Widget build(BuildContext context) => GNav(
    selectedIndex: _index,
    ... // Additional GNav parameters
);

The initially selected index is correct, but just does not update unless you tap on the GButton in the navigation bar.

sooxt98 commented 3 years ago

@JagandeepBrar Gotchas! I think this is is due to the null-safety refactor by @Ascenio and i never do actual testing

image

I think i would simply move back the

selectedIndex = widget.selectedIndex;

back into build function to solve this issue, without having to use didUpdateWidget

Ascenio commented 3 years ago

I'm sorry for introducing this bug, but I don't think we should have logic into build method which could be moved elsewhere. I don't think the index should be updated at each build, that's why I changed so it would only be set at initState.

Anyway. Fortunately @JagandeepBrar made a change which I checked already and it seems to be working.

JagandeepBrar commented 3 years ago

As @Ascenio mentioned, the more "correct" way is to not update values constantly within the build function, and instead use didUpdateWidget as used in the pull request I have opened 🙂

sooxt98 commented 3 years ago

Released https://pub.dev/packages/google_nav_bar/versions/5.0.2