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()),
);
Related
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()),
);
This is my homepage.dart. The error here said that there is an unexpected null value. I've been trying to debug this for the day but i still could not manage to find it, how to solve this problem? When i try to run the code. It won't shows the data from the 'Parking' which is inside the firestore database. The data was indeed there but it wont show inside this page. Can anyone help me with this ?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'addparking.dart';
class AdminHomePage extends StatefulWidget {
const AdminHomePage({Key? key}) : super(key: key);
#override
State<AdminHomePage> createState() => _AdminHomePageState();
}
class _AdminHomePageState extends State<AdminHomePage> {
CollectionReference ref = FirebaseFirestore.instance.collection('Parking');
//DELETE
Future<void> _deleteProduct(String productId) async {
await ref.doc(productId).delete();
// Show a snackbar
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('You have successfully deleted a product')));
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightBlueAccent,
appBar: AppBar(
backgroundColor: Color(0xFF121212),
elevation: 0.0,
title: const Text('Admin Page',
style:TextStyle(
color: Color(0xFFFFFFFF),
fontWeight: FontWeight.bold,
),
),
centerTitle:true,
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('Parking').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if(snapshot.hasData){
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context,index){
final DocumentSnapshot documentSnapshot = (snapshot.data!.docs[index]);
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
title: Text(documentSnapshot['level']),
subtitle: Text(documentSnapshot['parking']),
trailing: Row(
children: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: (){}
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => _deleteProduct(documentSnapshot.id),
),
],
),
),
);
});
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
drawer: const NavigationDrawer(),
);
}
}
class NavigationDrawer extends StatelessWidget {
const NavigationDrawer({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Drawer(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
buildHeader(context),
buildMenuItems(context),
],
),
),
);
Widget buildHeader (BuildContext context) => Container(
color: Colors.amber,
child: InkWell(
onTap: (){},
child: Container(
padding: EdgeInsets.only(
top: 24 + MediaQuery.of(context).padding.top,
bottom: 24,
),
child: Column(
children: const [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://www.shutterstock.com/image-vector/people-icon-vector-illustration-flat-design-405042562'
),
),
SizedBox(height: 12),
Text(
'Admin'
)
],
),
),
),
);
Widget buildMenuItems (BuildContext context) => Container(
padding: const EdgeInsets.all(24),
child: Wrap(
children: [
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Home'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Add Parking'),
onTap:(){
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(builder: (context) => AddParking(),));
}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Delete Parking'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Update Parking'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Report Feedback'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Payment Setup'),
onTap:(){}
),
],
),
);
}
try
1- documentSnapshot?['level']
2- documentSnapshot?['parking']
It's really hard to track down the error without the stacktrace but you can try to change the following lines:
Text(documentSnapshot['level'] ?? "")
Text(documentSnapshot['parking'] ?? "")
Text() requires a string as a parameter that isn't null and documentSnapshot['level'] returns an nullable value because the key level might not exist. Same for parking.
There're two buttons from my WelcomeScreen, when this page is loaded, two buttons will be pressed automatically.
two buttons were used by the external widget"RoundButton".
Why I knew those buttons were being pressed, because I was using print function, and I saw the first button and second button were pressed automatically and sequentially.
Navigator.pushNamed(context, LoginScreen2.id);
Navigator.pushNamed(context, RegistrationScreen.id);
Navigator.pushNamed(context, LoginScreen2.id);
Navigator.pushNamed(context, RegistrationScreen.id);
Is there any setting I should set to prevent this problem? Thank you.
environment:
sdk: ">=2.16.0 <3.0.0"
build this program on Chroma
welcome_screen.dart
import 'package:trashcollectionday/Screens/login_screen2.dart';
import 'package:trashcollectionday/screens/registration_screen.dart';
import 'package:flutter/material.dart';
import 'package:trashcollectionday/screens/login_screen.dart';
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:trashcollectionday/components/roundedButton.dart';
class WelcomeScreen extends StatefulWidget {
static const String id = 'welcome_screen';
// will be a class, you don't have to to WelcomeScreen().index
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> with SingleTickerProviderStateMixin {
late AnimationController controller;
late Animation animation;
late Animation animation1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
children: <Widget>[
Hero(
tag: 'logo',
child: Container(
child: Image.asset('images/logo.png'),
height: 60,
),
),
DefaultTextStyle(
style: const TextStyle(
fontSize: 40.0,
fontFamily: 'Horizon',
),
child: AnimatedTextKit(
animatedTexts: [TypewriterAnimatedText('Application')],
),
),
],
),
const SizedBox(
height: 48.0,
),
RoundButton(
title: 'Log In',
colour: Colors.lightBlue,
onPressed: () {
print('Log In');
//Go to login screen.
Navigator.pushNamed(context, LoginScreen2.id);
},
),
RoundButton(
title: 'Register',
colour: Colors.blueAccent,
onPressed: () {
print('Reg');
//Go to login screen.
Navigator.pushNamed(context, RegistrationScreen.id);
},
),
],
),
),
);
}
}
roundedButton.dart
import 'package:flutter/material.dart';
class RoundButton extends StatelessWidget {
const RoundButton({required this.title, required this.colour, required this.onPressed});
final Color colour;
final String title;
final Function onPressed;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Material(
elevation: 5.0,
color: colour,
borderRadius: BorderRadius.circular(30.0),
child: MaterialButton(
onPressed: onPressed(),
minWidth: 200.0,
height: 42.0,
child: Text(
title,
),
),
),
);
}
}
main. dart
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: Colors.teal,
textTheme: const TextTheme(bodyText2: TextStyle(color: Colors.yellow)),
primaryColor: Colors.orange,
),
initialRoute: WelcomeScreen.id,
// home: ItemDetailsScrrent(),
routes: {
WelcomeScreen.id : (context) => WelcomeScreen(),
LoginScreen2.id: (context) => LoginScreen2(),
RegistrationScreen.id: (context) => RegistrationScreen(),
RecordScreen.id: (context) => RecordScreen(),
LoginScreen.id: (context) => LoginScreen(),
ItemDetailsScrrent.id: (context) => ItemDetailsScrrent(),
},
// home: const LoginScreen(),
);
}
}
You should remove brackets from RoundButton class in
onPressed: onPressed()
to
onPressed:onPressed
and add brackets to this line of code
final Function onPressed;
as here
final Function() onPressed;
I'm not sure but maybe issue occurs because of you are using onPressed: onPressed() in RoundButton.
You can use this function without brackets like this; onPressed: onPressed,
I'm building my quiz app and my quizpage is taking solid shape but here's a problem i have. I added a Willpopscope just so that my users can't go back to the beginning when the quiz has started and it brings up a dialog box. Here's the code:
import 'dart:convert';
//import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class GetJson extends StatelessWidget {
const GetJson({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: DefaultAssetBundle.of(context).loadString("assets/python.json"),
builder: (context, snapshot) {
var mydata = jsonDecode(snapshot.data.toString());
if (mydata == null) {
return Scaffold(
body: Center(
child: Text(
"Loading",
),
),
);
} else {
return QuizPage();
}
},
);
}
}
class QuizPage extends StatefulWidget {
QuizPage({Key? key}) : super(key: key);
#override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
Widget choicebutton() {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 20.0,
),
child: MaterialButton(
onPressed: () {},
child: Text(
"option 1",
style: TextStyle(
color: Colors.white,
fontFamily: "Alike",
fontSize: 16.0,
),
maxLines: 1,
),
color: Colors.indigo,
splashColor: Colors.indigo[700],
highlightColor: Colors.indigo[700],
minWidth: 200.0,
height: 45.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
),
);
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Quizstar",
),
content: Text("You Can't Go Back At This Stage"),
actions: [
// ignore: deprecated_member_use
FlatButton(onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Ok",
),
)
],
)
);
},
child: Scaffold(
body: Column(
children: [
Expanded(
flex: 3,
child: Container(
padding: EdgeInsets.all(15.0),
alignment: Alignment.bottomLeft,
child: Text(
"This is a sample question which will be displayed?",
style: TextStyle(
fontSize: 16.0,
fontFamily: "Quando",
),
),
),
),
Expanded(
flex: 6,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
choicebutton(),
choicebutton(),
choicebutton(),
choicebutton(),
],
),
),
),
Expanded(
flex: 1,
child: Container(
alignment: Alignment.topCenter,
child: Center(
child: Text(
"30",
style: TextStyle(
fontSize: 35.0,
fontWeight: FontWeight.w700,
fontFamily: "Times New Roman",
),
),
),
),
),
],
),
),
);
}
}
The error is in the showDialog() but i can't seem to figure it out.
Thanks a lot guys.
This might help
On your willpop scope function do this instead
onWillPop: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Quizstar",
),
content: Text("You Can't Go Back At This Stage"),
actions: [
// ignore: deprecated_member_use
FlatButton(onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Ok",
),
)
],
)
);
return true;
),
child : your widget
Okay i figured it out
return WillPopScope(
onWillPop: () async {
print("Back Button Pressed");
final shouldPop = await showWarning(context);
return shouldPop ?? false;
},
Then i went ahead to define showWarning like this, then defined my dialog box inside it:
Future<bool?> showWarning(BuildContext context) async => showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text("Quizstar"),
content: Text("You cannot go back at this stage"),
actions: [
ElevatedButton(
onPressed: () => Navigator.pop(context, false),
child: Text("Okay"),
),
//ElevatedButton(
// onPressed: () => Navigator.pop(context, true),
// child: Text("Yes"),
//),
],
),
);
Tips: Don't forget to make the future a bool by writing inside it with it's '?'
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