Got a problem with my button after adding BottomNavigator - android

im new to flutter and i got a problem on my app,
firstly i was creating a button on my "ReminderPage" to navigate to a different page "AddReminder". it works before, so i try to add BottomNavigator in my "MainPage", but when i add a bottom navigatation from "HomePage" to "ReminderPage" all of the sudden the button didnt work, i also have an icon to change the theme, but the button didnt work and the background all of the sudden become blue, i dont know how this error happen so i need help from all of you guys, thank you
here is my "ReminderPage" code
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medreminder/Reminder/services/notification_services.dart';
import 'package:medreminder/Reminder/services/theme_services.dart';
import 'package:intl/intl.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/Reminder/ui/widgets/button.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
class ReminderHomePage extends StatefulWidget {
const ReminderHomePage({super.key});
#override
State<ReminderHomePage> createState() => _ReminderHomePageState();
}
class _ReminderHomePageState extends State<ReminderHomePage> {
DateTime _selectedDate = DateTime.now();
var notifyHelper;
#override
void initState() {
// TODO: implement initState
super.initState();
notifyHelper=NotifyHelper();
notifyHelper.initializeNotification();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: _appBar(),
backgroundColor: context.theme.backgroundColor,
body: Column(
children: [
_addTaskBar(),
_addDateBar(),
],
),
);
}
_addDateBar(){
return Container(
margin: const EdgeInsets.only(top: 20, left: 20),
child: DatePicker(
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: Color(0xFFAAB6FB),
selectedTextColor: Colors.white,
dateTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
dayTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
monthTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
onDateChange: (date){
_selectedDate=date;
},
),
);
}
_addTaskBar(){
return Container(
margin: const EdgeInsets.only(left: 20, right: 20, top: 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(DateFormat.yMMMMd().format(DateTime.now()),
style: subHeadingStyle,
),
Text("Today",
style: headingStyle,
)
],
),
),
MyButton(label: "Add Reminder", onTap: ()=>Get.to(AddReminderPage()))
],
),
);
}
_appBar(){
return AppBar(
elevation: 0,
backgroundColor: context.theme.backgroundColor,
leading: GestureDetector(
onTap: (){
ThemeService().switchTheme();
notifyHelper.displayNotification(
title:"Theme Changed!",
body: Get.isDarkMode?"Activated Light Theme!":"Activated Dark Theme!"
);
notifyHelper.scheduledNotification();
},
child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round,
size: 20,
color:Get.isDarkMode ? Colors.white:Colors.black
),
),
actions: [
CircleAvatar(
backgroundImage: AssetImage(
"images/profile.png"
),
),
// Icon(Icons.person,
// size: 20,),
SizedBox(width: 20,),
],
);
}
}
here is my BottomNavigator code
import 'package:flutter/material.dart';
import 'package:medreminder/Reminder/ui/home_reminder.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/home_page.dart';
import 'package:medreminder/profile_page.dart';
import 'package:medreminder/settings_page.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
void main() => runApp(MaterialApp(home: MainPage()));
class MainPage extends StatefulWidget {
const MainPage({super.key});
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List <Widget> pages = [
HomePage(),
SettingPage(),
ProfilePage()
];
int currentIndex = 0;
void onTap(int index){
setState(() {
currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
//height: MediaQuery.of(context).size.height * 0.4,
child: pages[currentIndex]
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
onTap: onTap,
currentIndex: currentIndex,
selectedItemColor: bluishClr,
unselectedItemColor: Colors.black,
showUnselectedLabels: false,
showSelectedLabels: false,
items: [
BottomNavigationBarItem(label: "Home", icon: Icon(Icons.home)),
BottomNavigationBarItem(label: "Settings", icon: Icon(Icons.settings)),
BottomNavigationBarItem(label: "Profile", icon: Icon(Icons.account_circle)),
],
),
);
}
}
and lastly here is my HomePage code
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 200,
fit: BoxFit.cover,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
child: Text("Button1"),
),
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {},
child: Text("Button2"),
),
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {},
child: Text("Button3"),
),
],
)
]),
),
);
}
}
i really need a help, so every help would mean so much to me, thankyou guys
here is my app working perfectly when i run only the ReminderPage
https://i.stack.imgur.com/JqcZp.png
and here's how it look if i run it with BottomNavigationBar (the add reminder button and moon icon cant be clicked)
https://i.stack.imgur.com/9hVr8.png

Try the following code:
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage())
);

try this
Navigator.of(context, rootNavigator: true).push(
context,
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);

Related

