flutter_pagewise library does not preserve page (scroll) state on tabbing away - flutter

I am using the flutter_pagewise library and have implemented a paginated grid as per the library's documentation (following their example at https://pub.dev/packages/flutter_pagewise/example), which grabs placeholder images and text via the network.
In my app, I have 2 pages (one is called PaginatedGrid and the other is called SearchPage) that I can tab to via a BottomNavigationBar. However, when I tab to the SearchPage, then tab back to PaginatedGrid, the paginated grid scroll state isn't preserved. The pagination starts from the very beginning and the screen is scrolled back to the top.
import 'package:myproject/my_events/my_events_page.dart';
import 'package:myproject/search/search_page.dart';
import 'package:myproject/widget/paginated_grid.dart';
import 'package:flutter/material.dart';
class PageWrapper extends StatefulWidget {
#override
_PageWrapperState createState() => _PageWrapperState();
}
class _PageWrapperState extends State<PageWrapper> {
ScrollController _scrollController = ScrollController();
int _curIndex = 0;
List<Widget> _pages;
final bucket = PageStorageBucket();
final Key searchPageKey = PageStorageKey('searchKey');
final Key paginatedGridKey = PageStorageKey('paginatedGrid');
#override
void initState() {
_pages = [
PaginatedGrid(key: paginatedGridKey),
SearchPage(key: searchPageKey)
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageStorage(
bucket: bucket,
child: CustomScrollView(
key: PageStorageKey(_pages[_curIndex].runtimeType.toString()),
controller: _scrollController,
slivers: <Widget>[SliverAppBar(), _pages[_curIndex]],
),
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int i) {
setState(() {
_curIndex = i;
});
},
currentIndex: _curIndex,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Browse',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
)
],
),
);
}
}
Any help would be appreciated.

Using an indexedStack is a solution that worked! The paginated state is preserved on navigation to another tab from the bottom navigation bar.
Instead of using a PageStorage widget, use an IndexedStack widget.
#override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: currentTab,
children: pages,
),
bottomNavigationBar: BottomNavigationBar(
The solution is described here: https://medium.com/#codinghive.dev/keep-state-of-widgets-with-bottom-navigation-bar-in-flutter-bb732214bd11

Related

How to call init method or specific function again when we click on already activated bottom menu

I have implemented following BottomNavigation
class AppMenu extends StatefulWidget {
const AppMenu({Key? key}) : super(key: key);
#override
State<AppMenu> createState() => _AppMenuState();
}
class _AppMenuState extends State<AppMenu> {
int current = 0;
final List<String> titles = [
"Home 1",
"Home 2"
];
final List<Widget> views = [
const HomeView1(),
const HomeView2(),
];
final List<String> icons = [
"icon_1",
"icon_2",
];
final List<String> barTitles = ["Home1", "Home2"];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: HomeAppBar(
title: titles[current],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: (index) {
setState(() {
current = index;
});
},
selectedItemColor: const Color(0xff6B6B6B),
showUnselectedLabels: true,
showSelectedLabels: true,
unselectedItemColor: const Color(0xff6B6B6B),
selectedLabelStyle: const TextStyle(fontSize: 12),
unselectedLabelStyle: const TextStyle(fontSize: 12),
items: views.map((e) {
final itemIndex = views.indexOf(e);
return BottomNavigationBarItem(
icon: Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Image.asset(
"assets/images/${icons[itemIndex]}${itemIndex == current ? "" : "_disabled"}.png",
width: 25,
),
),
label: barTitles[itemIndex],
);
}).toList()),
body: Column(
children: [
Expanded(child: views[current]),
],
),
);
}
}
Now it works perfect when I click on home1 and home2 bottom menu and it shows respected widget and load all the content which I have wrote on initState of home1 and home2 but now assume that I am on home1 and if I click again home1 then it is not calling initState again.
I want to call initState or specific function if user click on that menu even if it is selected.
Is there any way to do it?
You can create a initialize or initXXX function to initialize something in initState or somewhere. If parent widget call setState(), then child widget will call didUpdateWidget().
void initialize() {
// do something
}
Call initialize() in initState().
void initState() {
super.initState();
initialize();
}
Call initialize() in didUpdateWidget() of page(child widget).
#override
void didUpdateWidget(covariant PageTest oldWidget) {
super.didUpdateWidget(oldWidget);
initialize();
}
To handle the case in a simple way. You can add your method in onTap of BottomNavigationBar and then pass your data down to the widget tree.
It's only a demonstration to handle your case, you can adjust it with your own liking
For example
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: (index) {
if(current == index){
foo = yourMethodHere();
}
setState(() {
current = index;
});
},
Pass the variable in the tree
List<Widget> get views => [
HomeView1(foo),
HomeView2(foo),
];

