Home > front end >  Flutter - Execute two Functions, one via a constructor and one from inside a class at the same time
Flutter - Execute two Functions, one via a constructor and one from inside a class at the same time

Time:01-22

While learning Futter, I ran into a problem on how to execute two functions at the same time. One function which comes from a constructor in the Button Class together with another function that is inside the Button class.

This is a example code:

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

I have already tried to put the onPressed and the other print statement in curly brackets. But then only the print statement "Button pressed from inside the Button Class" is executed and not the whenButtonPressed function. What is the reason for this behaviour and how can I write this correctly?

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

CodePudding user response:

As @Peter Koltai states in his solution you have to add () to whenButtonPressed -> whenButtonPressed(). The correct code to make this work is:

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,
    );
  }
}
  •  Tags:  
  • Related