How to update data on screen after filtering using Flutter Bloc?

I am learning Flutter now and i have a screen that loading many series characters, and i have an icon in the AppBar showing
ModalBottomSheet and it have many choices to filter to update data with the new chosen ones.
I got the choices and stored the in a List of Strings but i dont know how to pass it to a function in my cubit file and i don't know how to update data using cubit , i tried many ways but didn't work with me.
Here's my code
import 'package:breakingbad/data/models/breaking_bad_characters.dart';
import 'package:breakingbad/domain/cubit/rick_and_morty_cubit.dart';
import 'package:breakingbad/presentation/character-detail.dart';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../widgets/character_item.dart';
import '../widgets/chip_choice.dart';
class MyHomePage extends StatefulWidget {
static String id ='home';
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return BlocConsumer<RickAndMortyCubit,RickAndMortyState>(
listener: (context, state){},
builder: (context, state) {
var cubit = RickAndMortyCubit.get(context);
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('Rick And Morty')),
actions: [
IconButton(
padding: const EdgeInsets.only(right: 25),
onPressed: (){
showModalBottomSheet(
context: context,
builder: (context) =>
Column(
children: [
Container(
alignment: Alignment.center,
color: Colors.black,
width: double.infinity,
height: 50,
child: const Text('Filter Characters',style: TextStyle(color:
Colors.white,fontSize: 22),),
),
const ChoiceChipWidget(),
],
)
);
},
icon: const Icon(Icons.filter_list_sharp,size: 40,)),
],
),
body: ConditionalBuilder(
condition: state is RickAndMortyCharsLoaded,
fallback: (context)=> const Center(child: CircularProgressIndicator()),
builder: (context) => GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 2 / 3,
crossAxisSpacing: 1,
mainAxisSpacing: 1,
),
itemCount: cubit.allHuman.length,
itemBuilder: (context,index) =>
CharacterItem(
rickAndMortyCharacters: cubit.allHuman[index],
widget:CharacterDetail(rickAndMortyCharacters: cubit.allHuman[index]),
)
),
)
);
}
);
}
}
import 'package:breakingbad/domain/cubit/rick_and_morty_cubit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ChoiceChipWidget extends StatefulWidget {
const ChoiceChipWidget( {super.key, });
#override
State<ChoiceChipWidget> createState() => _ChoiceChipWidgetState();
}
class _ChoiceChipWidgetState extends State<ChoiceChipWidget> {
String selectedChoice1 = "";
String selectedChoice2 = "";
String selectedChoice3 = "";
List<String> filter=[];
#override
Widget build(BuildContext context) {
return BlocBuilder<RickAndMortyCubit, RickAndMortyState>(
builder: (context, state) {
var cubit = RickAndMortyCubit.get(context);
return Column(
children: [
Chip(
elevation: 20,
padding: const EdgeInsets.all(8),
backgroundColor: Colors.greenAccent[100],
shadowColor: Colors.black,
label: const Text(
'Gender',
style: TextStyle(fontSize: 20),
), //Text
),
Row(
children: cubit.gender.map((item){
return Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
labelStyle: const TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0),
),
backgroundColor: Colors.grey[300],
selectedColor: Colors.blue,
selected: selectedChoice1 == item,
onSelected: (selected) {
setState(() {
selectedChoice1 = item;
filter.add(selectedChoice1);
});
},
),
);
}).toList()
),
Chip(
elevation: 20,
padding: const EdgeInsets.all(8),
backgroundColor: Colors.greenAccent[100],
shadowColor: Colors.black,
label: const Text(
'Species',
style: TextStyle(fontSize: 20),
), //Text
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children:cubit.species.map((item){
return Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
labelStyle: const TextStyle(
fontSize: 18,
color: Colors.black, fontWeight: FontWeight.bold),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0),
),
backgroundColor: Colors.grey[300],
selectedColor: Colors.blue,
selected: selectedChoice2 == item,
onSelected: (selected) {
setState(() {
selectedChoice2 = item;
filter.add(selectedChoice2);
});
},
),
);
}).toList()
),
),
Chip(
elevation: 20,
padding: const EdgeInsets.all(8),
backgroundColor: Colors.greenAccent[100],
shadowColor: Colors.black,
label: const Text(
'Statue',
style: TextStyle(fontSize: 20),
), //Text
),
Row(
children:cubit.statue.map((item){
return Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
labelStyle: const TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0),
),
backgroundColor: Colors.grey[300],
selectedColor: Colors.blue,
selected: selectedChoice3 == item,
onSelected: (selected) {
setState(() {
selectedChoice3 = item;
filter.add(selectedChoice3);
});
},
),
);
}).toList()
),
SizedBox(height: 4,),
InkWell(
onTap: (){
// here i want to apply changes
Navigator.pop(context);
},
child: Chip(
elevation: 20,
padding: const EdgeInsets.all(8),
backgroundColor: Colors.greenAccent[100],
shadowColor: Colors.black,
label: const Text(
'apply',
style: TextStyle(fontSize: 20),
), //Text
),
),
],
);
},
);
}
}
I have two main functions, the first one get all characters to the home screen:
List<Characters>?
getAllCharacters(){
myRepository.
getAllCharacters().then(
(allCharacters)=>
this.allCharacters =
allCharacters;
);
return allCharacters;
}
and the second function that takes a parameter of List of Strings which i suppose to get them from the filtering in bottomSheet;
List<Characters>?
getFilteredCharacters
(List<String> list){
myRepository
.getFilteredCharacters(list)
.then((filteredCharacters)=>
this.filteredCharacters =
filteredCharacters;
);
return filteredCharacters;
}
Anyone could help me in this issue?

