My project hierarchy is created similar to a MVC design pattern:
In the main.dart, I import the controller.dart
which houses the entire layout (Scaffold, AppBar, BottomNavigationBar) of my app and build the MaterialApp.
main.dart
import 'package:flutter/material.dart';
import 'controller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
To preserve my pages, I use a PageView
and PageController
with AutomaticKeepAliveClientMixin<MyView>
:
controller.dart
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
MyHomePageState createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
//Stores the selected index of navbar
int _selectedIndex = 0;
final PageController _pageController = PageController(initialPage: 0);
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
final List<Widget> pages = [
const View1(),
const View2(),
const View3(),
const View4(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(),
bottomNavigationBar: _bottomNavBar(_selectedIndex), //My navigation bar,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: _floatingActionButton, //My FAB
body: PageView(
controller: _pageController,
physics: const NeverScrollableScrollPhysics(),
children: pages,
),
drawer: const Drawer(),
extendBody: true,
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
_pageController.jumpToPage(_selectedIndex);
});
}
}

Everything is working as intended, except that I am not able to navigate to a new screen:
view2.dart
Future<void> _selectDate(BuildContext context) async {
DateTime selectedDate = inputDate.toLocal();
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2022, 1),
lastDate: DateTime(
selectedDate.year, selectedDate.month, selectedDate.day));
if (picked != null) {
//Navigate to new screen
if (!mounted) return;
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const NewView()),
);
}
}
Result:

I am pretty sure this isn't the way to do it, but I am not entirely sure how to navigate between screens with my project hierarchy either. My desired output is to push to a new screen while keeping my BottomNavigationBar
. Much appreciated for your help!