Unable to call a method in another dart file - flutter

I have a dart file with IndexedStack and the following function in the same file to change the stacks.
The file with method as follows-
class RootApp extends StatefulWidget with selectedTab {
#override
_RootAppState createState() => _RootAppState();
}
class _RootAppState extends State<RootApp> {
int pageIndex = 0;
List<Widget> pages = [
......
];
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
....
return AnimatedBottomNavigationBar(
.......
onTap: (index) {
selectedTab(index);
},
);
}
selectedTab(index) {
setState(() {
pageIndex = index;
});
}
}
There is this other dart file from which i would like to call selectedTab method with value of 0. The other file is as follows---
class CreatBudgetPage extends StatefulWidget {
#override
_CreatBudgetPageState createState() => _CreatBudgetPageState();
}
class _CreatBudgetPageState extends State<CreatBudgetPage> {
.......
FirebaseFirestore.instance
.collection('expenses/' + userId + '/' + todayDate)
.add({
....
}).then((_) {
print("collection created");
void rootApp() => selectedTab(0);
}).catchError((error) {
print(error);
});
}
How can i call this method from the other dart file?
P.S: I am a Newbie

You can pass the function callback as parameters from the source class to the intended class and invoke the function as you want.
here is a simple example.
class Example extends StatefulWidget {
const Example({Key? key}) : super(key: key);
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
int pageIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: IndexedStack(
index: pageIndex,
children: [
Tab1Page(),
Tab2Page(
/// solution 1
onPressed1: () {
selectedTab(0);
},
/// solution 2
// onPressed2: selectedTab,
),
],
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'TAB 1',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'TAB 2',
),
],
currentIndex: pageIndex,
selectedItemColor: Colors.amber[800],
onTap: selectedTab,
),
);
}
selectedTab(index) {
setState(() {
pageIndex = index;
});
}
}
class Tab1Page extends StatelessWidget {
const Tab1Page({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: Center(
child: Text(
"Tab1",
style: TextStyle(fontSize: 20),
),
),
);
}
}
class Tab2Page extends StatelessWidget {
final VoidCallback? onPressed1;
// final Function(int)? onPressed2;
const Tab2Page({
Key? key
/// solution 1
,
this.onPressed1,
/// solution 2
// this.onPressed2
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Tab2",
style: TextStyle(fontSize: 20),
),
ElevatedButton(
onPressed: () {
/// solution 1
if (onPressed1 != null) {
onPressed1!();
}
/// solution 2
// if(onPressed2!=null){
// onPressed2!(0);
//
// }
},
child: Text("click to navigate to another tab",
style: TextStyle(fontSize: 20)),
),
],
),
),
);
}
}

Related

set state Badge appbar - flutter

