Reputation: 402
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),
);
}
}
Upvotes: 2
Views: 4380
Reputation: 2617
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
);
}
}
Upvotes: 1