how to access PageViewController outside of widget - flutter

TabScreen is my main widget in my app that includes a BottomNavigationBar and a PageView to transition between pages.
PageController allows me to change views and everything is fine here, but there is one thing missing. How can I change my PageView controller outside of TabScreen? I'd like to put a button to access my main PageView controller from within my pages.
class _TabsScreenState extends State<TabsScreen> {
bool _isloading = true;
int? _selectedIndex;
List<Widget>? _pages = [
HomeScreen(),
CurrenPlanDetail(),
Container(),
ProfileScreen(),
SettingScreens(),
];
PageController? _pageController;
#override
void initState() {
_selectedIndex = 0;
_pageController = PageController(initialPage: _selectedIndex!);
}
}
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _pageController,
children: _pages!,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: Visibility(
visible: !_isloading,
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: kNewPurple,
//unselectedItemColor: Colors.grey,
currentIndex: _selectedIndex!,
onTap: (value) {
setState(() {
_selectedIndex = value;
_pageController!.jumpToPage(_selectedIndex!);
});
},
backgroundColor: Colors.grey[300],
items: [
BottomNavigationBarItem(
icon: Icon(
Ionicons.home_outline,
size: 15.sp,
),
label: 'Home'),
BottomNavigationBarItem(
icon: Icon(
Ionicons.reader_outline,
size: 15.sp,
),
label: 'Plan'),
BottomNavigationBarItem(
icon: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
fixedSize: Size(50, 50),
),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return FloatingButton();
});
},
child: Icon(Ionicons.add)),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Ionicons.happy_outline,
size: 15.sp,
),
label: 'Profile'),
BottomNavigationBarItem(
icon: Icon(
Ionicons.settings_outline,
size: 15.sp,
),
label: 'Setting'),
],
),
),
);
}
}
for example, somewhere in my app, I'd like to put a button and pass a function like this :
_pageController!.jumpToPage(1);

Define PageController as static and
TabScreen.pageController.jumpToPage(1);

Related

How to add scroll into bottom navigation bar items

I have implemented an app that navigates through a few screens. I have added the bottom navigation bar and 1st tab I add a page with list view items with sqlflite data.I can't scroll list view data. other tabs I have added to show another screen.
code is below.
//this is my homepage screen
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late List<LeaveModel> _leaveList = [];
final _userService = LeaveService();
int _selectedIndex = 0;
#override
void initState() {
getAllUserDetails();
super.initState();
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
I have create botom navigation bar with 4 item.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
),
title: const Text('Leave Tracker'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.add_box),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AddLeave()))
.then((data) {
if (data != null) {}
getAllUserDetails();
});
},
)
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.man),
label: 'All',
),
BottomNavigationBarItem(
icon: Icon(Icons.sick_rounded),
label: 'Sick',
),
BottomNavigationBarItem(
icon: Icon(Icons.holiday_village),
label: 'Casual',
),
BottomNavigationBarItem(
icon: Icon(Icons.weekend),
label: 'Other',
),
],
),
From this 4 items goto different 3 screens.1st item link to same page.(HomePage())
body: Center(
child: _selectedIndex == 0
? myListView(context)
: _selectedIndex == 1
? AllSickLeave()
: _selectedIndex == 2
? AllCasualLeave()
: ViewOtherLeave(),
),
);
}
In HomePage() i have add listview and data taking from sqlflite database.
getAllUserDetails() async {
var users = await _userService.readAllLeave();
_leaveList = <LeaveModel>[];
users.forEach((leave) {
setState(() {
var leaveModel = LeaveModel();
leaveModel.id = leave['id'];
leaveModel.leaveType = leave['leaveType'];
leaveModel.leaveStartDate = leave['leaveStartDate'];
leaveModel.leaveEndDate = leave['leaveEndDate'];
leaveModel.reason = leave['reason'];
leaveModel.leaveDays = leave['leaveDays'];
_leaveList.add(leaveModel);
});
});
}
Widget myListView(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 5.0,
),
Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
ListView.builder(
shrinkWrap: true,
itemCount: _leaveList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
'Leave Type : ${_leaveList[index].leaveType ?? ''}'),
subtitle: Text('Reason : ${_leaveList[index].reason}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: () {},
icon: Icon(
Icons.edit,
color: Colors.teal,
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.delete,
color: Colors.red,
)),
],
),
),
);
}),
],
),
),
);
}
}
You dont need to have multiple scaffold, and try this format
Widget myListView(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.only(top: 25),
itemCount: _leaveList.length + 1,
itemBuilder: (context, index) {
if (index == 0)
return Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
);
return Card(
child: ListTile(

How to add sliding transition animation to IndexedStack?

I'm working with IndexedStack and I would like to add a sliding transition animation when the page is changed with the Bottom Navigation Bar (NOT fade animation).
This is an abstract of my code:
class _LoggedHandleState extends State<LoggedHandle> {
int _selectedPage = 1;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("title"),
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.white60,
backgroundColor: Colors.red,
selectedItemColor: Colors.white,
currentIndex: _selectedPage,
onTap: (int index) {
setState(() {
_selectedPage = index;
});
},
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Hello',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: 'Account',
),
]),
body: IndexedStack(
index: _selectedPage,
children: [HelloView(), HomeView(), UserView()],
),
);
}
}
PS: I need to use IndexedStack in order to mantain the state, so I can't use PageBuilder
At the end of the day, IndexedStack is just a Stack of elements that will show the current tab on top. To achieve what you want I'd suggest to do something similar, yet different, like this:
class LoggedHandle extends StatefulWidget {
final _pages = <Widget>[HelloView(), HomeView(), UserView()];
#override
State<StatefulWidget> createState() => _LoggedHandleState();
}
class _LoggedHandleState extends State<LoggedHandle> {
var _selectedPage = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('title'),
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.white60,
backgroundColor: Colors.red,
selectedItemColor: Colors.white,
currentIndex: _selectedPage,
onTap: (i) {
setState(() {
_selectedPage = i;
});
},
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Hello',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: 'Account',
),
],
),
body: widget._pages[_selectedPage],
);
}
}
Then, for the animation, there's a Widget for that (AnimatedSwitcher). By exploiting that, along with an AnimatedWidget of your choice (or a custom one), you'll be good to go.
body: AnimatedSwitcher(
duration: const Duration(milliseconds: 650),
transitionBuilder: (child, animation) =>
ScaleTransition(scale: animation, child: child),
child: widget._pages[_selectedPage],
),

Flutter BottomNavigationBar stackoverflow

i'm starting with Flutter and i'm struggling with the navigationBar, if i add the body i keep getting a stackOverflow.
If i don't add the body everything is fine.
Error:
The following StackOverflowError was thrown building DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(blackMountainView bodyText2), inherit: false, color: Color(0xdd000000), family: Roboto, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip):
Stack Overflow
The relevant error-causing widget was:
Scaffold Scaffold:file:///Users/salvatorelafiura/git/energy_flutter/lib/screen/main.dart:104:12
When the exception was thrown, this was the stack:
#0 new Uint8List (dart:typed_data-patch/typed_data_patch.dart:2201:3)
#1 _createTables.<anonymous closure> (dart:core/uri.dart:3872:60)
#2 new _GrowableList.generate (dart:core-patch/growable_array.dart:133:28)
Code of the current widget, 3 screens one bottomNavigation.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widgetTitle.elementAt(selectedIndex)),
actions: <Widget>[
IconButton(
icon: const Icon(
Icons.logout,
color: Colors.white,
),
onPressed: () {
signOut();
},
)
],
),
body: Center(
child: IndexedStack(index: selectedIndex, children: tabPages),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Pratica"),
BottomNavigationBarItem(icon: Icon(Icons.mail), label: "Messages"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "Profilo"),
],
currentIndex: selectedIndex,
onTap: onItemTapped,
backgroundColor: Colors.white,
fixedColor: Colors.blue,
selectedLabelStyle: const TextStyle(color: Colors.red, fontSize: 20),
unselectedFontSize: 16,
selectedIconTheme:
const IconThemeData(color: Colors.blue, opacity: 1.0, size: 30.0),
unselectedItemColor: Colors.grey,
unselectedLabelStyle: const TextStyle(fontSize: 18, color: Colors.pink),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Create a Separate Class "Bottom" and Place the whole code of your Bottomnavigationbar inside that class then at every Screen just Call inside the Scaffold like:
bottomNavigationBar: Bottom();
Then Declare your int selectedIndex = 0; Globally
it will works fine.
Modify the Given code:
import 'package:flutter/material.dart';
int _selectedIndex = 0;
class Bottom extends StatefulWidget {
#override
_BottomState createState() => _BottomState();
}
class _BottomState extends State<Bottom> {
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
showSelectedLabels: true, // <-- HERE
showUnselectedLabels: true,
backgroundColor: Color(0xff38547C),
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
selectedItemColor: Color(0xFF1C2834),
unselectedItemColor: Colors.white,
items: [
BottomNavigationBarItem(
icon: const Icon(
Icons.home,
),
label: "Home",
),
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage("assets/images/ball.png"),
),
label: "Matches",
),
BottomNavigationBarItem(
icon: const Icon(
Icons.live_tv,
),
label: "Live"),
BottomNavigationBarItem(
icon: Icon(
Icons.poll,
),
label: "Ranking"),
BottomNavigationBarItem(
icon: Icon(
Icons.more_horiz,
),
label: "More"),
],
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
if (_selectedIndex == 0) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Home());
Navigator.of(context).push(route);
} else if (_selectedIndex == 1) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Matches());
Navigator.of(context).push(route);
} else if (_selectedIndex == 2) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Live());
Navigator.of(context).push(route);
} else if (_selectedIndex == 3) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Ranking());
Navigator.of(context).push(route);
} else if (_selectedIndex == 4) {
var route =
MaterialPageRoute(builder: (BuildContext context) => More());
Navigator.of(context).push(route);
}
});
}
}

Create two custom buttons inside Bottom Navigation Bar to control four pages using page view

I want to control four pages using two arrows on the bottom navigation bar, and in the middle of these two arrow buttons I have a counter to show the ID of the page. Like the image below:
I'm using modular route to change the pages, but I don't know how can I do that using only two buttons, and don't have idea how can I put the counter in the middle of this two buttons. Any suggestion?
class _CreateAccountPageState
extends ModularState<CreateAccountPage, CreateAccountController> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: controller.pageViewController,
children: [
RouterOutlet(),
RouterOutlet(),
RouterOutlet(),
RouterOutlet()
],
),
bottomNavigationBar: AnimatedBuilder(
animation: controller.pageViewController,
builder: (context, snapshot) {
return BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
elevation: 0,
backgroundColor: Colors.white,
currentIndex: controller.pageViewController.page?.round() ?? 0,
onTap: (id) {
if (id == 0) {
Modular.to.navigate('/createaccount/pageStep1');
} else if (id == 1) {
Modular.to.navigate('/createaccount/pageStep2');
} else if (id == 2) {
Modular.to.navigate('/createaccount/pageStep3');
} else if (id == 3) {
Modular.to.navigate('/createaccount/pageStep4');
}
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Page1',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Page2',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Page3',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Page4',
)
]
/*ElevatedButton(
onPressed: () => Modular.to.navigate("/login"),
child: Text("Voltar"))*/
);
},
));
}
Here is the output, I hope you can design the rest:
Widget
import 'package:flutter/material.dart';
class CreateAccountPage extends StatefulWidget {
CreateAccountPage({Key? key}) : super(key: key);
#override
_CreateAccountPageState createState() => _CreateAccountPageState();
}
class _CreateAccountPageState extends State<CreateAccountPage> {
PageController controller = PageController(initialPage: 0);
int currentPage = 0;
final pages = List.generate(
4,
(index) => Container(
alignment: Alignment.center,
color: index.isEven ? Colors.cyanAccent : Colors.yellowAccent,
child: Text(
"${index + 1}",
style: TextStyle(fontSize: 44),
),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: controller,
children: [...pages],
onPageChanged: (value) {
setState(() {
currentPage = value;
});
},
),
bottomNavigationBar: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
setState(() {
controller.previousPage(
duration: Duration(milliseconds: 400),
curve: Curves.easeInOut);
});
},
icon: Icon(Icons.arrow_left),
),
Text(
"${currentPage + 1}/${pages.length}",
),
IconButton(
onPressed: () {
controller.nextPage(
duration: Duration(milliseconds: 400),
curve: Curves.easeInOut);
},
icon: Icon(Icons.arrow_right),
)
],
),
));
}
}
I think what you are looking for is an onboarding screen. I suggest you take a look at this library here which is created especially for onboarding named introduction_screen. you can customize the bottons and texts as shown in the examples. read documentation for more information.

