onPressed from MaterialButton were trigged when the page from initialRoute - android

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,

Related

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()),
);

Why is my named routing is not working as expected In flutter?

I created the named routes in my main but its not navigating.
Inside the mainbutton widget i'm passing the navigator it accepts three parameters all of them are required...
import 'package:flutter/material.dart';
import 'package:texty/screens/welcome_screen.dart';
import 'package:texty/screens/login_screen.dart';
import 'package:texty/screens/registration_screen.dart';
import 'package:texty/screens/chat_screen.dart';
void main() => runApp(FlashChat());
class FlashChat extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: WelcomeScreen.id,
routes: {
WelcomeScreen.id: (context) => WelcomeScreen(),
ChatScreen.Id: (context) => ChatScreen(),
LoginScreen.Id: (context) => LoginScreen(),
RegistrationScreen.Id: (context) => RegistrationScreen(),
},
);
}
}
my welcome screen ->
import 'package:flutter/material.dart';
import 'package:texty/widgets/mainbutton.dart';
import 'login_screen.dart';
import 'registration_screen.dart';
import 'package:animated_text_kit/animated_text_kit.dart';
class WelcomeScreen extends StatefulWidget {
static const String id = 'welcome_screen';
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen>
with SingleTickerProviderStateMixin {
late AnimationController controller;
late Animation animation;
#override
void initState() {
super.initState();
controller =
AnimationController(duration: Duration(seconds: 1), vsync: this);
animation = ColorTween(begin: Colors.blueGrey, end: Colors.white)
.animate(controller);
controller.forward();
controller.addListener(() {
setState(() {});
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: animation.value,
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.0,
),
),
TypewriterAnimatedTextKit(
text: ['Texxty '],
textStyle: TextStyle(
fontSize: 45.0,
fontWeight: FontWeight.w900,
),
),
],
),
SizedBox(
height: 48.0,
),
mainButton(
title: 'Log In',
colour: Colors.lightBlueAccent,
onPressed: () {
Navigator.pushNamed(context, LoginScreen.Id);
},
),
mainButton(
title: 'Register',
colour: Colors.blueAccent,
onPressed: () {
Navigator.pushNamed(context, RegistrationScreen.Id);
},
),
],
),
),
);
}
}
try an other Option
instead of naming the pages
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);

How can I get the Navigator to work in Flutter?

I'm new on Flutter, so obviously I'm messing up somewhere in the code that I'm not being able to figure out. Basically I have a login screen from which I want to navigate to a second screen, but when I select the button absolutely nothing happens, nor does an error appear. I have been looking all over for an answer but none of them can solve the problem. I hope someone can help me. (The texts of the buttons are in Spanish).
This is the main.dart:
import 'package:flutter/material.dart';
import 'package:go_out/screens/screens.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: 'home',
routes: {
'home': (_) => const HomeScreen(),
'signInEmail': (_) => const SignInEmail(),
},
);
}
}
This is the home_screen.dart:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../widgets/widgets.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: Colors.black,
body: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Center(
child: _SignInPageDesign(),
),
),
);
}
}
class _SignInPageDesign extends StatelessWidget {
const _SignInPageDesign({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10, right: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'images/logo.png',
height: 200,
fit: BoxFit.cover,
),
const SizedBox(
height: 30,
),
CustomElevatedButtonWithoutIcon(
text: 'Crear Cuenta',
onPressed: () => Navigator.pushNamed(context, 'signInEmail'),
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Facebook',
onPressed: () {},
icon: FontAwesomeIcons.facebookSquare,
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Google',
onPressed: () {},
icon: FontAwesomeIcons.google,
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Apple',
onPressed: () {},
icon: FontAwesomeIcons.apple,
),
const SizedBox(height: 12),
const CustomTextButton(
text: 'Iniciar sesión',
),
const SizedBox(height: 12),
CustomElevatedButtonWithoutIcon(
text: 'Registrar comercio',
onPressed: () {},
),
],
),
);
}
}
This is the problem with home_screen.dart which does not return any value.
CustomElevatedButtonWithoutIcon(
text: 'Crear Cuenta',
onPressed: () => Navigator.pushNamed(context, 'signInEmail'),
),
This is the second screen I want to go to sign_in_email.dart:
import 'package:flutter/material.dart';
class SignInEmail extends StatelessWidget {
const SignInEmail({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromRGBO(254, 80, 0, 1),
),
);
}
}
This is the class CustomElevatedButtonWithoutIcon:
import 'package:flutter/material.dart';
class CustomElevatedButtonWithoutIcon extends StatelessWidget {
const CustomElevatedButtonWithoutIcon({
Key? key,
required this.text,
required this.onPressed,
}) : super(key: key);
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text(
text,
style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
onPressed: () {},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all<Size>(const Size(0, 50)),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromRGBO(254, 80, 0, 1)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
),
),
);
}
}
You didn't pass anything onPressed funciton, you kept it empty, so nothing was working, just pass your onPressed function inside ElevatedButton like below
import 'package:flutter/material.dart';
class CustomElevatedButtonWithoutIcon extends StatelessWidget {
const CustomElevatedButtonWithoutIcon({
Key? key,
required this.text,
required this.onPressed,
}) : super(key: key);
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text(
text,
style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
onPressed: onPressed,
style: ButtonStyle(
fixedSize: MaterialStateProperty.all<Size>(const Size(0, 50)),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromRGBO(254, 80, 0, 1)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
),
),
);
}
}
Also it's best practice to use RouteGenerator, create a route_generator.dart file with the following code below
import 'package:flutter/material.dart';
class RouterCustom {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case "home":
return MaterialPageRoute(
builder: (_) => const HomeScreen(),
settings: const RouteSettings(name: "home"),
);
case "signInEmail":
return MaterialPageRoute(
builder: (_) => const SignInEmail(),
settings: const RouteSettings(name: "signInEmail"),
);
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
),
settings: const RouteSettings(name: "404"),
);
}
}
}
Then pass it to your main method's router param
MaterialApp(
initialRoute: "home",
onGenerateRoute: RouterCustom.generateRoute,
)
CustomElevatedButtonWithoutIcon doesn't actually do anything when pressed, onPressed: () {}, should be onPressed: onPressed,.
A simple way to detect this, is by adding a print statement right before navigating, or adding a breakpoint. If neither is triggered, the function isn't being called and your issue isn't in the Navigation.
Your widget CustomElevatedButtonWithoutIcon is not calling any function after it is being pressed
You have this
onPressed: () {},
Change it for
onPressed: onPressed