I'm trying to increment the app bar icon by making a custom app bar. But I can't update the value with setState. I tried to update the value by the setAppBarValue function, but it didn't work.
MyAppBar.of(context)?.setAppBarValue(_counter);
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_incrementCounter();
MyAppBar.of(context)?.setAppBarValue(_counter);
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
MyAppBar() : super();
#override
Size get preferredSize => const Size.fromHeight(60);
#override
_MyAppBarState createState() => _MyAppBarState();
static _MyAppBarState? of(BuildContext context) =>
context.findAncestorStateOfType<_MyAppBarState>();
}
class _MyAppBarState extends State<MyAppBar>
with SingleTickerProviderStateMixin {
int _appBarValue = 0;
setAppBarValue(int value) {
setState(() {
_appBarValue = value;
});
}
#override
Widget build(BuildContext context) {
return AppBar(
title: const Text("teste"),
actions: <Widget>[Center(child: _alertBadge(context))]);
}
Widget _alertBadge(BuildContext context) {
return Badge(
position: BadgePosition.topEnd(
top: 0,
end: 3,
),
badgeStyle: BadgeStyle(
badgeColor: Colors.red,
),
badgeContent: Text(
_appBarValue.toString(),
style: TextStyle(color: Colors.white),
),
child:
IconButton(icon: Icon(Icons.shopping_bag_outlined), onPressed: () {}),
);
}
}
You Have to pass the increment variable value to the appbar widget like this:
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(
appBarValue: _counter,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_incrementCounter();
// MyAppBar.of(context)?.setAppBarValue(_counter);
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
And use that value in your app bar widget:
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
const MyAppBar({
Key? key,
required this.appBarValue,
}) : super(key: key);
final int appBarValue;
#override
Size get preferredSize => const Size.fromHeight(60);
#override
_MyAppBarState createState() => _MyAppBarState();
static _MyAppBarState? of(BuildContext context) =>
context.findAncestorStateOfType<_MyAppBarState>();
}
class _MyAppBarState extends State<MyAppBar>
with SingleTickerProviderStateMixin {
// int _appBarValue = 0;
//
// setAppBarValue(int value) {
// setState(() {
// _appBarValue = value;
// });
// }
#override
Widget build(BuildContext context) {
return AppBar(
title: const Text("teste"),
actions: <Widget>[Center(child: _alertBadge(context))]);
}
Widget _alertBadge(BuildContext context) {
return Badge(
position: BadgePosition.topEnd(
top: 0,
end: 3,
),
badgeStyle: BadgeStyle(
badgeColor: Colors.red,
),
badgeContent: Text(
widget.appBarValue.toString(),
style: TextStyle(color: Colors.white),
),
child:
IconButton(icon: Icon(Icons.shopping_bag_outlined), onPressed: () {}),
);
}
}

