如何从Flutter中的另一个文件访问用户定义的函数

时间:2020-05-19 09:19:22

标签: flutter dart

我定义了一个服务类来获取用户的位置,我想在我的LandingPage中调用该函数。 我正在获取未为类错误定义的函数。我使用方式有误吗?

LocationService.dart


  String location;
  Position _currentPosition;

  _getCurrentLocation(){
    //...
  }

}

LandingPage.dart

  @override
  _LandingPageState createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {

  @override
  Widget build(BuildContext context) {
    LocationService _locationService = LocationService();
    _locationService._getCurrentLocation();

    return MaterialApp(
      title: 'Test',
      home: SignInPage(),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

在Dart中,私有属性和函数由前面的_符号声明。因此,您的函数_getCurrentLocation是私有函数。

这使得它只能在其自己的类中访问,而不能在其外部访问。

如果您将方法重命名为getCurrentLocation,则该方法应该有效。 参见https://dart.dev/guides/language/language-tour#libraries-and-visibility

答案 1 :(得分:0)

通过在getCurrentLocation前面加上一个underscore(_),这意味着您正在使该方法也只能在它所属的class内部访问。

要在程序的其他部分使用method,请删除underscore(_)

检查以下代码:

 String location;
  Position _currentPosition;

  // remove the underscore and make it accessible in other parts of your code
  getCurrentLocation(){
    //...
  }

}