Flutter: Add new pages in pageview while swiping - flutter

How is it possible to add new page in pageview widget while I am swiping ?
I tried to setstate after animation and adding new page in list but it doesn't works.

Try this snippet:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
List<String> _list = ['test', 'test', 'test'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TabBar Demo'),
),
body: PageView.builder(
onPageChanged: (index) {
_list.add('test');
setState(() {});
},
itemCount: _list.length,
itemBuilder: (context, index) {
return Center(
child: Container(
child: Text(
_list[index],
),
),
);
},
),
);
}
}

import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
PageController _pageController = PageController(
initialPage: 0,
);
int currentIndex = 0;
Widget childWidget = ChildWidget(
number: AvailableNumber.First,
);
#override
void dispose() {
_pageController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Theme.of(context).primaryColor,
unselectedItemColor: Colors.grey[500],
currentIndex: currentIndex,
onTap: (value) {
currentIndex = value;
_pageController.animateToPage(
value,
duration: Duration(milliseconds: 200),
curve: Curves.linear,
);
setState(() {});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("First"),
),
BottomNavigationBarItem(
icon: Icon(Icons.trending_up),
title: Text("Second"),
),
BottomNavigationBarItem(
icon: Icon(Icons.dashboard),
title: Text("Third"),
),
BottomNavigationBarItem(
icon: Icon(Icons.dashboard),
title: Text("Third"),
),
],
),
body: PageView(
controller: _pageController,
onPageChanged: (page) {
setState(() {
currentIndex = page;
});
},
children: <Widget>[
Text('1'),
Text(2'),
Text('3'),
],
),
);
}
}
video example

Related

Flutter Setstate called multiple times (GestureDetector & PageView)

basically I have a swiping screen with elements, where user is able to swipe in left or right direction. When the user is swiping, im calling some functions. Im using GestureDetector for gesture recognitions and PageView.Custom for my items. Probably ListView.Custom does also work, but it doesn't fix my issue I have.
I need a PageController, because I have to control the navigation programatically. And I think the PageController maybe is the reason behind my issue that my functions are called multiple times. How to fix it? Does somebody know why setstate is called that often and what to do to prevent it?
Im providing you a fully working example (minified version) with a print on the swiping right actions, where you can see that its beeing called multiple times.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentIndex = 0;
#override
Widget build(BuildContext context) {
// Page selector for tab list
void _selectPage(int index) {
print('page index: $index');
setState(() {
currentIndex = index;
});
}
// Routes list for tab navigation Android
final List<Widget> _pages = [
ScreenA(),
ScreenB(func: _selectPage),
];
return Scaffold(
appBar: AppBar(),
body: _pages[currentIndex],
bottomNavigationBar: SafeArea(
child: BottomNavigationBar(
onTap: _selectPage,
iconSize: 22,
currentIndex: currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.description),
label: 'ScreenA',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.ac_unit_outlined),
label: 'ScreenB'),
],
),
),
);
}
}
class ScreenA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Text('HOME'),
);
}
}
class ScreenB extends StatefulWidget {
Function func;
ScreenB({Key key, #required this.func})
: super(key: key);
#override
_ScreenBState createState() => _ScreenBState();
}
class _ScreenBState extends State<ScreenB> {
_ScreenBState();
var _controller = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(Icons.access_alarm_sharp),
onPressed: () async {
widget.func(0);
},
),
],
),
body: PageView.custom(
dragStartBehavior: DragStartBehavior.start,
controller: _controller,
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
childrenDelegate: SliverChildBuilderDelegate((ctx, pageIndex) =>
GestureDetector(
onPanUpdate: (details) async {
if (details.delta.dx < 0) {
_controller.nextPage(
duration: Duration(milliseconds: 200),
curve: Curves.easeInOut);
print('function called');
}
},
child: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
child: Text('hi')))))),
);
}
}
Thanks in advance!
The problem is that you are using the onPanUpdate method, which is triggered every time a user drags their finger either right or left. You should use the onPanEnd method, which is only triggered when the user's finger is off the screen after dragging either left or right. The function below will work fine.
onPanEnd: (details) async { if (details.velocity.pixelsPerSecond.dx < 0) { _controller.nextPage( duration: Duration(milliseconds: 200), curve: Curves.easeInOut); print('function called'); } }
Please write this function out of widget build function
// Page selector for tab list
void _selectPage(int index) {
print('page index: $index');
setState(() {
currentIndex = index;
});
}
like this
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentIndex = 0;
// Page selector for tab list
void _selectPage(int index) {
print('page index: $index');
setState(() {
currentIndex = index;
});
}
// Routes list for tab navigation Android
final List<Widget> _pages = [
ScreenA(),
ScreenB(func: _selectPage),
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: _pages[currentIndex],
bottomNavigationBar: SafeArea(
child: BottomNavigationBar(
onTap: _selectPage,
iconSize: 22,
currentIndex: currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.description),
label: 'ScreenA',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.ac_unit_outlined),
label: 'ScreenB'),
],
),
),
);
}
}
class ScreenA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Text('HOME'),
);
}
}
class ScreenB extends StatefulWidget {
Function func;
ScreenB({Key key, #required this.func})
: super(key: key);
#override
_ScreenBState createState() => _ScreenBState();
}
class _ScreenBState extends State<ScreenB> {
_ScreenBState();
var _controller = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(Icons.access_alarm_sharp),
onPressed: () async {
widget.func(0);
},
),
],
),
body: PageView.custom(
dragStartBehavior: DragStartBehavior.start,
controller: _controller,
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
childrenDelegate: SliverChildBuilderDelegate((ctx, pageIndex) =>
GestureDetector(
onPanUpdate: (details) async {
if (details.delta.dx < 0) {
_controller.nextPage(
duration: Duration(milliseconds: 200),
curve: Curves.easeInOut);
print('function called');
}
},
child: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
child: Text('hi')))))),
);
}
}

AutomaticKeepAliveClientMixin not working with a BottomNavigationBar Page

I'm trying to keep only one page alive, but it doesn't work. I have all the required stuff.
added the with AutomaticKeepAliveClientMixin<PageName>
added the #override bool get wantKeepAlive => true; at the end
added the super.build(context); inside the build
Here's the code of the Page with the AutomaticKeepAliveClientMixin:
class MatchingPage extends StatefulWidget {
//
static final id = 'match';
//
#override
_MatchingPageState createState() => _MatchingPageState();
}
class _MatchingPageState extends State<MatchingPage> with AutomaticKeepAliveClientMixin<MatchingPage> {
#override
void initState() {
super.initState();
print('MATCHING PAGE');
print(User.uid);
}
#override
Widget build(BuildContext context) {
super.build(context);
setState(() {
screenHeight = MediaQuery.of(context).size.height;
screenWidth = MediaQuery.of(context).size.width;
});
return ModalProgressHUD(
inAsyncCall: showSpinner,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.white.withOpacity(0.10),
statusBarIconBrightness: Brightness.dark),
child: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Text('MatchPage'),
),
),
),
);
}
#override
bool get wantKeepAlive => true;
}
And here's the code of the Page that has the BottomNavBar:
List<Widget> _pages = [ProfilePage(), MatchingPage(), ChatsPage()];
class HomePage extends StatefulWidget {
//
static String id = 'home';
//
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//
int pageIndex = 1;
//
#override
Widget build(BuildContext context) {
return CustomScaffoldWithNavBar(
statusBarColor: Colors.white,
statusBarIconBrightness: Brightness.dark,
backgroundColor: Colors.white,
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.white,
currentIndex: pageIndex,
selectedItemColor: Colors.balck,
unselectedItemColor: _kAppIconGray,
type: BottomNavigationBarType.fixed,
showSelectedLabels: false,
showUnselectedLabels: false,
items: [
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
],
onTap: (int index) {
setState(() => pageIndex = index);
},
),
child: _pages[pageIndex],
);
}
}
Try to use PageView. The PageView widget wraps the current pages with PageStorage, and should keep the page state
List<Widget> _pages = [ProfilePage(), MatchingPage(), ChatsPage()];
class HomePage extends StatefulWidget {
//
static String id = 'home';
//
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//
int pageIndex = 1;
PageController _pageController;
//
#override
void initState() {
_pageController = PageController(initialPage: pageIndex, keepPage: true);
super.initState();
}
#override
Widget build(BuildContext context) {
return CustomScaffoldWithNavBar(
statusBarColor: Colors.white,
statusBarIconBrightness: Brightness.dark,
backgroundColor: Colors.white,
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.white,
currentIndex: pageIndex,
selectedItemColor: Colors.balck,
unselectedItemColor: _kAppIconGray,
type: BottomNavigationBarType.fixed,
showSelectedLabels: false,
showUnselectedLabels: false,
items: [
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
BottomNavigationBarItem(icon: Icon(...), title: Text('')),
],
onTap: (int index) {
setState(() {
pageIndex = index;
_pageController.jumpToPage(index);
} );
},
),
child: PageView(
physics: NeverScrollableScrollPhysics(),
controller: _pageController,
children: _pages,
),
);
}
}

Flutter: value of currentIndex property in BottomNavigationBar doesn't update when the state updates