Flutter bottomNavigationBar not changing pages (when it's the "same page")

I have a bottom navigation bar and realized that the different pages/widgets that the navigator was going to were pretty much the exact same page (except for 2 parameters that changed). So instead of creating 2 pages/widgets which were pretty much identical (with only 2 differing parameters), I wanted to consolidate it into only one widget and pass the parameters from the page with the bottom navigator. The problem is that now that I did that it won't change the page it displays, or at least it won't change consistently (it usually will only show the page that corresponds to the first tab in the navigator (i.e., index = 0)). Here is my page with the bottom navigator:
class FreestylePage extends StatefulWidget {
const FreestylePage({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _FreestylePageState();
}
}
class _FreestylePageState extends State<FreestylePage> {
int _currentIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: showCategory(_currentIndex),
)),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.looks_one_outlined),
label: 'Single rope',
backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
BottomNavigationBarItem(
icon: Icon(Icons.looks_two_outlined),
label: 'Double dutch',
backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
],
onTap: (index) {
if (mounted) {
setState(() {
_currentIndex = index;
});
}
},
),
);
}
showCategory(index) {
if (index == 0) {
return [
WorkoutListPage(categoryIndex: 2, subCategories: Utils.srfDropdown)
];
} else {
return [
WorkoutListPage(categoryIndex: 3, subCategories: Utils.ddfDropdown)
];
}
}
}
And the WorkoutListPage looks as follows:
class WorkoutListPage extends StatefulWidget {
final int categoryIndex;
final List<String> subCategories;
const WorkoutListPage(
{Key? key, required this.categoryIndex, required this.subCategories})
: super(key: key);
#override
State<StatefulWidget> createState() {
return _WorkoutListPageState();
}
}
class _WorkoutListPageState extends State<WorkoutListPage> {
bool isLoading = true;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) =>
FutureBuilder<List<Map<String, dynamic>>>(
future: MyCard.getData(widget.categoryIndex, widget.subCategories)!
.whenComplete(() => setState(() {
isLoading = false;
})),
builder: ((context, snapshot) {
if (snapshot.hasData && snapshot.data!.isNotEmpty) {
return FutureBuilder<List<MyCard>>(
future: MyCard.readData(snapshot.data),
builder: (context, cards) {
if (cards.hasData) {
final card = cards.data!;
return Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: card.length,
itemBuilder: (context, index) {
return MyCard.buildCard(card[index], context);
},
),
);
} else {
return const Text("No data");
}
});
} else {
return isLoading
? Column(
children: const [CircularProgressIndicator()],
)
: const Text("You do not have any workouts yet");
}
}),
);
}
This doesn't work, but ironically if I change my showCategory function in the widget with the bottom navigation bar to the following:
showCategory(index) {
if (index == 0) {
return [
WorkoutListPage(categoryIndex: 2, subCategories: Utils.srfDropdown)
];
} else {
return [const FreestyleDDPage()];
}
}
where the FreestyleDDPage is the following:
class FreestyleDDPage extends StatefulWidget {
const FreestyleDDPage({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _FreestyleDDPageState();
}
}
class _FreestyleDDPageState extends State<FreestyleDDPage> {
var isLoading = true;
#override
Widget build(BuildContext context) =>
FutureBuilder<List<Map<String, dynamic>>>(
future: MyCard.getData(3, Utils.ddfDropdown)!
.whenComplete(() => setState(() {
isLoading = false;
})),
builder: ((context, snapshot) {
if (snapshot.hasData && snapshot.data!.isNotEmpty) {
return FutureBuilder<List<MyCard>>(
future: MyCard.readData(snapshot.data),
builder: (context, cards) {
if (cards.hasData) {
final card = cards.data!;
return Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: card.length,
itemBuilder: (context, index) {
return MyCard.buildCard(card[index], context);
},
),
);
} else {
return const Text("No data");
}
});
} else {
return isLoading
? Column(
children: const [CircularProgressIndicator()],
)
: const Text("You do not have any workouts yet");
}
}),
);
}
then it works.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
CustomWidgetWithParametr(index: 0 , categoryName: "HOME"),
CustomWidgetWithParametr(index: 1 , categoryName: "BUSINES"),
CustomWidgetWithParametr(index: 2 , categoryName: "SCHOOL"),
CustomWidgetWithParametr(index: 3 , categoryName: "Settings"),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.red,
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
backgroundColor: Colors.green,
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
backgroundColor: Colors.purple,
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
backgroundColor: Colors.pink,
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
class CustomWidgetWithParametr extends StatefulWidget {
const CustomWidgetWithParametr({Key? key, required this.index, required this.categoryName}) : super(key: key);
final int index;
final String categoryName;
#override
State<CustomWidgetWithParametr> createState() => _CustomWidgetWithParametrState();
}
class _CustomWidgetWithParametrState extends State<CustomWidgetWithParametr> {
#override
Widget build(BuildContext context) {
return
Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(widget.index.toString()),
Text(widget.categoryName),
],
);
}
}

How to change the BottomNavigationBar after a Navigator.push?

I would like to set a new BottomNavigationBar after i've clicked on one of my ListTile. Right now, i am getting two BottomNavigationbar after I've clicked on one of them.
Below is my code where I setup the first bar:
class CoachNav extends StatefulWidget {
const CoachNav({Key? key}) : super(key: key);
#override
State<CoachNav> createState() => _CoachNavState();
}
class _CoachNavState extends State<CoachNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
const TeamListView(),
const SettingsFormView(),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.groups),
label: "Mes équipes",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: "Paramètres"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
Then, there is the code where I setup the second bar:
class TeamNav extends StatefulWidget {
const TeamNav({Key? key}) : super(key: key);
#override
State<TeamNav> createState() => _TeamNavState();
}
class _TeamNavState extends State<TeamNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
const PlayersListView(),
const GamesListView(),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.group),
label: "Mes joueurs",
),
BottomNavigationBarItem(
icon: Icon(Icons.sports_basketball), label: "Mes matchs"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
Here are two screenshots of what is happening
First Bar
Second Bar
---------------- EDIT ----------------------
This is what I get when I make the _widgetOptions texts
I got the first bar... whith the content from where the second bar should Appear
this is the snippet of the code I got as answer below:
lass App extends StatelessWidget {
const App({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(home: CoachNav());
}
}
class TeamNav extends StatefulWidget {
const TeamNav({Key? key}) : super(key: key);
#override
State<TeamNav> createState() => _TeamNavState();
}
class _TeamNavState extends State<TeamNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
Text("PlayersListView"),
Text("PlayersListView"),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
/* floatingActionButton: FloatingActionButton(onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CoachNav(),
));
}),*/
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.group),
label: "Mes joueurs",
),
BottomNavigationBarItem(
icon: Icon(Icons.sports_basketball), label: "Mes matchs"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
class CoachNav extends StatefulWidget {
const CoachNav({Key? key}) : super(key: key);
#override
State<CoachNav> createState() => _CoachNavState();
}
class _CoachNavState extends State<CoachNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
Text("PlayersListView"),
Text("PlayersListView"),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
//floatingActionButton: FloatingActionButton(onPressed: () {}),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.groups),
label: "Mes équipes",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: "Paramètres"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
This is the code that have the text shown in the third screenshot.
class PlayersListView extends StatelessWidget {
const PlayersListView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(body: Text("Playerslist"),);
}
}
I think you have a design problem.
In your case, the best way is this one, i think.
When you tap on a tile you should fix a flag and rebuild your page instead of navigating to a new route.
Then, when building your BottomNavigationBarItemlist check the flag and add or remove BottomNavigationBarItem as you need.
Remove extra scaffold from _widgetOptions children that contains bottomNavBar. Follow the snippet pattern
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(home: TeamNav());
}
}
class TeamNav extends StatefulWidget {
const TeamNav({Key? key}) : super(key: key);
#override
State<TeamNav> createState() => _TeamNavState();
}
class _TeamNavState extends State<TeamNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
Text("PlayersListView"),
Text(" GamesListView()"),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CoachNav(),
));
}),
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.group),
label: "Mes joueurs",
),
BottomNavigationBarItem(
icon: Icon(Icons.sports_basketball), label: "Mes matchs"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
class CoachNav extends StatefulWidget {
const CoachNav({Key? key}) : super(key: key);
#override
State<CoachNav> createState() => _CoachNavState();
}
class _CoachNavState extends State<CoachNav> {
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
Text("TeamListView"),
Text("SettingsFormView"),
];
Widget? _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: _widgetOptions.elementAt(_selectedIndex),
),
floatingActionButton: FloatingActionButton(onPressed: () {}),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.groups),
label: "Mes équipes",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: "Paramètres"),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
),
);
}
}
Ok so I found a solution, I simply needed to add "rootNavigator: true" to my Navigator.push. It works as intended now.

Flutter - Call a function defined in another dart file to refresh a ListView

