无法使用静态访问访问 Flutter 实例成员“{0}”

Flutter Instance member ‘{0}’ can’t be accessed using static access

我在 flutter 中将一个 activity 的变量传递给另一个 activity,但出现错误 "Instance member ‘latitude’ can’t be accessed using static access" 我需要在该块中对其进行转换,以便我可以将其分配给静态 URL。

class Xsecond extends StatefulWidget {
  final double latitude;
  final double longitude;
  Xsecond(this.latitude, this.longitude, {Key key}): super(key: key);

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

class _Xsecond extends State<Xsecond> {
  static String lat = Xsecond.latitude.toString(); // Error: Instance member ‘latitude’ can’t be accessed using static access
  ...

接着是

  ...
  String url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},$lng&radius=$radius&type=restaurant&key=$api';
  ...

在您的代码中,纬度和经度都被定义为非静态的,即实例变量。这意味着它们只能使用 class 实例调用。

class _Xsecond extends State<Xsecond> {
      final xsecond = Xsecond();
      static String lat = xsecond.latitude.toString();
      ...

请阅读任何面向对象编程语言的基础知识,例如飞镖,java,C++

但是,在您的上下文中,第一个 class 是您的 StatefullWidget。因此,您可以通过您所在州 class.

widget 字段访问它

修复:

class _Xsecond extends State<Xsecond> {
          static String lat = widget.latitude.toString();
          ...

如果您使用静态变量等非静态变量,则会出现此错误。让我们来看看这个例子:

class MyPage extends StatefulWidget {
  final foo = Foo();
  // ...
}

class _MyPageState extends State<MyPage> {
  final newFoo = MyPage.foo; // Error
  // ...
}

MyPage.foo 不是静态成员,但您正在使用它。


要解决此问题,您可以使变量 static

static final foo = Foo();

使用widget变量获取基础变量。

class _MyPageState extends State<MyPage> {
  @override
  void initState() {
    super.initState();
    final newFoo = widget.foo; // No Error
  }
  // ...
}