【问题标题】:Flutter: how can I call method from another class?Flutter:如何从另一个类调用方法?
【发布时间】:2019-10-23 11:39:07
【问题描述】:

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

我尝试将方法设为静态,但该方法包含 setState() 方法,因此无法实现。

所以我必须从wallet.dart 打电话给main.dart >>> showDialogWith()

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

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

【问题讨论】:

    标签: function flutter dart


    【解决方案1】:

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

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

    在您的 WalletContent 中添加一个 Function 字段并将其分配给您的 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
        );
      }
    }
    

    【讨论】:

    • 太棒了!不知道可以将函数作为参数传递。非常感谢!!!
    猜你喜欢
    • 2019-03-04
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多