简体   繁体   English

从 main.dart 调用另一个 dart 文件中的 dart 方法

[英]Calling a dart method in another dart file from main.dart

I am trying to call a dart method which is in another dart file from main.我正在尝试从 main 调用另一个 dart 文件中的 dart 方法。 dart. dart。 For some reason the method seems to inaccessible.由于某种原因,该方法似乎无法访问。 Here I am trying to access the _configureAmplify method which is in another class.在这里,我试图访问另一个 class 中的 _configureAmplify 方法。 I got all the import added correctly.我正确添加了所有导入。 What am I doing wrong?我究竟做错了什么? Here is my main.dart class -这是我的主要内容。dart class -

class _AmplifyFlutterState extends State<AmplifyFlutter> {
  bool _amplifyConfigured = false;


  void initState() {
    super.initState();
    Authentication._configureAmplify().then((result) {
      if (result) {
        setState(() {
          _amplifyConfigured = true;
          Navigator.push(context, MaterialPageRoute(builder: (_) => SignUpScreen()));
        });
      } else {
        _amplifyConfigured = false;
      }
    });

  }
}

Here is the other class which defines the _configureAmplify method这是定义 _configureAmplify 方法的另一个 class

class Authentication {
    
      Future<bool> _configureAmplify() async {
        bool _amplifyConfigured = false;
        Amplify.addPlugin(AmplifyAuthCognito());
        try {
          await Amplify.configure(amplifyconfig);
        }
        on AmplifyAlreadyConfiguredException {
          print("Amplify was already configured. Was the app restarted?");
        } catch(e) {
          print(e);
        }
        return _amplifyConfigured;
      }
    }

EDIT编辑在此处输入图像描述

In Dart, when you proceed a function with _ it makes it private ie.在 Dart 中,当您使用_进行 function 时,它会将其设为私有,即。 inaccessible from outside the class.无法从 class 外部访问。

If the function is only meant to be used from within the class, it's always better to keep it private.如果 function 仅用于在 class 中使用,最好将其保密。 But if you need to access it from outside, then it needs to be public with no underscore.但是如果你需要从外部访问它,那么它需要是公开的,没有下划线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM