How to add variables in a class programmatically in dart? - flutter

How to add Variable in a Class Programmatically?
for example this is my current Variables in my class
Before
class ChartSampleData {
ChartSampleData({
this.yValue1,
this.yValue2,
});
num yValue1;
num yValue2;
}
Is there any way to add variable programmatically based on how many i want
just like this:
After
class ChartSampleData {
ChartSampleData({
this.yValue1,
this.yValue2,
this.yValue3, // NEW
this.yValue4, // NEW
});
num yValue1;
num yValue2;
num yValue3; //NEW
num yValue4; //NEW
}

No, You can use Map to add and get values.
For example
class ChartSampleData {
ChartSampleData({
});
Map values = Map();
addNewValue(String key, String value) {
values.add(key, value);
}
String getValue(String key){
return values[key];
}
}

No. But you can use a list or array or any data structures that allow adding or removing elements. Example:
class ChartSampleData{
List<num> yValues;
ChartSampleData({this.yValues});
}

Related

How to dynamically create object names based on a list?

I have a class FoodDetails which accepts a list of names
class FoodDetails extends StatefulWidget {
FoodDetails({this.namesList});
final List namesList;
#override
State<FoodDetails> createState() => FoodDetailsState();
}
I want to create objects of a class NameClass based on the names of namesList.
For example:
If namesList=["John", "Doe"];
I want to create lists like
List<NameClass> John;
List<NameClass> Doe;
How can I achieve this? I tried the following but it doesn't work
class FoodDetailsState extends State<FoodDetails> {
void initState() {
super.initState();
for (int i = 0; i < widget.namesList.length; i++) {
List<NameClass> widget.namesList[i];
}
}
}
You cannot create objects dynamically like javascript in dart.
Easy workaround would be using HashMap in which the key will be the desired dynamically allocated name and the value will be the instance of the object.
Code snippet which would help you start with this:
import 'dart:collection';
class Class {
String? var1;
String? var2;
Class({var1, var2}) {
this.var1 = var1;
this.var2 = var2;
}
}
void main() {
var list = ["John", "Doe"];
HashMap<String, Class> map = new HashMap();
list.forEach((element) {
map.addAll({element: new Class()}); // Just adding the key to the Map
});
print(map.containsKey("John"));
print(map.containsKey("Doe"));
// Can easily manipulate the value known the key
map["John"]!.var1 = "variable1";
map["Doe"]!.var2 = "variable2";
map.forEach((key, value) {
print("Key: " +
key +
" has values var1: " +
(value.var1 ?? "") +
" and var2: " +
(value.var2 ?? ""));
});
}
The output would be:
true
true
Key: John has values var1: variable1 and var2:
Key: Doe has values var1: and var2: variable2

Dart: Which is a better practice? Using 'late' or constructor initializer list

I am modelling a Dart class with the new null safety types in mind. I believe there are two effective ways to initialize non-nullable properties, calculated from a parameter.
For this example, we will use the Favourite class.
This class uses the initializer list in the constructor.
class Favourite {
int favouriteId;
Favourite({required this.favouriteId});
Favourite.mapFromJson(dynamic json)
: this.favouriteId = json["favouriteId"];
}
This class uses the 'late' keyword.
class Favourite {
late int favouriteId;
Favourite({required this.favouriteId});
Favourite.mapFromJson(dynamic json) {
this.favouriteId = json["favouriteId"];
}
}
When would you use one over the other? Using 'late' feels risky. If I added another named constructor, the compiler would not complain about 'favouriteId' not being initialized.
Are there other options?
Thank you!
Neither.
Use a default constructor that initializes the fields themselves and a factory constructor that handles deserializing the json object:
class Favourite {
final int favouriteId;
Favourite({required this.favouriteId});
factory Favourite.fromMap(Map<String, dynamic> map) {
final favouriteId = json['favouriteId'];
assert(favouriteId != null && favouriteId is int);
return Favourite(
favouriteId: favouriteId,
);
}
}
The late keyword can be a source of headache if you don't handle it properly, so in general don't use it unless you have to.
If you're sure the json will always have a "favouriteId", you can write it like this:
class Favourite {
int favouriteId;
Favourite({required this.favouriteId});
Favourite.mapFromJson(Map<String, dynamic?> json):
assert(() {
final favouriteId = json["favouriteId"];
return favouriteId != null && favouriteId is int;
}()),
favouriteId = json["favouriteId"] as int;
}
void main() {
dynamic m = {"favouriteId":2};
final favourite = Favourite.mapFromJson(m);
print("favourite id: ${favourite.favouriteId}");
}

How to remove elements with same parameter in a dart class list?

This is the dart class:
class CategoriesContent {
final String category;
final String image;
final int categoryNumber;
CategoriesContent({this.category, this.image, this.categoryNumber});
}
How to remove elements in
List<CategoriesContent> categoryList;
Such that no elements with same category number remain.
.toSet().toList() doesn't work.
Example addition
categoryList.add(CategoriesContent(
image: x["img"][0],
category: x["category"],
categoryNumber: ii));
}
So you save the ids separately and call toSet() to make unique then you loop through your list and keep only those
final categoryNumbers = categoryList.map((e) => e.categoryNumber).toSet();
categoryList.retainWhere((x) => categoryNumbers.remove(x.categoryNumber));
if you want to remove an element in a list you can use removeWhere function
i putted List<CategoriesContent> categoryList; in a Hypothetical class ,but you should find its class and instantiate that class
this is the class that contains the categoryList
class Name {
List<CategoriesContent> categoryList;
}
you should instantiate the class in where you want to use it
var name = Name();
then where ever you want to remove that element you can use removewhere function i putted it in a onPressed function so whenever user clicks on the button that element would be removed , you can use it in initstate or wherever you suppose
onPressed: (){
name.categoryList.removeWhere((element) => element.category == '1');
},
i putted string 1 by default but you should put what you want to remove for example if you want to remove mobile category you should say
element.category == 'mobile'
and if you want to remove where elements are wuth same parameter you should say
for (var item in name.categoryList) {
name.categoryList.removeWhere((element) => element == item);
}
or
name.categoryList.removeWhere((element) => element.category == element.category);
i'm not sure about the second one
tell me the result

