skip to Main Content

I wonder if it is possible if I want to pass functions to a void function?

As in the below example I have a void function as firstFunction(), then I want to pass functions like print('do something'); and print('do final Function'); in it.

This is the code example

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            firstFunction(
              myFunctions: () async {
                // this is functions that I want to execute after the first function
                await print('do something');
                await print('do final Function');
              },
            );
          },
          child: const Text("Press"),
        ),
      ),
    );
  }

  void firstFunction({void myFunctions}) {
    print('do first function');
    myFunctions; // this is functions that I want to execute after the first function
  }
}

2

Answers


  1. This is indeed possible. Your code seems correct, except your function declaration. I think it should be something like this:

    void firstFunction({required Function myFunctions}) async {
      print('do first function');
      await myFunctions(); // this is functions that I want to execute after the first function
    }
    

    (Dind’t test the code, let me know if there are still errors)

    Login or Signup to reply.
  2. You should pass the type of myFunctions of type Function instead of void.

    Example:

      void firstFunction({required Function myFunctions}) async {
        print('do first function');
        await myFunctions(); // call the function that was passed as an argument
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search