【问题标题】:Flutter - Execute two Functions, one via a constructor and one from inside a class at the same timeFlutter - 执行两个函数,一个通过构造函数,一个同时在类内部
【发布时间】:2022-01-18 17:18:28
【问题描述】:

在学习 Futter 的过程中,遇到了如何同时执行两个函数的问题。一个来自 Button 类中的构造函数的函数以及另一个在 Button 类中的函数。

这是一个示例代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          color: Colors.blueGrey,
          child: Center(
            child: Button(
              whenButtonPressed: () {
                print("Button pressed from outside the Button Class");
              },
            ),
          ),
        ),
      ),
    );
  }
}

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: whenButtonPressed,
                 //print("Button pressed from inside the Button Class"); <- Execute this additionally. 
      backgroundColor: Colors.red,
    );
  }
}

我已经尝试将 onPressed 和其他打印语句放在大括号中。但随后只执行打印语句“从按钮类内部按下按钮”,而不执行 whenButtonPressed 函数。这种行为的原因是什么,我该如何正确编写?

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: (){ whenButtonPressed; // <-now this is not executed. 
                 print("Button pressed from inside the Button Class");},

      backgroundColor: Colors.red,
    );
  }
}

【问题讨论】:

  • 为什么不使用 bloc 和 future 方法进行多个同步调用
  • 尝试调用这个函数,比如whenButtonPressed(),而不是whenButtonPressed。如果没有(),它只在分配函数时起作用,比如onPressed: whenButtonPressed
  • 是whenButtonPressed一个函数吗?
  • @彼得科尔泰。谢谢,这行得通。我使用您的解决方案为可能有相同问题的其他用户创建了我的问题的答案。

标签: flutter function class constructor


【解决方案1】:

正如@Peter Koltai 在他的解决方案中所说,您必须将 () 添加到 whenButtonPressed -> whenButtonPressed()。 完成这项工作的正确代码是:

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        whenButtonPressed!();
        print("Button pressed from inside the Button Class");
      },
      backgroundColor: Colors.red,
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 2014-08-01
    • 2012-06-22
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多