Flutter button shows error instead of navigate

im new in flutter and i have this button error that wont navigate to different pages.
so i have a "HomePage" that have a button to navigate to "ReminderHomePage". but when i try to press it it show this error:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a
descendant of a Navigator widget.
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_packages/flutter/src/widgets/navigator.dart 2554:9 <fn>
packages/flutter/src/widgets/navigator.dart 2560:14 of
packages/flutter/src/widgets/navigator.dart 2019:34 push
packages/medreminder/home_page.dart 42:32 <fn>
packages/flutter/src/material/ink_well.dart 1072:21
handleTap
packages/flutter/src/gestures/recognizer.dart 253:24
invokeCallback
packages/flutter/src/gestures/tap.dart 627:11
handleTapUp
packages/flutter/src/gestures/tap.dart 306:5
[_checkUp]
packages/flutter/src/gestures/tap.dart 239:7
handlePrimaryPointer
packages/flutter/src/gestures/recognizer.dart 615:9
handleEvent
packages/flutter/src/gestures/pointer_router.dart 98:12
[_dispatch]
packages/flutter/src/gestures/pointer_router.dart 143:9 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/linked_hash_map.dart 21:13
forEach
packages/flutter/src/gestures/pointer_router.dart 141:17
[_dispatchEventToRoutes]
packages/flutter/src/gestures/pointer_router.dart 127:7 route
packages/flutter/src/gestures/binding.dart 460:19
handleEvent
packages/flutter/src/gestures/binding.dart 440:14
dispatchEvent
packages/flutter/src/rendering/binding.dart 337:11
dispatchEvent
packages/flutter/src/gestures/binding.dart 395:7
[_handlePointerEventImmediately]
packages/flutter/src/gestures/binding.dart 357:5
handlePointerEvent
packages/flutter/src/gestures/binding.dart 314:7
[_flushPointerEventQueue]
packages/flutter/src/gestures/binding.dart 295:7
[_handlePointerDataPacket]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 1183:13
invoke1
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 244:5
invokeOnPointerDataPacket
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 147:39
[_onPointerData]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 653:20 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 594:14 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 288:16
loggedHandler
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 179:80 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14
_checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
Handler: "onTap"
Recognizer:
TapGestureRecognizer#02cb0
════════════════════════════════════════════════════════════════════════════════════════════════════
i dont know why this error occur and how to fix it, any help would mean so much to me.
here is my "HomePage" code
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 200,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
child: const Text('Button 1'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
ElevatedButton(
child: const Text('Button 2'),
onPressed: () {},
),
ElevatedButton(
child: const Text('Button 3'),
onPressed: () {},
),
],
),
],
),
),
);
}
}
and here is the "ReminderHomePage" that i want to navigate to
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medreminder/Reminder/services/notification_services.dart';
import 'package:medreminder/Reminder/services/theme_services.dart';
import 'package:intl/intl.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/Reminder/ui/widgets/button.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/home_page.dart';
class ReminderHomePage extends StatefulWidget {
const ReminderHomePage({super.key});
#override
State<ReminderHomePage> createState() => _ReminderHomePageState();
}
class _ReminderHomePageState extends State<ReminderHomePage> {
DateTime _selectedDate = DateTime.now();
var notifyHelper;
#override
void initState() {
// TODO: implement initState
super.initState();
notifyHelper=NotifyHelper();
notifyHelper.initializeNotification();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(),
backgroundColor: context.theme.backgroundColor,
body: Column(
children: [
_addTaskBar(),
_addDateBar(),
],
),
);
}
_addDateBar(){
return Container(
margin: const EdgeInsets.only(top: 20, left: 20),
child: DatePicker(
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: Color(0xFFAAB6FB),
selectedTextColor: Colors.white,
dateTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
dayTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
monthTextStyle: GoogleFonts.lato(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color:Colors.grey
),
),
onDateChange: (date){
_selectedDate=date;
},
),
);
}
_addTaskBar(){
return Container(
margin: const EdgeInsets.only(left: 20, right: 20, top: 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(DateFormat.yMMMMd().format(DateTime.now()),
style: subHeadingStyle,
),
Text("Today",
style: headingStyle,
)
],
),
),
MyButton(label: "Add Reminder", onTap: ()=>Get.to(AddReminderPage()))
],
),
);
}
_appBar(){
return AppBar(
elevation: 0,
backgroundColor: context.theme.backgroundColor,
leading: GestureDetector(
onTap: (){
ThemeService().switchTheme();
notifyHelper.displayNotification(
title:"Theme Changed!",
body: Get.isDarkMode?"Activated Light Theme!":"Activated Dark Theme!"
);
notifyHelper.scheduledNotification();
},
child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round,
size: 20,
color:Get.isDarkMode ? Colors.white:Colors.black
),
),
actions: [
CircleAvatar(
backgroundImage: AssetImage(
"images/profile.png"
),
),
// Icon(Icons.person,
// size: 20,),
SizedBox(width: 20,),
],
);
}
}
thankyou.
That's not how you Navigate. You just need to give the class name in the builder method.
From this:
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Scaffold(
body: ReminderHomePage()
),
),
);
},
To this:
void main() {
runApp(const MyApp()); //change the main method to call our root class
}
class MyApp extends StatelessWidget { //add a new class on top of your main class
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage(), //call your old class in that new main class
);
}
And this should remain the same:
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ReminderHomePage(),
),
);
},
Check this flutter site
https://docs.flutter.dev/cookbook/navigation/navigation-basics
For navigation use this
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);

