【问题标题】:How to pass Navigator function as a parameter in Dart?如何在 Dart 中将 Navigator 函数作为参数传递?
【发布时间】:2022-01-21 16:47:52
【问题描述】:

我有一个代表按钮的自定义小部件,该小部件位于“lib”文件夹内一个名为“Widgets”的单独文件夹中,这就是按钮小部件文件

import 'package:flutter/material.dart';

Widget buttonWidget(String text, Function action) {
  return ElevatedButton(
    onPressed: () => action,
    child: Text(text, style: const TextStyle(fontSize: 20),
  );
}

现在在 main.dart 文件中,我希望 buttonWidget 使用 Navigator.pushNamed 函数,所以我将 buttonWidget 称为

buttonWidget("Navigate", Navigator.pushNamed(context, '/screenTwo')),

但是 buttonWidget 调用给了我这个错误

The argument type 'Future<Object?>' can't be assigned to the parameter type 'Function'.

【问题讨论】:

    标签: flutter dart widget


    【解决方案1】:

    您需要围绕调用创建一个匿名函数,就像直接将其传递给onPressed 参数一样。

    buttonWidget("Navigate", () => Navigator.pushNamed(context, '/screenTwo')),
    

    buttonWidget("Navigate", () {
      Navigator.pushNamed(context, '/screenTwo');
    }),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2020-09-09
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多