Flutter: how can I call method from another class?

2,857

You can pass a function as a parameter.

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

Add a Function field into your WalletContent and assign it to your 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
    );
  }
}
Share:
2,857
1encore
Author by

1encore

20 y.o. Full-stack dev

Updated on December 15, 2022

Comments

  • 1encore
    1encore over 1 year

    I am new in Dart and Flutter. Now I am having a problem with calling a method from another class.

    I have tried to make the method static, but the method contains setState() method so it is not possible.

    So I have to call main.dart >>> showDialogWith() from 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),
        );
      }
    }
    
  • 1encore
    1encore over 4 years
    Amazing! Didn't know that it is possible to pass functions as parameter. Thanks a lot!!!