How to disable a button if the user is not inside a certain radius?

So basically I wanted to disable the button at first until or if the user enters a certain radius then the button would be enabled again but I'm not sure how to do it so here's the example of my code which i wanted to disable the button on the 'Reserve parking' button. Here's the code to the page.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:parkingtechproject/Screens/reportfeedback.dart';
import 'package:parkingtechproject/authenticate/sign_in.dart';
import 'package:parkingtechproject/model/parking.dart';
import 'car_reservation.dart';
import 'maps.dart';
import 'profile_page.dart';
class Home extends StatefulWidget{
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late String _timeString;
bool isButtonActive = true;
//firebase instance
User? user = FirebaseAuth.instance.currentUser;
Parking loginuser = Parking();
#override
void initState(){
super.initState();
FirebaseFirestore.instance
.collection('parkingTech')
.doc(user!.uid)
.get()
.then((value){
this.loginuser = Parking.fromMap(value.data());
setState(() {});
});
}
//Sign Out
Future <void> logout(BuildContext context) async {
await FirebaseAuth.instance.signOut();
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => LoginScreen()));
}
// void initState(){
// _timeString = "${DateTime.now().hour} : ${DateTime.now().minute} :${DateTime.now().second}";
// Timer.periodic(Duration(seconds:1), (Timer t)=>_getCurrentTime());
// super.initState();
// }
Widget build(BuildContext context){
return Scaffold(
backgroundColor: Colors.amber,
appBar: AppBar(
backgroundColor: Colors.amber,
elevation: 0.0,
title: Text('Parking Tech',
style:TextStyle(
color: Color(0xFF121212),
fontWeight: FontWeight.bold,
),
),
centerTitle:true,
actions: [
IconButton(onPressed: (){
logout(context);
},
icon: Icon(
Icons.logout,
size: 25,
),
),
]
),
body: Column(
children:[
Expanded(
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/images/Parkingtech.png'
),
// image: NetworkImage(
// 'https://www.istockphoto.com/photo/car-icon-special-black-square-button-gm624404280-109743191?utm_source=unsplash&utm_medium=affiliate&utm_campaign=srp_photos_top&utm_content=https%3A%2F%2Funsplash.com%2Fs%2Fphotos%2Fcar-icon&utm_term=car%20icon%3A%3Asearch-explore-top-affiliate-outside-feed%3Aenabled'),
fit: BoxFit.fill),
),
),
),
Expanded(
child:Container(
color: Color(0xFF121212),
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 20),
Text("Welcome, ${loginuser.name}",
style: const TextStyle(
color: Colors.white,
fontWeight:FontWeight.normal,
fontSize: 15,
),
),
const SizedBox( height: 10),
Text("Car Plate : ${loginuser.car}",
style: const TextStyle(
color: Colors.white,
fontWeight:FontWeight.normal,
fontSize: 15,
),
),
const SizedBox( height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFFF59539),
Color(0xFFF59222),
Color(0xFFD97503),
],
),
),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.all(10.0),
primary: Colors.white,
textStyle: const TextStyle(fontSize: 13.1),
),
onPressed: isButtonActive?() {
setState(() {
isButtonActive = false;
});
Navigator.push(context,MaterialPageRoute(builder: (context) => Reservation()));
} : null,
child: const Text('Reserve parking? '),
),
],
),
),
const SizedBox(height: 15,),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFFF62626),
Color(0xFFDB1010),
Color(0xFFC60505),
],
),
),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.all(10.0),
primary: Colors.white,
textStyle: const TextStyle(fontSize: 15),
),
onPressed: () {
showDialog(context: context, builder: (context) => const FeedbackDialog());
},
child: const Text('Make a report ?'),
),
],
),
),
const SizedBox(height: 12,),
],
)
),
),
),
],
),
);
}
And here is the code to the maps page.
import 'package:easy_geofencing/easy_geofencing.dart';
import 'package:easy_geofencing/enums/geofence_status.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'dart:async';
import 'package:geolocator/geolocator.dart';
import '../provider/location_provider.dart';
class GoogleMapPage extends StatefulWidget {
#override
_GoogleMapPageState createState() => _GoogleMapPageState();
}
class _GoogleMapPageState extends State<GoogleMapPage> {
late StreamSubscription<GeofenceStatus> geofenceStatusStream;
Geolocator geolocator = Geolocator();
String geofenceStatus = '';
bool isReady = false;
late Position position;
TextEditingController latitudeController = new TextEditingController();
TextEditingController longitudeController = new TextEditingController();
TextEditingController radiusController = new TextEditingController();
#override
void initState(){
getCurrentPosition();
super.initState();
// tz.initializeTimeZones();
Provider.of<LocationProvider>(context,listen:false).initalization();
}
getCurrentPosition() async {
position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
print("LOCATION => ${position.toJson()}");
isReady = (position != null) ? true : false;
EasyGeofencing.startGeofenceService(
// pointedLatitude: "2.2276356",
// pointedLongitude: "102.4568397",
pointedLatitude: "2.221395",
pointedLongitude: "102.453115",
radiusMeter: "30",
eventPeriodInSeconds: 5
);
StreamSubscription<GeofenceStatus> geofenceStatusStream = EasyGeofencing.getGeofenceStream()!.listen(
(GeofenceStatus status) {
print(status.toString());
});
}
setLocation() async {
await getCurrentPosition();
print("POSITION => ${position.toJson()}");
latitudeController =
TextEditingController(text: position.latitude.toString());
longitudeController =
TextEditingController(text: position.longitude.toString());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hotspot Checker"),
),
body: googleMapUI(),
);
}
}
Widget googleMapUI(){
EasyGeofencing.startGeofenceService(
pointedLatitude: "2.2741204",
pointedLongitude: "102.4448842",
radiusMeter: "10",
eventPeriodInSeconds: 5
);
Set<Circle> mycircles = Set.from([Circle(
circleId: CircleId('0'),
center: LatLng(2.221395, 102.453115),
radius: 6,
strokeWidth: 1,
fillColor:(Colors.red),
),
Circle(
circleId: CircleId('1'),
center: LatLng(2.2065488, 102.2244857),
radius: 4,
strokeWidth: 1,
fillColor:(Colors.yellow),
)]);
return Consumer<LocationProvider>(
builder:(consumerContext,model,child){
if(model.locationPosition != null)
{
return Column(
children: [
Expanded(
child: GoogleMap(
mapType:MapType.normal,
initialCameraPosition: CameraPosition(
target: model.locationPosition,
zoom: 18,
),
circles: mycircles,
myLocationEnabled: true,
myLocationButtonEnabled: true,
onMapCreated: (GoogleMapController controller){
},
),
),
],
);
}
return Container(
child: Center(child: CircularProgressIndicator(),),
);
}
);
}
Basically, I'm not sure how to make both of these pages combine together.