I have a BottomNavigationBar that navigates to other pages when pressing an icon. This works fine, except the value of the currentIndex property in BottomNavigationBar doesn't update when the state updates, which means there is no change on the acual BottomNavigationBar. enter image description here
I'm using a vaiable (_selectedPage) to keep track of the selected index in the BottomNavigationBar, and the value changes when tapping an item, but it's not updating the currentIndex property when the state updates.. why is that?
import 'package:flutter/material.dart';
import 'package:independentproject/pages/home_page.dart';
import 'package:independentproject/pages/cook_recipe.dart';
class PageNavigationBar extends StatefulWidget {
#override
_PageNavigationBarState createState() => _PageNavigationBarState();
}
class _PageNavigationBarState extends State<PageNavigationBar> {
//default page showing in bottom navigation bar will be CookRecipe()
int _selectedPage = 1;
//all pages optional in bottom navigation bar
final List<Widget> _pageOptions = [
HomePage(),
CookRecipe(),
];
void onTapped(int pageTapped) {
setState(() {
//print(pageTapped);
_selectedPage = pageTapped;
Navigator.push(context, MaterialPageRoute(builder: (context) => _pageOptions[pageTapped]));
//print(_selectedPage);
});
}
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
//TODO: currentIndex: doesn't update when the state updates, why?
currentIndex: _selectedPage,
//items showing in bottom navigation bar
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
);
}
}
import 'package:flutter/material.dart';
import 'package:independentproject/page_navigation_bar.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home page'),
),
body: Center(
child: Text('Home page'),
),
bottomNavigationBar: PageNavigationBar(),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:independentproject/page_navigation_bar.dart';
class CookRecipe extends StatefulWidget {
#override
_CookRecipeState createState() => _CookRecipeState();
}
class _CookRecipeState extends State<CookRecipe> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Search recipe'),
),
body: Center(
child: Text('Search recipes'),
),
bottomNavigationBar: PageNavigationBar(),
),
);
}
}
I would advise you to create a widget that will contain the BottomNavigationBar and also PageView that would allow you to switch pages with PageController.
For example:
class _MainScreenState extends State<MainScreen> {
PageController _pageController;
int _page = 1;
Duration pageChanging = Duration(milliseconds: 300);//this is for page animation-not necessary
Curve animationCurve = Curves.linear;//this is for page animation-not necessary
_MainScreenState();
#override
void initState() {
super.initState();
_pageController = PageController(initialPage: 1);
}
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
controller: _pageController,
onPageChanged: onPageChanged,
children: <Widget>[
//here are all the pages you need:
//CookRecipe(),
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.message,
),
title: Container(height: 0.0),
),
BottomNavigationBarItem(
icon: Icon(
Icons.home,
),
title: Container(height: 0.0),
),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
),
title: Container(height: 0.0),
),
],
onTap: navigationTapped,
selectedItemColor: Theme.of(context).backgroundColor,
currentIndex: _page,
),
),
);
}
void navigationTapped(int page) {
_pageController.animateToPage(page,duration: pageChanging,
curve: animationCurve,);
}
#override
void dispose() {
super.dispose();
_pageController.dispose();
}
void onPageChanged(int page) {
if (this.mounted){
setState(() {
this._page = page;
});
}}
You can also do this without the PageView,and use only the controller to switch pages.
BTW-you create new instance of the navigation bar when you load a page which is bad practice
it is because PageNavigationBar is a own class, when you call there a setstate only this class updates
take a look at the Provider
a very usefull state management Package
or you can also handle your Page, when the NavBar is your Main Page and you have only one Page
return MaterialApp(
home: Scaffold(
appBar: ownAppBar(_selectedPage),
body: _bodyOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedPage,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
)
),
);
final List<Widget> _bodyOptions = [
HomePage(),
CookRecipe(),
];
You don't need to use Navigator to change pages, I modified your code just try.
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(home: PageNavigationBar()));
}
class PageNavigationBar extends StatefulWidget {
#override
_PageNavigationBarState createState() => _PageNavigationBarState();
}
class _PageNavigationBarState extends State<PageNavigationBar> {
//default page showing in bottom navigation bar will be CookRecipe()
int _selectedPage = 1;
//all pages optional in bottom navigation bar
final List<Widget> _pageOptions = [
HomePage(),
CookRecipe(),
];
void onTapped(int pageTapped) {
setState(() {
//print(pageTapped);
_selectedPage = pageTapped;
// Navigator.push(context, MaterialPageRoute(builder: (context) => _pageOptions[pageTapped]));
//print(_selectedPage);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _pageOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
//TODO: currentIndex: doesn't update when the state updates, why?
currentIndex: _selectedPage,
//items showing in bottom navigation bar
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
),
);
}
}
class CookRecipe extends StatefulWidget {
#override
_CookRecipeState createState() => _CookRecipeState();
}
class _CookRecipeState extends State<CookRecipe> {
#override
Widget build(BuildContext context) {
return Center(
child: Text('Search recipes'),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Center(
child: Text('Home page'),
);
}
}

BottomNavigationBar with page view wont animated to indexed page

I try to add three pages on BottomNavigationBar to navigate to the indexed page, the impimention of my code is so clean with no errors but the BottomNavigationBar wont change to other pages meanwile the selecten BottomNavigationBar item color changes to the selected one with no any errors on DEBUG console and this is my code
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int bottomSelectedIndex = 0;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Red')
),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: new Text('Blue'),
),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline),
title: Text('Yellow')
)
];
}
PageController pageController = PageController(
initialPage: 0,
keepPage: true,
);
Widget buildPageView() {
return PageView(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
children: <Widget>[
Red(),
Blue(),
Yellow(),
],
);
}
#override
void initState() {
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
pageController.animateToPage(index, duration: Duration(milliseconds: 500), curve: Curves.ease);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: buildPageView(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bottomSelectedIndex,
onTap: (index) {
bottomTapped(index);
},
items: buildBottomNavBarItems(),
),
);
}
}
You can copy paste run full code below
You can use PageView.builder
code snippet
List<Widget> listWidget = [Red(), Yellow(), Blue()];
...
return PageView.builder(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
itemCount: listWidget.length,
itemBuilder: (BuildContext context, int index) {
return listWidget[index];
},
);
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> listWidget = [Red(), Yellow(), Blue()];
int bottomSelectedIndex = 0;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: new Icon(Icons.home), title: new Text('Red')),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: new Text('Blue'),
),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline), title: Text('Yellow'))
];
}
PageController pageController = PageController(
initialPage: 0,
keepPage: true,
);
Widget buildPageView() {
return PageView.builder(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
itemCount: listWidget.length,
itemBuilder: (BuildContext context, int index) {
return listWidget[index];
},
);
}
#override
void initState() {
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
pageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: buildPageView(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bottomSelectedIndex,
onTap: (index) {
bottomTapped(index);
},
items: buildBottomNavBarItems(),
),
);
}
}
class Red extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("Red");
}
}
class Blue extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("Blue");
}
}
class Yellow extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("Yellow");
}
}

How to jump to another page with pageview flutter

Hello I tried to jump to my second page tab if I press on a button on my first Page tab. Currently I know only call route of my seconde page widget but bottomnavbar isn't present... I don't know how to call my parent widget from my first page tab to jump to the seconde page tab.
class Parent {
int bottomSelectedIndex = 0;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('First')
),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: new Text('Second'),
),
];
}
PageController pageController = PageController(
initialPage: 0,
keepPage: true,
);
Widget buildPageView() {
return PageView(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
children: <Widget>[
First(),
Second(),
],
);
}
#override
void initState() {
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
pageController.animateToPage(index, duration: Duration(milliseconds: 500), curve: Curves.ease);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: buildPageView(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bottomSelectedIndex,
onTap: (index) {
bottomTapped(index);
},
items: buildBottomNavBarItems(),
),
);
}
}
class first {
return Container(
// here a pressbutton for jump to the second widget
);
}
----------------------------------------------------------
class second
return Container(
);
}
You can use this:
void onAddButtonTapped(int index) {
// use this to animate to the page
pageController.animateToPage(index);
// or this to jump to it without animating
pageController.jumpToPage(index);
}
Pass the function as params:
class first {
final void Function(int) onAddButtonTapped;
return Container(
// call it here onAddButtonTapped(2);
);
}
class Second {
final void Function(int) onAddButtonTapped;
return Container(
);
}
children: <Widget>[
First(onAddButtonTapped),
Second(onAddButtonTapped),
],
You can pass a callback to your first widget and call that when the button is pressed, so you can change the page in the parent widget.
Something like this:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Parent(),
);
}
}
class Parent extends StatefulWidget {
#override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int bottomSelectedIndex = 0;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: new Icon(Icons.home), title: new Text('First')),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: new Text('Second'),
),
];
}
PageController pageController = PageController(
initialPage: 0,
keepPage: true,
);
Widget buildPageView() {
return PageView(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
children: <Widget>[
FirstWidget(
onButtonPressed: () => pageController.animateToPage(
1,
duration: Duration(milliseconds: 300),
curve: Curves.linear,
),
),
SecondWidget(),
],
);
}
#override
void initState() {
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
pageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: buildPageView(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bottomSelectedIndex,
onTap: (index) {
bottomTapped(index);
},
items: buildBottomNavBarItems(),
),
);
}
}
class FirstWidget extends StatefulWidget {
final VoidCallback onButtonPressed;
FirstWidget({#required this.onButtonPressed});
#override
_FirstWidgetState createState() => _FirstWidgetState();
}
class _FirstWidgetState extends State<FirstWidget> {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: Center(
child: FlatButton(
onPressed: widget.onButtonPressed,
child: Text('Go to second page'),
),
),
);
}
}
class SecondWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(color: Colors.green);
}
}