如何在Flutter中从另一个类调用对话函数



我想在flutter中从另一个类文件调用对话函数,正确的方法是什么…

File1: -

 import 'package:eg/eg/dialog_file.dart'
    floatingActionButton: FloatingActionButton(
            onPressed: () {
            // This is where I want to call the function
            },
            backgroundColor: Colors.black,
            child: Container(
              child: Icon(
                icons.add,
                size: 23,
                color: Colors.white,
              ),
            ),
          ),
 

File2: -

    showMyDialog(parentContext) {
    return showDialog(
      context: parentContext,
      builder: (context) {
        return SimpleDialog(
          title: Text("Title"),
          children: <Widget>[
            SimpleDialogOption(
              child: Text("Option1"),
              onPressed: function1,
            ),
            SimpleDialogOption(
              child: Text("Option2"),
              onPressed: function2,
            ),
            SimpleDialogOption(
              child: Text("Option3"),
              onPressed: function3,
            ),
          ],
        );
      },
    );
  }

对话框函数在File2中有onPressed函数所以我无法在File1中编写自定义对话框函数

我怎样才能做到这一点?

你没有提到你的function1等…但是一般来说,有一种方法是从另一个类调用对话框。我把它们设置为静态,这样我就不必创建类的实例了。

class Dialogs {
  static Future<void> showMyDialog(parentContext) {
    return showDialog(
      context: parentContext,
      builder: (context) {
        return SimpleDialog(
          title: Text("Title"),
          children: <Widget>[
            SimpleDialogOption(child: Text("Option1"), onPressed: () {}),
            SimpleDialogOption(child: Text("Option2"), onPressed: () {}),
            SimpleDialogOption(child: Text("Option3"), onPressed: () {})
          ],
        );
      },
    );
  }
}

下面是一个按钮的例子,它将通过传递它所在的构建方法的上下文来显示上面的对话框。

 ElevatedButton(
    onPressed: () => Dialogs.showMyDialog(context),
     child: Text('Dialog'),
 ),

你应该试试下面的答案:

首先在其他类中编写对话函数

 @override
 Widget build(BuildContext context) {
 return Container(
    color: Colors.white30,
    child:AlertDialog(
    title: Text(
       'name',
       style: TextStyle(
       fontWeight: FontWeight.bold,
      ),
      textAlign: TextAlign.center,
    ),
    content: Text(
      'name',
       style: TextStyle(
       fontWeight: FontWeight.bold,
      ),
      textAlign: TextAlign.center,
    ),
    actions: [
       TextButton(
        onPressed: () => Navigator.of(context).pop(),
        child: Text('OK'),
       )
     ],
   ),
  );
}

然后在其他类中编写对话框类函数,或者像下面这样调用它:

onPressed: () {
   Navigator.push(
   context,
   MaterialPageRoute(
     builder: (context) => CampaignData(),
    ),
   );
  },

最新更新