I have 2 dart files home.dart and video_list.dart.
I have a PopupMenuButton and a BottomNavigationBar in home.dart. video_list.dart is shown in the "body:" of home.dart.
Each time the value changes in PopupMenuButton in home.dart, I want to call a function in video_list.dart (_loadPlaylist()) so that the ListView in video_list.dart is refreshed.
How is this possible? I am a newbie.
home.dart
import 'package:crt/models/subject.dart';
import 'package:crt/pages/faq.dart';
import 'package:crt/pages/quiz.dart';
import 'package:crt/pages/video_list.dart';
import 'package:crt/pages/resource_list.dart';
import 'package:flutter/material.dart';
import 'package:crt/data/subjects.dart';
class Home extends StatefulWidget {
Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
//GlobalKey<_VideoListState> _key = GlobalKey<_VideoListState>();
Subject _selectedSubject = subjects[0];
int _currentIndex = 0;
List<StatefulWidget> pages = [];
#override
void initState() {
super.initState();
_setPages();
}
void _setPages() {
pages = [
VideoList(_selectedSubject),
ResourceList(_selectedSubject),
Quiz(_selectedSubject),
Faq(_selectedSubject),
];
}
IndexedStack _loadPage() {
return IndexedStack(
index: _currentIndex,
children: pages,
);
}
void _changeSubject(Subject subject) {
setState(() {
_selectedSubject = subject;
_setPages();
if (_selectedSubject.name == 'English') {
// I want to call _loadPlaylist function defined in video_list.dart
// VideoList()._loadPlaylist;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_selectedSubject.name),
elevation: 0,
actions: [
PopupMenuButton<Subject>(
onSelected: _changeSubject,
itemBuilder: (BuildContext context) {
return subjects.map((Subject subject) {
return PopupMenuItem<Subject>(
value: subject,
child: Text(subject.name),
);
}).toList();
},
)
],
),
body: _loadPage(),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
iconSize: 30,
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _currentIndex,
onTap: (index) => setState(() {
_currentIndex = index;
}),
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.video_library),
label: 'Videos',
),
BottomNavigationBarItem(
icon: Icon(Icons.library_books),
label: 'Resources',
),
BottomNavigationBarItem(
icon: Icon(Icons.quiz),
label: 'Quiz',
),
BottomNavigationBarItem(
icon: Icon(Icons.question_answer),
label: 'FAQ',
),
],
),
);
}
}
video_list.dart
import 'package:crt/models/subject.dart';
import 'package:flutter/material.dart';
import 'package:crt/models/playlist.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:crt/utilities/services.dart';
class VideoList extends StatefulWidget {
VideoList(Subject this.selectedSubject, {Key? key}) : super(key: key);
final Subject selectedSubject;
#override
State<VideoList> createState() => _VideoListState();
}
class _VideoListState extends State<VideoList> {
late Playlist _playlist;
bool _isLoading = true;
late String _name;
#override
void initState() {
super.initState();
_playlist = Playlist();
_playlist.items = List.empty(growable: true);
_loadPlaylist();
}
//I want to call this function from home.dart
_loadPlaylist() async {
String playlistId = widget.selectedSubject.playlistId;
Playlist playlist = await Services.getPlaylist(playlistId: playlistId);
_playlist.items?.addAll(playlist.items as Iterable<Item>);
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: ListView.builder(
itemCount: _playlist.items?.length,
itemBuilder: ((context, index) {
Item item = _playlist.items![index];
return Card(
child: InkWell(
onTap: () async {
// Navigator.push(context, MaterialPageRoute(builder: (context) {
// return VideoPlayer(
// item: item,
// );
// }));
},
child: Row(children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: CachedNetworkImage(
imageUrl:
item.snippet.thumbnails.thumbnailsDefault.url),
),
SizedBox(
width: 10.0,
),
Flexible(
child: Text(
item.snippet.title,
style: TextStyle(
fontSize: 18.0,
),
)),
const SizedBox(
width: 20.0,
),
]),
),
);
})),
);
}
}
Just move the _loadPlayList() function to Home and pass it down to VideoList widget.
class VideoList extends StatefulWidget {
VideoList(Subject this.selectedSubject, {Key? key, this.loadPlayList})
: super(key: key);
final Subject selectedSubject;
final Future<Function> loadPlayList;
#override
State<VideoList> createState() => _VideoListState();
}
The whole code - home.dart
import 'package:crt/models/subject.dart';
import 'package:crt/pages/faq.dart';
import 'package:crt/pages/quiz.dart';
import 'package:crt/pages/video_list.dart';
import 'package:crt/pages/resource_list.dart';
import 'package:flutter/material.dart';
import 'package:crt/data/subjects.dart';
class Home extends StatefulWidget {
Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
//GlobalKey<_VideoListState> _key = GlobalKey<_VideoListState>();
Subject _selectedSubject = subjects[0];
int _currentIndex = 0;
List<StatefulWidget> pages = [];
#override
void initState() {
super.initState();
_setPages();
}
void _setPages() {
pages = [
VideoList(_selectedSubject, loadPlayList()),
ResourceList(_selectedSubject),
Quiz(_selectedSubject),
Faq(_selectedSubject),
];
}
loadPlaylist() async {
String playlistId = widget.selectedSubject.playlistId;
Playlist playlist = await Services.getPlaylist(playlistId: playlistId);
_playlist.items?.addAll(playlist.items as Iterable<Item>);
}
IndexedStack _loadPage() {
return IndexedStack(
index: _currentIndex,
children: pages,
);
}
void _changeSubject(Subject subject) {
setState(() {
_selectedSubject = subject;
_setPages();
if (_selectedSubject.name == 'English') {
this.loadPlaylist();
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_selectedSubject.name),
elevation: 0,
actions: [
PopupMenuButton<Subject>(
onSelected: _changeSubject,
itemBuilder: (BuildContext context) {
return subjects.map((Subject subject) {
return PopupMenuItem<Subject>(
value: subject,
child: Text(subject.name),
);
}).toList();
},
)
],
),
body: _loadPage(),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
iconSize: 30,
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _currentIndex,
onTap: (index) => setState(() {
_currentIndex = index;
}),
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.video_library),
label: 'Videos',
),
BottomNavigationBarItem(
icon: Icon(Icons.library_books),
label: 'Resources',
),
BottomNavigationBarItem(
icon: Icon(Icons.quiz),
label: 'Quiz',
),
BottomNavigationBarItem(
icon: Icon(Icons.question_answer),
label: 'FAQ',
),
],
),
);
}
}
video_list.dart
import 'package:crt/models/subject.dart';
import 'package:flutter/material.dart';
import 'package:crt/models/playlist.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:crt/utilities/services.dart';
class VideoList extends StatefulWidget {
VideoList(Subject this.selectedSubject, this.loadPlayList, {Key? key})
: super(key: key);
final Subject selectedSubject;
final Future<Function> loadPlayList;
#override
State<VideoList> createState() => _VideoListState();
}
class _VideoListState extends State<VideoList> {
late Playlist _playlist;
bool _isLoading = true;
late String _name;
#override
void initState() {
super.initState();
_playlist = Playlist();
_playlist.items = List.empty(growable: true);
widget.loadPlaylist().then(() {
setState(() {
_isLoading = false;
});
};
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: ListView.builder(
itemCount: _playlist.items?.length,
itemBuilder: ((context, index) {
Item item = _playlist.items![index];
return Card(
child: InkWell(
onTap: () async {
// Navigator.push(context, MaterialPageRoute(builder: (context) {
// return VideoPlayer(
// item: item,
// );
// }));
},
child: Row(children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: CachedNetworkImage(
imageUrl:
item.snippet.thumbnails.thumbnailsDefault.url),
),
SizedBox(
width: 10.0,
),
Flexible(
child: Text(
item.snippet.title,
style: TextStyle(
fontSize: 18.0,
),
)),
const SizedBox(
width: 20.0,
),
]),
),
);
})),
);
}
}

