Flutter:如何从另一个类调用方法?

时间:2019-10-23 11:39:07

标签: function flutter dart

我是Dart和Flutter的新手。现在,我在从另一个类调用方法时遇到问题。

我试图使该方法静态化,但是该方法包含setState()方法,因此不可能。

所以我必须从main.dart致电showDialogWith() >>> wallet.dart

main.dart

import 'package:flutter/material.dart';
import 'dialog/operation.dart';
import 'pages/wallet.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future showDialogWith(String dialogName) async {
    Widget dialog;
    switch (dialogName) {
      case 'operations':
        setState(() {
          dialog = OperationsDialog();
        });
        break;
        // another cases and default...
    }
    await showDialog(
        context: context,
        child: dialog,
    );
  }

  @override
  Widget build(BuildContext context) {
   body: WalletContent();
  }
}

wallet.dart

class WalletContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      onPressed: () {
        // here I have to call the 'showDialogWith()' method
      },
    );
  }
}

operation.dart

class OperationsDialog extends StatefulWidget{
  OperationsDialog({Key key}) : super(key: key);

  @override
  _OperationDialogState createState() => new _OperationDialogState();
}

class _OperationDialogState extends State<OperationsDialog> {

  @override
  Widget build(BuildContext context) {
    return new SimpleDialog(
      title: new Text('Операции', textAlign: TextAlign.center),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您可以将函数作为参数传递。

@override
  Widget build(BuildContext context) {
  body: WalletContent(showDialogWith);
}

在您的WalletContent中添加一个功能字段,并将其分配给您的MaterialButton

class WalletContent extends StatelessWidget {
  WalletContent(this.onPressed);

  final Function onPressed;

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      onPressed: () => onPressed(...), // Pass your desired string here
    );
  }
}