我是Dart和Flutter的新手。现在我在从另一个类调用方法时遇到了问题。
我试图使该方法静态化,但是该方法包含setState()方法,因此这是不可能的。
所以我必须从main.dart
调用showDialogWith()
>>> wallet.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();
}
}
钱包。 Dart
class WalletContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialButton(
onPressed: () {
// here I have to call the 'showDialogWith()' method
},
);
}
}
操作箭
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),
);
}
}
最佳答案
您可以将函数作为参数传递。
@override
Widget build(BuildContext context) {
body: WalletContent(showDialogWith);
}
将功能字段添加到
WalletContent
中,并将其分配给MaterialButtonclass WalletContent extends StatelessWidget {
WalletContent(this.onPressed);
final Function onPressed;
@override
Widget build(BuildContext context) {
return MaterialButton(
onPressed: () => onPressed(...), // Pass your desired string here
);
}
}
关于function - Flutter:如何从另一个类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522028/