Black-Screen with the FlatButton in the AppBar

My App contains basically 2 parts -> Appbar (with 1 Button) and BottomNavigationBar (with some buttons that works properly). The problem came when I pressed the Appbar button (goes to a black screen instead of show the "manual_page.dart")
this is the content of the 2 files (the home_page.dart and manual_page.dart):
home_page.dart
import 'package:flutter/material.dart';
import 'package:opening_a_pdf/manual_page.dart';
import 'package:opening_a_pdf/first_page.dart';
import 'package:opening_a_pdf/second_page.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedPage = 0;
List<Widget> pageList = List<Widget>();
#override
void initState() {
pageList.add(FirstPage());
pageList.add(SecondPage());
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFFAFAFA),
appBar: AppBar(
backgroundColor: Colors.black,
title: const Text('Aplicación en Desarrollo'),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
child: Text(
'MANUAL',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Voice()),
);
}
)
],
),
body: IndexedStack(
index: _selectedPage,
children: pageList,
),
bottomNavigationBar: BottomNavigationBar(
// type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.compare_arrows),
title: Text('Conectividad'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.blur_on),
title: Text('Captura Datos'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.graphic_eq),
title: Text('Voz'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.list),
title: Text('Comandos'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.settings),
title: Text('Ajustes'),
),
],
currentIndex: _selectedPage,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _onItemTapped(int index) {
setState(() {
_selectedPage = index;
});
}
}
manual_page.dart
import 'package:flutter/material.dart';
// ignore: camel_case_types
class Voice extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sección de Órdenes por Voz"),
),
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
bottom: 0,
width: MediaQuery.of(context).size.width,
child: Center(
child: MaterialButton(
onPressed: () {},
color: Colors.red,
),
),
)
],
),
);
}
}
Try to initial the height of container in the second screen before Stack
There are no errors in the code. Works correctly. Maybe the fault is in the main () or in the emulator.
Code in main:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
I executed your code and found no problem with it:
But you can put empty Container() as the child of MaterialButton().
Corrected code:
MaterialButton(
onPressed: () {},
color: Colors.red,
child:Container(),
),

How to Set Timer Countdown in Flutter for 30 Second with OnPressed FAB Button?

Currently, I have write codes for making up the counter app with two buttons. 1 raised button to reset and one fab button for increment counter.
is it possible to add the countdown timer to implement on FAB button? When FAB button clicks 20-second countdown timer start.
Also, I have found below thread for the same type of function implement. But I don't where to put codes in my app to implement countdown work on FAB button.
How to make a countdown in flutter?
import 'package:flutter/material.dart';
import 'dart:ui';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Counter App'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
int _counter = 0;
AnimationController controller;
bool _isButtonDisabled;
Duration get duration => controller.duration * controller.value;
bool get expired => duration.inSeconds == 0;
#override
void initState() {
controller = AnimationController(
vsync: this,
duration: Duration(seconds: 20),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'number $_counter added',
),
AnimatedBuilder(
animation: controller,
builder: (BuildContext context, Widget child) {
return new Text(
'${duration.inSeconds}',
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50.0,
),
);
}),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new RaisedButton(
padding: const EdgeInsets.all(15.0),
textColor: Colors.white,
color: Colors.redAccent,
onPressed: () {
setState(() {
controller.reset();
_counter = 0;
});
},
child: new Text("Reset"),
),
new RaisedButton(
onPressed: () => setState(() {
controller.reverse(from: 1);
}),
textColor: Colors.white,
color: Colors.purple,
padding: const EdgeInsets.all(15.0),
child: new Text(
"Start",
),
),
],
),
],
),
),
bottomNavigationBar: BottomAppBar(
child: Container(
height: 50.0,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() {
_counter++;
}),
tooltip: 'Increment Counter',
child: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
}
you can use anywhere this code.
Timer(Duration(seconds: 30), () {
//checkFirstSeen(); your logic
});
try the following:
import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Counter App'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
int _counter = 0;
AnimationController controller;
Duration get duration => controller.duration * controller.value;
bool get expired => duration.inSeconds == 0;
#override
void initState() {
controller = AnimationController(
vsync: this,
duration: Duration(seconds: 20),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedBuilder(
animation: controller,
builder: (BuildContext context, Widget child) {
return new Text(
'${duration.inSeconds}',
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50.0,
),
);
}),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new RaisedButton(
padding: const EdgeInsets.all(15.0),
textColor: Colors.white,
color: Colors.redAccent,
onPressed: () {
setState(() {
controller.reset();
});
},
child: new Text("Reset"),
),
],
),
],
),
),
bottomNavigationBar: BottomAppBar(
child: Container(
height: 50.0,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() {
controller.reverse(from: 1);
}),
tooltip: 'Increment Counter',
child: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
}

Categories

Resources