flutter error type 'Null' is not a subtype of type 'String'

so i want to print user name and user username in the profile page and in the end it shows it but for a few seconds there is a red screen that says The following _TypeError was thrown building Profile_page(dirty, state: _Profile_pageState#68414):
type 'Null' is not a subtype of type 'String'
this is the code of main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/name.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question1.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question2.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question3.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question4.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question5.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/photo.dart';
import 'package:gp1_7_2022/screen/home/Profile_Page.dart';
import 'package:firebase_core/firebase_core.dart';
/*pages */
import 'package:gp1_7_2022/screen/auth/signup_login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signup.dart';
import 'package:gp1_7_2022/screen/auth/Login/login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupConfirmationCode.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupPassword.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupBirthday.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupUsername.dart';
import 'package:gp1_7_2022/screen/auth/Login/forget_password.dart';
import 'package:gp1_7_2022/screen/settings.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(
initialRoute: "/",
routes: {
"/": (context) => MainPage(),
"/signup": (context)=> Signup(),
'/login':(context)=>Login(),
'/Profile_Page':(context) => Profile_page(uid: FirebaseAuth.instance.currentUser!.uid),
// '/confirmationCode':(context) => ConfirmationCode(),
// '/signupPassword':(context) => signupPassword(),
'/signupBirthday':(context) => SignupBirthday(),
'/signupUsername':(context) => SignupUsername(),
'/forget_password':(context) => forget_password(),
'/name':(context) => name(),
'/question1':(context) => question1(),
'/question2':(context) => question2(),
'/question3':(context) => question3(),
'/question4':(context) => question4(),
'/question5':(context) => question5(),
'/photo':(context) => Photo(),
'/settings':(context) => settings(),
}
)
);
}
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot){
if(snapshot.connectionState==ConnectionState.waiting){
return const Center(child: CircularProgressIndicator());
}else if(snapshot.hasError){
return const Center(child: Text("Something went wrong!"));
}else if(snapshot.hasData){
if(FirebaseAuth.instance.currentUser!.emailVerified && FirebaseAuth.instance.currentUser!.uid != null ){
String uid = FirebaseAuth.instance.currentUser!.uid;
return Profile_page(uid: uid );
}else{
String? x = FirebaseAuth.instance.currentUser!.email;
String y= x??" ";
return ConfirmationCode(email: y);
}
} else{
return const Signup_Login();
}
},
),
);
}
}
this is the code of profile_page.dart
// import 'dart:html';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:focused_menu/focused_menu.dart';
import 'package:focused_menu/modals.dart';
/*pages */
/*colors */
import 'package:gp1_7_2022/config/palette.dart';
import 'package:gp1_7_2022/Widgets/follow_button.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:gp1_7_2022/screen/settings.dart';
class Profile_page extends StatefulWidget {
final uid;
const Profile_page({Key? key, required this.uid}) : super(key: key);
#override
State<Profile_page> createState() => _Profile_pageState();
}
class _Profile_pageState extends State<Profile_page> {
var padding= 0.8;
var userData = {};
#override
void initState() {
super.initState();
getData();
}
/* get data method */
getData() async {
try {
if (widget.uid != null) {
var userSnap = await FirebaseFirestore.instance.collection('users').doc(
widget.uid).get();
userData = userSnap.data()!;
setState(() {
});
}
}
catch(e){
Alert(
context: context,
title: "Something went wrong!",
desc: e.toString(),
).show();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Palette.backgroundColor,
appBar: AppBar(
//appBar style
elevation: 0,
backgroundColor: Palette.backgroundColor,
automaticallyImplyLeading: false,//no arrow
//username
title: Padding(
padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text(
userData['username'],
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 24,
),
),
),
//setting icon
actions:[
FocusedMenuHolder(
//
menuWidth: MediaQuery.of(context).size.width * 0.4,
menuOffset: 0,
menuItemExtent: 49,
//list
menuItems: [
FocusedMenuItem(
title: const Text("Log out"),
trailingIcon: const Icon(Icons.logout),
onPressed: (){
/*go to sign up page*/
Navigator.pushNamed(context, '/');
return FirebaseAuth.instance.signOut();
}
),
FocusedMenuItem(
title: const Text("Settings"),
trailingIcon: const Icon(Icons.settings),
onPressed: (){
Navigator.of(context).popAndPushNamed('/settings');
},
),
],
openWithTap: true,
onPressed: (){},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Image.asset(
"assets/menu-icon.png",
height: 25,
width: 25,
),
),
),
],
),
body: ListView(
children: [
Container(
margin: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
//user photo
const Padding(
padding: EdgeInsets.fromLTRB(0, 0, 40, 0),
child: CircleAvatar(
backgroundColor: Colors.white ,
child: Icon(
Icons.account_circle_sharp,
color: Colors.grey,
size: 90,
),
),
),
//end user photo
Expanded(
flex: 7,
child: Column(
children: [
SizedBox(height:40,),
//post, followers and following
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildStatColumn(20, "posts"),
buildStatColumn(150, "Followers"),
buildStatColumn(10, "Following"),
],
),
//end post, followers and following
],
),
),
],
),
//username
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.fromLTRB(10, 40, 0, 0),
child: Text(
userData['name'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
//end of username
//bio
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.fromLTRB(10, 1, 0, 0),
child: const Text(
'bio',
style: TextStyle(
fontSize: 16,
),
),
),
//end of bio
//edit profile button
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FollowButton(
text: 'Edit profile',
backgroundColor: Palette.backgroundColor,
borderColor: Palette.grey,
textColor: Colors.black,
function: () {},
)
],
),
//end of button
],
),
),
],
),
);
}
}
// function to show following/followers/# of posts
Column buildStatColumn(int num, String label) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
num.toString(),
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Container(
margin: const EdgeInsets.only(top: 4),
child: Text(
label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
],
);
}
enter image description here
Show some other widgets until data is not fully loaded.
class _Profile_pageState extends State<Profile_page> {
...
bool _isloaded = false; // Add this boolean
In getData function
getData() async {
try {
...
setState(() {
_isloaded = true; // when data is loaded update state
});
}
...
In build, return widget according to data(user)
#override
Widget build(BuildContext context) {
return _isloaded == false ?
Center(
child: CircularProgressIndicator(), // Show indicator
)
: Scaffold(
backgroundColor: Palette.backgroundColor,
...
); //Scaffold
You're assuring flutter that the data isn't null which will result in a momentary error. You can try either setting a load bool that sets to true when the data arrives or using the ?? operator. e.g userData['name'] ?? "loading" which will print loading incase the userData['name'] is null

How can I use same navigation route I used for bottomnavigationbar in drawer widget in flutter?

I already have a bottom navigation bar which navigates to different pages.
then I add a drawer which I want it to change the widget in the body only, but the issue is that I made the drawer in another page and I called it, so it is not responding or I'm not calling it perfectly as I should.
Below is the navigation for the bottomnavigationbar, I have imported all necessary files
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int currentTab = 0;
final tabs = [
IndexPage(),
Save(),
Invest(),
Wallet(),
Cards(),
];
#override
Widget build(BuildContext context) {
return MaterialApp(
color: Colors.grey[900],
debugShowCheckedModeBanner: false,
title: 'Flochristos App',
theme: ThemeData(),
home: Scaffold(
backgroundColor: Colors.black,
resizeToAvoidBottomPadding: false,
resizeToAvoidBottomInset: false,
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.grey[900],
title: Text(
'PettySave',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.brightness_7_outlined),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.keyboard_arrow_down_sharp),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.account_circle_rounded),
onPressed: () {},
),
],
//shadowColor: Colors.grey,
),
body: tabs[currentTab], //this is where I want to change the pages
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setState(() {
currentTab = index;
});
},
currentIndex: currentTab,
backgroundColor: Colors.grey[900],
unselectedIconTheme: IconThemeData(color: Colors.grey),
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
// ignore: deprecated_member_use
title: Text(
"Home",
),
),
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.pagelines),
// ignore: deprecated_member_use
title: Text(
"Save",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.trending_up),
// ignore: deprecated_member_use
title: Text(
"Invest",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_balance_wallet_outlined),
// ignore: deprecated_member_use
title: Text(
"Wallet",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.credit_card),
// ignore: deprecated_member_use
title: Text(
"Cards",
),
),
],
),
),
);
}
}
}
that's the main.dart code
body: tabs[currentTab], //this is where I want to change the pages
then I created another page for drawer which I called all appropriate pages
from one of the list style in the slidedrawer.dart , I'm trying to set currentTab to any index I want.... but it's not working.
ListTile(
contentPadding: EdgeInsets.fromLTRB(30, 0, 0, 0),
leading: Icon(
Icons.trending_up,
color: Colors.grey[500],
),
title: Text(
'Investments',
style: TextStyle(
color: Colors.grey[300],
fontWeight: FontWeight.bold,
),
),
onTap: () {
setState(() {
currentTab = 1;
});
},
),
I want the index to turn to Save()
List<Widget> tabs = [
IndexPage(),
Save(),
Invest(),
Wallet(),
Cards(),
];
There are many ways to add a drawer to an app, but the most common one is to use the drawer property thats within the Scaffold() Widget.
e.x.
Scaffold(
appBar: AppBar(
...
),
drawer: Drawer() // This is where you call the new Widget(class) that you made the drawer in
body: tabs[currentTab],
);
This is how I understood your question, correct me if I misunderstood it.
This is an example how I used a navigation tab bar in one of my projects.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/auth.dart';
import '../../../widgets/auth/admin/main_drawer.dart';
import '../../auth/profile_screen.dart';
import '../../home_screen.dart';
import './../projects_screen.dart';
class AdminTabBarScreen extends StatefulWidget {
static const routeName = 'auth-tab-bar-view';
#override
_AdminTabBarScreenState createState() => _AdminTabBarScreenState();
}
class _AdminTabBarScreenState extends State<AdminTabBarScreen>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
_tabController = TabController(length: 3, vsync: this);
super.initState();
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final auth = Provider.of<Auth>(context);
return Scaffold(
// appBar: AppBar(
// title: Text('SHTEGU'),
// ),
extendBody: true,
drawer: MainDrawer(), // this is where I called my drawer
body: Container(
// color: Colors.blueAccent,
child: TabBarView(
children: <Widget>[
HomeScreen(),
ProjectsScreen(),
ProfileScreen(),
// LoginScreen(),
],
controller: _tabController,
),
),
bottomNavigationBar: Container(
padding: EdgeInsets.all(16.0),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
child: Container(
color: Colors.black26,
child: TabBar(
labelColor: Color(0xFFC41A3B),
unselectedLabelColor: Colors.white,
labelStyle: TextStyle(fontSize: 13.0),
indicator: UnderlineTabIndicator(
borderSide: BorderSide(color: Colors.black54, width: 0.0),
insets: EdgeInsets.fromLTRB(50.0, 0.0, 50.0, 40.0),
),
//For Indicator Show and Customization
indicatorColor: Colors.black54,
tabs: <Widget>[
Tab(
text: 'Home',
),
Tab(
text: 'Projects',
),
Tab(
text: 'Profile',
),
// Tab(
// text: 'Login',
// ),
],
controller: _tabController,
),
),
),
),
);
}
}
Here is how I called the class above to check if admin
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../screens/auth/admin/admin_tab_bar_screen.dart';
import '../../screens/auth/user_tab_bar_screen.dart';
import '../../providers/auth.dart';
class AuthTabBarScreen extends StatelessWidget {
static const routeName = 'auth-tab-bar-view';
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: Provider.of<Auth>(context, listen: false).isAdmin(),
builder: (context, snapshot) => snapshot.hasData
? snapshot.data
? AdminTabBarScreen()
: UserTabBarScreen()
: CircularProgressIndicator(), // while you're waiting for the data, show some kind of loading indicator
);
}
}
And here is my drawer:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../screens/auth/admin/register_user_screen.dart';
import '../../../screens/auth/auth_tab_bar_screen.dart';
import '../../../screens/tab_bar_screen.dart';
import '../../../providers/auth.dart';
class MainDrawer extends StatelessWidget {
Widget buildListTile(
String title, IconData icon, Function tapHandler, BuildContext ctx) {
return ListTile(
tileColor: Color(0xffF2F7FB),
selectedTileColor: Theme.of(ctx).accentColor,
leading: Icon(
icon,
size: 26,
color: Theme.of(ctx).primaryColor,
),
title: Text(
title,
style: TextStyle(
fontFamily: 'RobotoCondensed',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Theme.of(ctx).primaryColor,
),
),
onTap: tapHandler,
);
}
#override
Widget build(BuildContext context) {
final authData = Provider.of<Auth>(context, listen: false);
return Drawer(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
buildListTile(
'Home',
Icons.home_rounded,
() {
Navigator.of(context)
.pushReplacementNamed(AuthTabBarScreen.routeName);
},
context,
),
buildListTile(
'Add user',
Icons.person_add_alt_1_rounded,
() {
// Navigator.of(context).pop();
Navigator.of(context)
.pushReplacementNamed(RegisterUserScreen.routeName);
},
context,
),
buildListTile(
'Sign Out',
Icons.exit_to_app_rounded,
() {
authData.signOut();
},
context,
),
],
),
),
),
);
}
}
Hope this is at least of help to you :D

Categories

Resources