Mark
Mark

Reputation: 435

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

I am passing variables from one activity to another in flutter but getting the error "Instance member ‘latitude’ can’t be accessed using static access" I need it converted in that block so I can assign it to a static 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
  ...

followed by

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

Upvotes: 18

Views: 48529

Answers (2)

iDecode
iDecode

Reputation: 28906

This error occurs if you use non-static variable like static. Let's take a look at this example:

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

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

MyPage.foo isn't a static member but you are using if it was.


To solve this issue, you can either make the variable static

static final foo = Foo();

or

Use widget variable to get hold of the underlying variable.

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

Upvotes: 0

Sisir
Sisir

Reputation: 5398

In your code both latitude and longitude are defined as non-static i.e. are instance variables. Which means they can only be called using a class instance.

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

Please read the basics of any Object Oriented Programming language e.g. Dart, java, C++

However, in your context the first class is your StatefullWidget. So you can access that by the widget field of your state class.

FIX:

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

Upvotes: 14

Related Questions