'onPressed from MaterialButton were trigged when the page from initialRoute

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.

  1. Navigator.pushNamed(context, LoginScreen2.id);
  2. Navigator.pushNamed(context, RegistrationScreen.id);
  3. Navigator.pushNamed(context, LoginScreen2.id);
  4. 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(),
    );
  }
}


Solution 1:[1]

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;

Solution 2:[2]

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,

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Furkan AbbasioÄŸlu