Flutter: Calling Function from another Class State

My app allows people to post text and switch between different pages on a navbar. On the users page, there is a button, when clicked, will show an overlay so the user can create a post. The overlay includes a back button that calls a function to close the overlay. I want to keep the navbar available at the bottom so user can back out of the post that way if they want to.
The problem is, when the user uses the navbar, the overlay does not close because the close overlay function is on the user page and the navbar page does not have access to it.
How do I give another class on another dart file access to a method or function? If you are able to answer, can you please use my code instead of another example to help me follow better? Thank you.
User Page File #1
class UserPage extends StatefulWidget {
#override
_UserPageState createState() => _UserPageState();
}
class _UserPageState extends State<UserPage> {
OverlayEntry? entry;
#override
Widget build(BuildContext context) {
return Scaffold(
ElevatedButton(
child: const Text('New Post'),
onPressed: showOverlay,
),
),
}
void showOverlay() {
(...)
}
void closeOverlay() {
entry?.remove();
entry = null;
}
}
Nav Bar File #2 (Need help with "OnTap")
class Nav extends StatefulWidget {
const Nav({Key? key}) : super(key: key);
#override
_NavState createState() => _NavState();
}
class _NavState extends State<Nav> {
int currentTab = 1; // makes the home page the default when loading up the app
#override
void initState() {
super.initState();
}
List<Widget> tabs = <Widget>[
const Other(),
const Home(),
const UserPage(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: tabs.elementAt(currentTab),
),
// BOTTOM NAVIGATION BAR
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentTab,
onTap: (value) {
setState(() => currentTab = value);
const _UserPageState().closeOverlay(); //HERE IS WHERE I NEED HELP WITH THE CODE
},
items: const [
BottomNavigationBarItem(
label: 'Other',
),
BottomNavigationBarItem(
label: 'Home',
),
BottomNavigationBarItem(
label: 'User Page',
),
],
),
);
}
}
You can try to make your _UserPageState public by removing - from it, and then call it UserPageState().closeOverlay();

Show Page with Specific List maintaining Bottom AppBar - Flutter

I am building an app with a bottom appbar with classic indexed pages to navigate the main menu:
class OverAllScreen extends StatefulWidget {
final int initialPage;
OverAllScreen(this.initialPage);
#override
_OverAllScreenState createState() => _OverAllScreenState();
}
class _OverAllScreenState extends State<OverAllScreen> {
List _pageOptions = [
Shop(),
Home(),
Discover(),
Account(),
];
int _page;
#override
void initState() {
super.initState();
setState(() {
_page = widget.initialPage;
});
}
#override
Widget build(BuildContext context) {
final _theme = Theme.of(context);
final _mediaSize = MediaQuery.of(context).size;
return Scaffold(
body: _pageOptions[_page],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: _theme.primaryColor,
selectedItemColor: _theme.accentColor,
unselectedItemColor: Colors.white,
currentIndex: _page,
onTap: (index) {
setState(() {
_page = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.shop), label: 'Shop'),
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Discover'),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline), label: 'Account'),
],
),
);
}
}
In the account page, further down the widget tree I have a widget that shows a list of detailed products.
I want this page to open up when I click on an item of a simple (non-detailed) grid of products.
This I can easily do with Navigator.of(context).push(MaterialPageR0ute(...))). However I would like to keep the bottomAppBAr visible (like instagram when you look at the products of a user).
The problem is that I have the specific list of products in down in the widget tree, so I can't pass them as an argument at the occount page level, without passing them back each step of the way by passing a function as an argument of the widget.
class ProductList extends StatelessWidget {
#override
Widget build(BuildContext context) {
var _products = Provider.of<List<ProductModel>>(context);
return ListView.builder(
itemExtent: 150,
scrollDirection: Axis.horizontal,
itemCount: _products.length,
itemBuilder: (context, index) => Card(
margin: const EdgeInsets.all(5),
child: InkWell(
child: ProductTile(_products[index]),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ProductDetailList(
productIndex: index,
products: _products,
),
),
),
),
),
);
}
}
Here I use MaterialPageRoute, but would like to keep BottomAppBar visible.
Thank you.
To achieve the functionality you are looking for, you would have to write several switch and break case which can be cumbersome as your use is going to be very basic.
What I would suggest is go for this package
This package provide a persistent bottom navigaton bar which is highly customisable and you could even use salmon like bottom bar without writing a single line of extra code.

