2

Im new and my question may be stupid but

in class Location i have 2 var :

var latitude;
var longitude;

then :

Location({Key? key, this.latitude , this.longitude}) : super(key: key);

and after some works when I print them I get the value

print(widget.latitude);
print(widget.longitude);

there is no problem here BUT when I want to use these vars in another class like this :

var myLat = Location().latitude;
var myLong = Location().longitude;

the values are NULL

how can get the values the second class too?

1
  • That is beacause you are creating a new instance of each class, you should use a state management solution like Provider, Riverpod, Getx, etc. to access data from different locations in the app. Commented Jan 13, 2023 at 12:50

2 Answers 2

1

When you type Location() - you create the new instance of this class. It isn't connected to the previous instance you were working on. To make this work you need to type

var myLat = location.latitude;
var myLong = location.longitude;

WHERE location is the SAME object you created previously. So you need to pass it somehow to the place where you're trying to access these fields.

Sign up to request clarification or add additional context in comments.

3 Comments

Or you can not create the object but add the word "static" to the two original variables
thanks for answer . when I add static then in my methods I can't use these variables . what can I do? it says "create a local variable"
could you please share your entire class? I can suggest adjustments
1

as you know you have 2 ways:

  1. if you want to navigate from first page to second page you can pass the Location args by the code in my answer to a question. and if you want to read a doc here is the link.
  2. you can use Provider as a stateManagement. here is my answer to using provider. believe me that using stateManagement make your tasks easy .because sometimes you need to use datas from one page to 10 pages later. what you want to do?? do you want to pass datas to every pages????? if you didn't understand what i mean, please write in comment down. happy coding... Moraghebe khodet bash ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.