Printing a class item of integer type in flutter

Is there a specific method to show integer value in flutter.
I have a code snippet similar to :
class with integer value:
class item{
item({
this.int_number
});
int int_number=1;
}
To print an int value in flutter, we usually use Text("$number")
but when trying similar method to print the class value :
Text("$item.int_number")
The number isn't printed correctly. but only data about $item
Is there a direct solution to this problem ?? to print int values that is a class item.
Thanks
use Text("${item.int_number}")
to print the values of instances like obj.value you need to wrap it in {}
thus you can use print("${obj.value}");
EDIT:
Tested this code on dartpad
void main() {
var item = Item(intNumber: 5);
print("${item.intNumber}");
print(item);
}
class Item {
Item({this.intNumber});
int intNumber = 1;
toString() => "Item (int_number = $intNumber)";
}
So you should be able to use
Text('${item.intNumber}')
or
Text('$item')
Use toString to converting int variable into String
For Example :
int intValue = 1;
I will use this in Text like this
Text("Value is:" + intValue.toString)
For more info try this link

Dart: convert Map to List of Objects

Did several google searches, nothing helpful came up. Been banging my head against some errors when trying to do something that should be pretty simple. Convert a map such as {2019-07-26 15:08:42.889861: 150, 2019-07-27 10:26:28.909330: 182} into a list of objects with the format:
class Weight {
final DateTime date;
final double weight;
bool selected = false;
Weight(this.date, this.weight);
}
I've tried things like: List<Weight> weightData = weights.map((key, value) => Weight(key, value));
There's no toList() method for maps, apparently. So far I'm not loving maps in dart. Nomenclature is confusing between the object type map and the map function. Makes troubleshooting on the internet excruciating.
Following on Richard Heap's comment above, I would:
List<Weight> weightData =
mapData.entries.map( (entry) => Weight(entry.key, entry.value)).toList();
Don't forget to call toList, as Dart's map returns a kind of Iterable.
List<Weight> weightData = List();
weights.forEach((k,v) => weightData.add(Weight(k,v)));
Sometimes the typecast will fail and you can enforce it by doing:
List<Weight> weightData =
weightData.entries.map<Weight>( (entry) => Weight(entry.key, entry.value)).toList();
Example from my project where it wasn't working without typecast:
List<NetworkOption> networkOptions = response.data['data']['networks']
.map<NetworkOption>((x) => NetworkOption.fromJson(x))
.toList();
Use the entries property on the map object
This returns a List of type MapEntry<key,value>.
myMap.entries.map((entry) => "${entry.key} + ${entry.value}").toList();
You can also use a for collection to achieve the same.
var list = [for (var e in map.entries) FooClass(e.key, e.value)];
Details
Flutter 1.26.0-18.0.pre.106
Solution
/libs/extensions/map.dart
extension ListFromMap<Key, Element> on Map<Key, Element> {
List<T> toList<T>(
T Function(MapEntry<Key, Element> entry) getElement) =>
entries.map(getElement).toList();
}
Usage
import 'package:myApp/libs/extensions/map.dart';
final map = {'a': 1, 'b': 2};
print(map.toList((e) => e.value));
print(map.toList((e) => e.key));
You can do this:
List<Weight> weightData = (weights as List ?? []).map((key, value) => Weight(key,value)).toList()
or you can try:
List<Weight> weightData = List.from(weights.map((key, value) => Weight(key, value)))
If you need to convert Map values to a list, the simplest oneline code looks like this:
final list = map.values.toList();
Vidor answer is correct .any way this worked for me
List<String> list = new List();
userDetails.forEach((k, v) => list.add(userDetails[k].toString()));
its very simple just initialize a list of your custom object like this
List<CustomObject> list=[];
for (int i = 0; i < map.length; i++) {
CustomObject customObject= CustomObject(
date:map[i]['key'],
weight:map[i]['key']
);
list.add(CustomObject);
}
hope it works for you thanks
You simply don't need to. the values property is an Iterable<> of your objects. You can iterate over this or you can convert it to a list. For example,
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("convert Map to List of Objects", (tester) async {
final weight1 = Weight(const ValueKey("1"), DateTime.now(), 1);
final weight2 = Weight(const ValueKey("2"), DateTime.now(), 2);
final map = {weight1.key: weight1, weight2.key: weight2};
//You don't have to convert this to a list
//But you can if you want to
final list = map.values.toList();
list.forEach((w) => print("Key: ${w.key} Weight: ${w.weight} "));
});
}
class Weight {
final Key key;
final DateTime date;
final double weight;
bool selected = false;
Weight(this.key, this.date, this.weight);
}
Object Class
class ExampleObject {
String variable1;
String variable2;
ExampleObject({
required this.variable1,
required this.variable2,
});
Map<String, dynamic> toMap() {
return {
'variable1': this.variable1,
'variable2': this.variable2,
};
}
factory ExampleObject.fromMap(Map<String, dynamic> map) {
return ExampleObject(
variable1: map['variable1'] as String,
variable2: map['variable2'] as String,
);
}
}
Convert Map to Object List
List<ExampleObject> objectList = List<ExampleObject>.from(mapDataList.map((x) => ExampleObject.fromMap(x)));