How to navigate to one of the pages of BottomNavigationBar by clicking on a button present in the page in Flutter?

I have a bottom navigation bar in my flutter app which is used to show different pages. I need to click on a button in one of the pages to navigate to another which can also be navigated through the bottom navigation bar. To keep the state of the page i have used IndexedStack widget. also i highlight which page i am currently at.
How to do so.
Here is the code.
class IndexPage extends StatefulWidget {
#override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage>
with SingleTickerProviderStateMixin {
final ValueNotifier<int> pageNumberNotifier = ValueNotifier<int>(0);
final List<Widget> _widgets = <Widget>[
Page1(),
Page2(),
Page3(),
];
#override
void dispose() {
super.dispose();
pageNumberNotifier.dispose();
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: pageNumberNotifier,
builder: (BuildContext context, int pageNumber, Widget child) {
return SafeArea(
child: Scaffold(
body: IndexedStack(
index: pageNumberNotifier.value,
children: _widgets,
),
bottomNavigationBar: BottomNavigationBar(
showUnselectedLabels: true,
currentIndex: pageNumber,
onTap: (index) => pageNumberNotifier.value = index,
items: <BottomNavigationBarItem>[
bottomNavigationBarItem(
iconString: 'page1', index: 0, title: 'Page1'),
bottomNavigationBarItem(
iconString: 'page2', index: 1, title: 'Page2'),
bottomNavigationBarItem(
iconString: 'page3', index: 2, title: 'Page3'),
],
),
),
);
});
}
BottomNavigationBarItem bottomNavigationBarItem(
{String iconString, int index, String title}) {
//shows the icons and also highlights the icon of the current page based on the current index.
}
}
Here is the page that contains the button
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
...
onTap(){
// go to Page3 and also highlight Page3 icon in the bottom navigation bar
}
...
}
}
Use a GlobalKey
GlobalKey<_IndexPageState> key = GlobalKey();
make a function inside _IndexPageState:
void setPage(int page) {
pageNumberNotifier.value = page;
}
call this method from anywhere with:
key.currentState.setPage(0);

Flutter - Send params in Bottom Navigation Bar

I have two different pages. One of these is a form, the other is a list of elements. If you swipe one of the elements to left can edit. I need to send the element data (from the list) to first page (the form)
When the application starts the data is null, if it come from the element list isnĀ“t null.
The navigation bar code is:
import 'package:flutter/material.dart';
import 'package:datameter/screens/configuration/form/partials/home_page.dart';
import 'package:datameter/screens/configuration/list/datameters.dart';
import 'package:datameter/locations/locations.dart';
class Navigation extends StatefulWidget {
final item;
Navigation(
{Key key,
this.item})
: super(key: key);
#override
State<StatefulWidget> createState() {
return _NavigationState();
}
}
class _NavigationState extends State<Navigation> {
int currentIndex = 0;
List<Widget> children = [
HomePageScreen(datameter: widget.item), //ERRROR HERE
DatametersPageScreen(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: children[currentIndex],
bottomNavigationBar: new Theme(
data: Theme.of(context).copyWith(
primaryColor: Colors.blue[700],
textTheme: Theme.of(context)
.textTheme
.copyWith(caption: new TextStyle(color: Colors.black)),
),
child: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: currentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.add),
title: Text(DemoLocalizations.of(context).text('new-device')),
),
BottomNavigationBarItem(
icon: Icon(Icons.list),
title: Text(DemoLocalizations.of(context).text('show-all')),
),
],
)),
);
}
void onTabTapped(int index) {
setState(() {
currentIndex = index;
});
}
}
When I try to send params from elements list (using navigation bottom bar) to the form, returns
Static only members can be accessed in initializers.
Does anybody know how to fix this?
_NavigationState Object is not constructed so you cannot access "widget" getter yet because its not initialized and its not static property either.
change
List<Widget> children = [
HomePageScreen(datameter: widget.item), //ERRROR HERE
DatametersPageScreen(),
];
to
List<Widget> _children() =>
[
HomePageScreen(datameter: widget.item),
DatametersPageScreen(),
];
and then in your build change
#override
Widget build(BuildContext context)
{
final List<Widget> children = _children();
return Scaffold
(
//code
body: children[currentIndex],
//code
);
}