简体   繁体   English

ElevatedButton onPressed function 自行执行

[英]ElevatedButton onPressed function executing on its own

I am building a quiz app which has a homepage that allows you to select the subject you want to be quizzed on and then displays the questions.我正在构建一个测验应用程序,它有一个主页,允许您 select 您想被测验的主题,然后显示问题。 However, when I run my code, it doesn't display this homepage and instead displays the questions that should come if the last button was pressed.但是,当我运行我的代码时,它不会显示此主页,而是显示如果按下最后一个按钮应该出现的问题。 Here are the relevant snippets of my code:以下是我的代码的相关片段:

[main.dart] [main.dart]

import 'package:flutter/material.dart';
import './page.dart';
import './s_button.dart';

class _MyAppState extends State<MyApp> {

  List subjects = ["biology", "chemistry", "physics"];

  bool PageIndex = true; 

  String selected_subject = "";

  void changePage(s) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        selected_subject = s;
        PageIndex = false;
      });
    });
  } 

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.pink[100],
        body: PageIndex ? Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Quiz App", style: TextStyle(fontSize: 24)),
              SizedBox(height: 30),
              Text("Select a subject"), 
              SizedBox(height: 40),
              ...subjects.map((sub){
                return SubjectButton(pageHandler: changePage, subject: sub);
              })
            ]
          ),
        ) 
        : QuizPage(selected_subject) 
      )
    );
  }
}

[s_button.dart] [s_button.dart]

import 'package:flutter/material.dart';

class SubjectButton extends StatelessWidget {

  final Function pageHandler;
  final String subject;

  const SubjectButton({Key? key, required this.pageHandler, required this.subject}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: 120, 
          height: 60,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              primary: Colors.pink,
              elevation: 5, 
            ),
            onPressed: pageHandler(subject),
            child: Text(subject) 
          )
        ),
        SizedBox(height: 20)
      ],
    );
  }
}

When I run this however, QuizPage() is displayed with the question for physics, which is the last button as per my initial list.然而,当我运行它时,QuizPage() 会显示物理问题,这是我最初列表中的最后一个按钮。 Somehow, my PageIndex is being set to false and my selected_subject is being set to "physics" before I even have a chance to click on the buttons.不知何故,我的 PageIndex 被设置为 false 并且我的 selected_subject 被设置为“物理”,甚至在我有机会点击按钮之前。 What is going wrong?出了什么问题?

onPressed: pageHandler(subject) means, while building the widget, it will be called. onPressed: pageHandler(subject)表示,在构建小部件时,它将被调用。

To call on runtime use调用运行时使用

onPressed:()=> pageHandler(subject),

use利用

 onPressed:()=> pageHandler(subject),

instead of代替

onPressed: pageHandler(subject),

Check the onPressed line, you're directly executing the function and assigning the return to the onPressed but not binding it.检查onPressed行,您正在直接执行 function 并将返回分配给onPressed但不绑定它。

onPressed: pageHandler(subject),

You may meant to do the following:您可能打算执行以下操作:

onPressed: () => pageHandler(subject),

Like this, it won't get automatically executed at first:)像这样,一开始它不会自动执行:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM