dart 如何将未来函数传递给void函数

oxf4rvwz  于 2023-03-10  发布在  其他
关注(0)|答案(2)|浏览(133)

我想知道如果我想把函数传递给一个void函数是否可能?
在下面的例子中,我有一个void函数firstFunction(),然后我想在其中传递print('do something');print('do final Function');这样的函数。
这是代码示例

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
  }
}
gg0vcinb

gg0vcinb1#

这确实是可能的。你的代码看起来是正确的,除了你的函数声明。我想应该是这样的:

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(不测试代码,如果仍然有错误,请让我知道)

pepwfjgg

pepwfjgg2#

您应该传递Function类型的myFunctions类型,而不是void
示例:

void firstFunction({required Function myFunctions}) async {
    print('do first function');
    await myFunctions(); // call the function that was passed as an argument
  }

相关问题