Flutter persistent app bar across PageView

Ideally I would like to set up my Flutter app as follows
PageView to swipe left/right between 3 pages and a bottom navigation bar to serve as a label and also help with navigation
Persistent appbar on top with drawer and contextual icons
Page content in between
As can be seen in the image, I have this mostly set up the way I would like in the following manner
main.dart - app entry point, set up appbar, set up pageview with children for new PeoplePage, new TimelinePage, new StatsPage
people_page.dart
timeline_page.dart
stats_page.dart
These three pages just deliver the content to the PageView children as required.
Is this the correct way to achieve this? On the surface it works fine. The issue I am coming across is that on the people page I want to implement a selectable list that changes the appbar title/color as in this example, but the appbar is set up on the main page. Can I access the appbar globally?
I could build a new appbar for each page, but I dont want a new appbar swiping in when switching page. I'd prefer the appbar to look persistent and only have the content swipe in.
Any guidance on the best way to accomplish this would be appreciated.
I put together a quick example of how you might communicate from your screen down to the pages and then also back again. This should solve your problem.
https://gist.github.com/slightfoot/464fc225b9041c2d66ec8ab36fbdb935
import 'package:flutter/material.dart';
void main() => runApp(TestApp());
class TestApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.green[900],
scaffoldBackgroundColor: Colors.grey[200],
),
home: MainScreen(),
);
}
}
class AppBarParams {
final Widget title;
final List<Widget> actions;
final Color backgroundColor;
AppBarParams({
this.title,
this.actions,
this.backgroundColor,
});
}
class MainScreen extends StatefulWidget {
final int initialPage;
const MainScreen({
Key key,
this.initialPage = 0,
}) : super(key: key);
#override
MainScreenState createState() => MainScreenState();
static MainScreenState of(BuildContext context) {
return context.ancestorStateOfType(TypeMatcher<MainScreenState>());
}
}
class MainScreenState extends State<MainScreen> {
final List<GlobalKey<MainPageStateMixin>> _pageKeys = [
GlobalKey(),
GlobalKey(),
GlobalKey(),
];
PageController _pageController;
AppBarParams _params;
int _page;
set params(AppBarParams value) {
setState(() => _params = value);
}
#override
void initState() {
super.initState();
_page = widget.initialPage ?? 0;
_pageController = PageController(initialPage: _page);
WidgetsBinding.instance.addPostFrameCallback((_) {
_pageKeys[0].currentState.onPageVisible();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: _params?.title,
actions: _params?.actions,
backgroundColor: _params?.backgroundColor,
),
body: PageView(
controller: _pageController,
onPageChanged: _onPageChanged,
children: <Widget>[
PeoplePage(key: _pageKeys[0]),
TimelinePage(key: _pageKeys[1]),
StatsPage(key: _pageKeys[2]),
],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _page,
onTap: _onBottomNavItemPressed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
title: Text('people'),
icon: Icon(Icons.people),
),
BottomNavigationBarItem(
title: Text('timeline'),
icon: Icon(Icons.history),
),
BottomNavigationBarItem(
title: Text('stats'),
icon: Icon(Icons.pie_chart),
),
],
),
);
}
#override
void reassemble() {
super.reassemble();
_onPageChanged(_page);
}
void _onPageChanged(int page) {
setState(() => _page = page);
_pageKeys[_page].currentState.onPageVisible();
}
void _onBottomNavItemPressed(int index) {
setState(() => _page = index);
_pageController.animateToPage(
index,
duration: Duration(milliseconds: 400),
curve: Curves.fastOutSlowIn,
);
}
}
abstract class MainPageStateMixin<T extends StatefulWidget> extends State<T> {
void onPageVisible();
}
class PeoplePage extends StatefulWidget {
const PeoplePage({Key key}) : super(key: key);
#override
PeoplePageState createState() => PeoplePageState();
}
class PeoplePageState extends State<PeoplePage> with MainPageStateMixin {
final List<Color> _colors = [
Colors.orange,
Colors.purple,
Colors.green,
];
int _personCount = 3;
#override
void onPageVisible() {
MainScreen.of(context).params = AppBarParams(
title: Text('People'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.person_add),
onPressed: () => setState(() => _personCount++),
),
],
backgroundColor: Colors.green,
);
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _personCount,
itemBuilder: (BuildContext context, int index) {
return Card(
child: InkWell(
onTap: () => _onTapCard(index),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Material(
type: MaterialType.circle,
color: _colors[index % _colors.length],
child: Container(
width: 48.0,
height: 48.0,
alignment: Alignment.center,
child: Text('$index', style: TextStyle(color: Colors.white)),
),
),
SizedBox(width: 16.0),
Text(
'Item #$index',
style: TextStyle(
color: Colors.grey[600],
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
);
},
);
}
void _onTapCard(int index) {
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Item #$index')));
}
}
class TimelinePage extends StatefulWidget {
const TimelinePage({Key key}) : super(key: key);
#override
TimelinePageState createState() => TimelinePageState();
}
class TimelinePageState extends State<TimelinePage> with MainPageStateMixin {
#override
void onPageVisible() {
MainScreen.of(context).params = AppBarParams(
title: Text('Timeline'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.alarm_add),
onPressed: () {},
),
],
backgroundColor: Colors.purple,
);
}
#override
Widget build(BuildContext context) {
return Center(
child: Text('Coming soon'),
);
}
}
class StatsPage extends StatefulWidget {
const StatsPage({Key key}) : super(key: key);
#override
StatsPageState createState() => StatsPageState();
}
class StatsPageState extends State<StatsPage> with MainPageStateMixin {
#override
void onPageVisible() {
MainScreen.of(context).params = AppBarParams(
title: Text('Stats'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add_box),
onPressed: () {},
),
],
backgroundColor: Colors.orange,
);
}
#override
Widget build(BuildContext context) {
return Center(
child: Text('Coming soon'),
);
}
}
One way to tackle this would be to have the AppBar title and background color as state variables, and in your PageView set the onPageChanged to a function. This function takes in the page int and based on the page int it sets the state of the title and color to the values that you desire. For the multiselect list you set the title to the variable which keeps the values you have selected, may be keep it as a state variable in the main page and pass it down to the child component. You can use any of the state management strategies and that should probably work fine.
Example of onPageChanged function:
void onPageChanged(int page) {
String _temptitle = "";
Color _tempColor;
switch (page) {
case 0:
_temptitle = "People";
_tempColor = Colors.pink;
break;
case 1:
_temptitle = "Timeline";
_tempColor = Colors.green;
break;
case 2:
_temptitle = "Stats";
_tempColor = Colors.deepPurple;
break;
}
setState(() {
this._page = page;
this._title = _temptitle;
this._appBarColor = _tempColor;
});
}
So for the multiselect case, instead of setting the title to some constant you set the title to the variable which holds the values of the selected options.
Full code is here:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
PageController _pageController;
int _page = 0;
String _title = "MyApp";
Color _appBarColor = Colors.pink;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(_title),
backgroundColor: _appBarColor,
),
body: PageView(
children: <Widget>[
Container(
child: Center(child: Text("People")),
),
Container(
child: Center(child: Text("Timeline")),
),
Container(
child: Center(child: Text("Stats")),
),
],
controller: _pageController,
onPageChanged: onPageChanged,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.people),
title: Text("People"),
),
BottomNavigationBarItem(
icon: Icon(Icons.access_time),
title: Text("Timeline"),
),
BottomNavigationBarItem(
icon: Icon(Icons.pie_chart),
title: Text("Stats"),
),
],
onTap: navigateToPage,
currentIndex: _page,
),
);
}
void navigateToPage(int page) {
_pageController.animateToPage(page,
duration: Duration(milliseconds: 300), curve: Curves.ease);
}
void onPageChanged(int page) {
String _temptitle = "";
Color _tempColor;
switch (page) {
case 0:
_temptitle = "People";
_tempColor = Colors.pink;
break;
case 1:
_temptitle = "Timeline";
_tempColor = Colors.green;
break;
case 2:
_temptitle = "Stats";
_tempColor = Colors.deepPurple;
break;
}
setState(() {
this._page = page;
this._title = _temptitle;
this._appBarColor = _tempColor;
});
}
#override
void initState() {
super.initState();
_pageController = new PageController();
_title = "People";
}
#override
void dispose() {
super.dispose();
_pageController.dispose();
}
}
You can improve this code for your needs. Hope this was helpful in someway. Let me know if there is something I can improve about this answer.