use variable value in another class in flutter - flutter

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?

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.

as you know you have 2 ways:
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.
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 ;)

Related

How to retrieve the value of an object by using it's key name as a String? [duplicate]

This question already has answers here:
How to get a property by this name in String?
(2 answers)
Closed 4 months ago.
I have a typical class userData.
class userData ({K1:V1,K2:V2,K3:V3})
But i want to retrieve the data from several of them at the same time.
userData1 {K1:V1,K2:V2,K3:V3}
userData2 {K1:V4,K2:V5,K3:V6}
userData3 {K1:V7,K2:V7,K3:V8}
instead of using typical direct way:
print ("${userData1.K1} ${userData2.K1} ${userData3.K1}") ;
I want to access the data in an indirect method by using the key name as a String. Something like this:
String MyKey = 'K1';
print ("${userData1[MyKey]} ${userData2[MyKey]} ${userData3[MyKey]}") ;
Is there a way to retireve the values by using the key name as a String?
Thanks in advance for your help
Your question is unclear.
You may be looking for __getitem__. https://docs.python.org/3/library/operator.html#operator.getitem
Consider
d = dict(a=1, b=2)
When you ask for d['a'], you are calling d.__getitem__('a') behind the scenes.
There is an opportunity for your container class to inherit from dict,
and override __getitem__, if you wish to add behavior like logging,
or something fancier.
This is similar to the str() protocol that you likely are already familiar with.
Overriding __str__ will change the behavior of str(...)
and things that call it, such as format(...).
You should certainly review the getattr documentation.
When you write some code that addresses the need to your liking,
do post it here. https://stackoverflow.com/help/self-answer
Here is one solution that worked for me by creating a new dynamic in my class:
class MyClass{
....
dynamic getProp(String key) => <String, dynamic>{
'K1': K1,
'K2': K2,
'K3': K3,
}[key].toString();
}
}
With this i can retrieve with this line:
print(MyClass.getProp("K1"));
And so to get the data from my array, it work like this:
userData1 {K1:V1,K2:V2,K3:V3}
userData2 {K1:V4,K2:V5,K3:V6}
userData3 {K1:V7,K2:V7,K3:V8}
myKey = "K1";
print ("${userData1.getProp("K1")} ${userData2.getProp("K1")} ${userData3.getProp("K1")}"); // prints "V1 V4 V7"

Searching for a solution for more memory friendly way while adding elements to a list of class in flutter/dart

I'm trying to produce a runtime table. Below class and codes are simplified version of my final purpose.
class AppModel {
int appID;
String appName;
AppModel({this.appID, this.appName});
}
I'm calculating, fetching some another data and trying to fill the following object like this:
// _newApps value is between 1-30 mostly but not limited
List<AppModel> theList = [];
for (int i = 0; i < _newApps; i++) {
AppModel _newRecord = AppModel();
_newRecord.appID = _getNewAppID();
_newRecord.appName = _getNewAppName();
theList.add(_newRecord);
}
So the question is the code creates a new AppModel instance for only adding the element to the list for every iteration inside the for loop. According to my program logic, this event can be repeated 100-150 times sometimes.
Is it normal or is there any more memory efficient way to do so?
Thank you in advance.
I would like to point out (a better approach) that instead of for Loop you could have used the map method on the Apps List you have. And instead of creating a object every time in the Loop create a constructor for returning the object instance using the required details.
Hope you find it useful.

Flutter GetX RxList assign issue

Im trying to convert old code to new code syntax. I have a issue with RxList.
So I change postModel.assign(postDetail);
But In my news_detail page How I can access to value?
First of all you shouldn''t use postModel as a List as your API clearly returns a single post (NewsModel) by id and not a list of post (List of NewsModel). So using var postModel = <NewsModel>[].obs; is totally unnecessary in my opinion.
What you could do is:
final postModel = NewsModel().obs;
And then on API call:
postModel.value = postDetail;
And then on View:
Image.network(controller.postModel.value.imageUrl);
postModel is a List.
So you would need to access an item in that list, using an int index.
Something like this:
return Image.network(newsDetailController.postModel[0].imageUrl);

How can I assign a List<int> value of a map to a list outside of that map?

I need a list of my map assigned to a List variable outside of this map. How can I do that?
class Lists {
late var list = Map<int, List<int>>();
Lists() {
list[0] = [];
list[1] = [];
list[2] = [];
list[3] = [];
}
}
In another file I then try to assign the list[0] to a List variable:
List<int> listOutside = Lists.list[0];
I then receive this error:
What does the "?" mean and how can I fix that?
Thanks for the help.
Greetings
there are 2 major problems that are there.
You are trying to access a static variable outside a class which is wrong. This problem can be fixed by adding List<int> listOutside = Lists().list[0]; (notice the parentheses)
By accessing the list[0]; you are saying that the element always exists but here the compiler comes into play saying that this is a nullable list (List<int>?) which you are trying to assign to List<int> which is not possible as both have different types. This problem can be quickly fixed by using ! at the end Lists().list[0]!;
But note that this comes with a side effect that if there is no element at 0the index then this will throw NPE.
NOTE: Always avoid using ! in expressions where you are not sure that it is not nullable.
Seems to work when adding a "!".
List<int> listOutside = Lists.list[0]!;
I have no clue why, but anyways it works :D
? means that this field can have the null value. The Dart language now supports sound null safety and to indicate that a variable might have the value null, just add ? to its type declaration:
int? aNullableInt = null;
For your problem, you try to access list variable as a static usage and you use late but you initialize field immediately. For this reason, you can omit late and put static.
This usage could solve your problem:
static var list = Map<int, List<int>>();
List<int> listOutside = Lists.list[0];

Please help me understand fromMap and toMap from this code?

I got this code from the internet and I can not seem to understand it or find anything on the internet for it.
In the code below toMap is a method that returns 2 items, How is that possible?
And what is fromMap, is it a user created method? I thought methods used {} or => so it is a bit confusing.
Also, what is the key here for the Map? Can the map only store 2 categories of items? One is the key and the other is the value. Or it can have one key but multiple categories of values.
For example, there might be a single unique key, which could help take out the task title, time, reminder data, notes, etc as values of the map.
class Task {
String title;
bool completed;
Task({
this.title,
this.completed = false,
});
Task.fromMap(Map<String, dynamic> map): title = map['title'],completed = map['completed'];
updateTitle(title) {
this.title = title;
}
Map toMap() {
return {
'title': title,
'completed': completed,
};
}
}
In the code below toMap is a method that returns 2 items, How is that
possible?
No, it returns a Map (with two items). More about maps can be found here.
And what is fromMap, is it a user created method? I thought methods
used {} or => so it is a bit confusing.
Task.fromMap(Map<String, dynamic> map) is called "named constructor". The : title = map['title'],completed = map['completed'] part is initializer list
My understanding is;
In fromMap, you retrieve the title and completed from some map, and save it in your local variables.
In the toMap you take the saved values in your local variables and can return a Map.
The key is whatever you put you chose it to be, but here you chose one key to be titleand one to be completed.
Does this help you?
First of all we discuss about FormMap So what is fromMap()?
whenever you have any api and at firetime you will get json format so when you want to convert that data into any class format then you have to do like
Map temp = json.decode(response.body);
so your function can understand map key and retrieve that value and set in class local variable
and now Second point is toMap So what is toMap()?
Whenever you want to post something into api or somewhere you have map data so you can post in api
like
Abc a = Abc(name:"hari",address:"india");
a.toMap();