How to toggle visibility of TabBar with Bottom Navigation Items in Flutter

I have a bottomNavigationBar and an AppBar in my flutter app. At the bottom of the AppBar is a TabBar consisting of two items. So I want the TabBar to be invisible when some items of the BottomNavigationBar is clicked. I tried to assign the Visibility class to my TabBar with a Boolean variable but it doesn't work. It seems like I can't handle the TabBar widget separately.
How do resolve this?
class DashBoardPage extends StatefulWidget {
#override
_DashBoardPageState createState() => _DashBoardPageState();
}
class _DashBoardPageState extends State<DashBoardPage> {
SharedPreferences sharedPreferences;
bool showTabs = false;
int tabsIndex = 0;
int _currentIndex = 0;
String _appBarText = "Welcome, User";
Widget callPage(int currentIndex) {
switch (currentIndex) {
case 0:
showTabs = true;
_appBarText = "Welcome, User";
return TabBarView(
children:[
new HomePage(),
new SchedulePage()
]
);
break;
case 1:
showTabs = false;
break;
case 2:
showTabs = false;
break;
default:
return HomePage();
}
}
#override
void initState() {
super.initState();
checkLoginState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MAF Mentor',
debugShowCheckedModeBanner: false,
home: DefaultTabController(
length: choices.length,
child: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFFFFFFFF),
title: Text(
_appBarText,
style: TextStyle(
color: Color(0xFF1C2447),
fontFamily: 'Muli',
fontSize: 16.0,
),
),
bottom: showTabs? TabBar(
isScrollable: true,
tabs: choices.map<Widget>((Choice choice) {
return Tab(
text: choice.title,
icon: Icon(choice.icon),
);
}).toList(),
labelColor: Color(0xFF1C2447),
):null,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.account_circle,
color: Color(0xFF1C2447),
),
onPressed: () {
Navigator.of(context).pushNamed('/profile_page');
},
),
IconButton(
icon: Icon(
Icons.notifications,
color: Color(0xFF1C2447),
),
onPressed: () {
// do something
},
),
],
), //AppBar
body: callPage(_currentIndex),
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
fixedColor: Color(0xFF1C2447),
currentIndex: _currentIndex,
onTap: (value) {
_currentIndex = value;
callPage(_currentIndex);
setState(() {
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text("Bar 1")),
BottomNavigationBarItem(
icon: Icon(Icons.people), title: Text("Bar 2")),
BottomNavigationBarItem(
icon: Icon(Icons.history), title: Text("Bar 3"))
],
),
),
),
);
}
bottom requires a PreferredSizeWidget so you can not use the Visibility widget there. You can use a boolean variable to do that. You can see the whole code below. Since I don't know your choices and tabs I randomly put something. But the idea is if you want to show TabBar when user tap BottomNavigationBarItem
number 1 you just update your boolean variable as true. Otherwise make it false.
class TabBarExample extends StatefulWidget {
#override
_TabBarExampleState createState() => _TabBarExampleState();
}
class _TabBarExampleState extends State<TabBarExample> {
bool showTabs = false;
int selectedIndex = 0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFFFFFFFF),
title: Text(
'_appBarText',
style: TextStyle(
color: Color(0xFF1C2447),
fontFamily: 'Muli',
fontSize: 16.0,
),
),
bottom: showTabs
? TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(
text: 'Choice1',
icon: Icon(Icons.add_circle_outline),
),
Tab(
text: 'Choice1',
icon: Icon(Icons.add_circle),
),
],
labelColor: Color(0xFF1C2447),
)
: null,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text('first')),
BottomNavigationBarItem(
icon: Icon(Icons.favorite), title: Text('second')),
],
onTap: (index) {
if (index == 1) {
setState(() => showTabs = true);
} else {
setState(() => showTabs = false);
}
setState(() => selectedIndex = index);
},
),
),
);
}
}