how to sum list values from API in flutter - flutter

Does anyone here know/have references/examples of how to add up the values in the list in Flutter. Thanks

use sum:
import 'package:collection/collection.dart';
void main() {
final list = [1, 2, 3, 4];
final sum = list.sum;
print(sum); // prints 10
}
Your question is similar to the question here, refer to it for more information

you can use .fold() method
fold method:
T fold<T>(T initialValue, T Function(T, Data) combine)
example for sum list of object:
void main() {
List<Data> listData = [
Data(count: 10, name: 'a'),
Data(count: 12, name: 'bc'),
Data(count: 21, name: 'abc'),
];
int sum = listData.fold(0, (int preValue, data) => preValue + data.count);
print(sum);// 43
}
class Data {
int count;
String name;
Data({required this.count, required this.name});
}

Related

I want to reverse the key and value of Map

How can I reverse the key and value of the map?
for example, {1:a , 2:b , 3:c} => {a:1 ,b:2 ,c:3}
Try this piece of code:
Map<int, String> map = {1: "a", 2: "b", 3: "c"};
Iterable<String> values = map.values;
Iterable<int> keys = map.keys;
Map<String, int> reversedMap = Map.fromIterables(values, keys);
print(reversedMap); // {a:1 ,b:2 ,c:3}
You can do this:
const items = {1:'a' , 2:'b' , 3:'c'};
void main() {
final inverted = items.map((key, value) => MapEntry(value, key));
print(inverted);
}
It logs
{a: 1, b: 2, c: 3}

Combining repeating items in a list

I have a list of items containing unique and repeating IDs, I want to sum the prices and display the number of the repeating IDs
class Model{
int id,price,count;
Model(this.id,this.price,this.count);
}
List<Model> list1 = [
Model(1,5000,10),
Model(2,1000,20),
Model(1,5000,5),
Model(2,5000,10),
];
List<Model> list2 = [];
I need the second list to be like this
list2 = [
Model(1,10000,15),
Model(2,6000,30),
];
try this :
void main() {
int sum = 0;
List<Model> list1 = [
Model(1, 5000, 10),
Model(2, 1000, 20),
Model(1, 5000, 5),
Model(2, 5000, 10),
];
List<Model> list2 = modelsWithoutRepeatingIdsButSumOfPricesAndAmount(
list1); // [Model(1,10000,15), Model(2,6000,30),]
}
List<Model> modelsWithoutRepeatingIdsButSumOfPricesAndAmount(
List<Model> modelList) {
Map<int, Model> map = {};
for (int index = 0; index < modelList.length; index += 1) {
Model current = modelList[index];
map[current.id] ??= Model(current.id, 0, 0);
map[current.id]!.price += current.price;
map[current.id]!.count += current.count;
}
return map.values.toList();
}
class Model {
int id, price, count;
Model(this.id, this.price, this.count);
}
Use reduce method to get the sum of a list
var total = [1, 2, 3].reduce((a, b) => a + b);
If you don't want to use reduce method you can also use .fold() there are couple more you can get them by importing dart collections package.

How to random select 3 element without repeating?

Random 3 Element with repeating
How to random select 3 element without repeating?
List<Question> imageList = [
Question(
index: 1,
image: 'assets/images/1.png',
),
Question(
index: 2,
image: 'assets/images/2.png',
),
Question(
index: 3,
image: 'assets/images/3.png',
),
Question(
index: 4,
image: 'assets/images/4.png',
),
Question(
index: 5,
image: 'assets/images/5.png',
),
];
This is Element List
getRandom =
List<Question>.generate(3, (_) => imageList[random.nextInt(imageList.length)]);
This is Random Function with repeating.
You could define an extension on List<T> so you can reuse it on all types of List:
List<String> alphabets = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
extension XList<T> on List<T> {
List<T> takeRandom(int n) {
return ([...this]..shuffle()).take(n).toList();
}
}
void main() {
print(alphabets.takeRandom(3));
print(alphabets.takeRandom(5));
print(alphabets.takeRandom(7));
}
Console log
[B, S, G]
[P, M, F, Q, K]
[U, M, R, C, Z, D, G]
Get the list count;
int total = imageList.length;
create index list numbers;
var listindex = List<int>.generate(total, (i) => i++);
shuffle list;
listindex .shuffle();
//result
[3, 6, 2, 0, 9, 1, 5, 7, 8, 4]
and get data from first 3 index list.
imageList[3].image
imageList[6].image
imageList[2].image
I solved this problem
Initialized with variable
List<Question> getRandom = [];
late Question correctElement;
Random random = Random();
Init State for first time run
#override
void initState() {
setRandom();
if (kDebugMode) {
print('getRandomNum is $getRandom & correctElement is $correctElement');
}
super.initState();
}
Used do while loop to unrepeate
Question shaffel() {
return imageList[random.nextInt(imageList.length)];
}
setRandom() {
getRandom.clear();
do {
Question data = shaffel();
if (getRandom.isEmpty) {
setState(() {
getRandom.add(data);
});
} else if (getRandom.contains(data)) {
} else {
setState(() {
getRandom.add(data);
});
}
} while (getRandom.length != 3);
correctElement = getRandom[random.nextInt(getRandom.length)];
}

dart null safety class initialization

I built two classes.
first class is the video Class.
second class is Player Class.
And one of Player variables is list of video class
and after dart null safety it is not allowed to add null varaiables
I should add initialization value to the class ( I don't want to add required ).
First Class - Video
import 'dart:convert';
VideoModel videoModelFromJson(String str) =>
VideoModel.fromJson(json.decode(str));
String videoModelToJson(VideoModel data) => json.encode(data.toJson());
class VideoModel {
VideoModel({
this.playerVideoId = -1,
this.playerIdId = -1,
this.videoLink = "Please Upload",
});
int playerVideoId;
int playerIdId;
String videoLink;
factory VideoModel.fromJson(Map<String, dynamic> json) => VideoModel(
playerVideoId: json["playerVideoId"],
playerIdId: json["playerId_id"],
videoLink: json["videoLink"],
);
Map<String, dynamic> toJson() => {
"playerVideoId": playerVideoId,
"playerId_id": playerIdId,
"videoLink": videoLink,
};
}
Second Class which contain error in defining videos
// To parse this JSON data, do
//
// final playerBasic = playerBasicFromJson(jsonString);
import 'dart:convert';
import 'package:sportive/pages/player/Model/Video_Model.dart';
PlayerBasic playerBasicFromJson(String str) =>
PlayerBasic.fromJson(json.decode(str));
String playerBasicToJson(PlayerBasic data) => json.encode(data.toJson());
class PlayerBasic {
PlayerBasic({
this.playerId = -1,
this.userIdId = -1,
this.playerFirstName = "",
this.playerLastName = "",
this.nationality = "",
this.birthday = "",
this.height = -1,
this.weight = -1,
this.currentCountry = "",
this.currentCity = "",
this.game = "",
this.image = "",
this.gender = "Male",
this.videos, // Error here Parameter The parameter 'videos' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
//Try adding either an explicit non-'null' default value or the 'required' modifier
});
int playerId;
int userIdId;
String playerFirstName;
String playerLastName;
String nationality;
String birthday;
int height;
int weight;
String currentCountry;
String currentCity;
String game;
String image;
String gender;
List<VideoModel> videos;
factory PlayerBasic.fromJson(Map<String, dynamic> json) => PlayerBasic(
playerId: json["playerId"],
userIdId: json["userId_id"],
playerFirstName: json["playerFirstName"],
playerLastName: json["playerLastName"],
nationality: json["nationality"],
birthday: json["birthday"],
height: json["height"],
weight: json["weight"],
currentCountry: json["currentCountry"],
currentCity: json["currentCity"],
game: json["game"],
image: json["image"],
gender: json['gender'],
videos: json['videos'],
);
Map<String, dynamic> toJson() => {
"playerId": playerId,
"userId_id": userIdId,
"playerFirstName": playerFirstName,
"playerLastName": playerLastName,
"nationality": nationality,
"birthday": birthday,
"height": height,
"weight": weight,
"currentCountry": currentCountry,
"currentCity": currentCity,
"game": game,
"image": image,
"gender": gender,
"videos": videos,
};
}
Sorry Iam Flutter beginner question.
Just change the videos declaration to
List<VideoModel>? videos;
Let's suppose you have this class and you want to provide a default value for bar in the constructor:
class Foo {
List<int> bar;
}
If you want to be able to modify bar later:
class Foo {
// Use this
Foo({List<int>? bar}) : bar = bar ?? [];
List<int> bar;
}
void main() {
Foo foo;
foo = Foo();
print(foo.bar);
// Outputs []
foo.bar.add(4);
print(foo.bar);
// Outputs [4]
foo = Foo(bar: [1, 2, 3]);
print(foo.bar);
// Outputs [1, 2, 3]
foo.bar.add(4);
print(foo.bar);
// Outputs [1, 2, 3, 4]
}
If you want to keep bar immutable (i.e. you won't use methods such as add or remove):
class Foo {
// Use this
Foo({this.bar = const []});
List<int> bar;
}
void main() {
Foo foo;
foo = Foo();
print(foo.bar);
// Outputs []
// foo.bar.add(4);
// It'll throw Uncaught Error: Unsupported operation: add
foo = Foo(bar: [1, 2, 3]);
print(foo.bar);
// Outputs [1, 2, 3]
foo.bar.add(4);
print(foo.bar);
// Outputs [1, 2, 3, 4]
}

How to convert a list of numbers in a String to a list of int in dart

After reading a line from a file, I have the following String:
"[0, 1, 2, 3, 4]"
What is the best way to convert this String back to List<int>?
Just base on following steps:
remove the '[]'
splint to List of String
turn it to a int List
Sth like this:
List<int> list =
value.replaceAll('[', '').replaceAll(']', '')
.split(',')
.map<int>((e) {
return int.tryParse(e); //use tryParse if you are not confirm all content is int or require other handling can also apply it here
}).toList();
Update:
You can also do this with the json.decode() as #pskink suggested if you confirm all content is int type, but you may need to cast to int in order to get the List<int> as default it will returns List<dynamic> type.
eg.
List<int> list = json.decode(value).cast<int>();
You can convert String list to int list by another alternate method.
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
stringList.map((e){
var intValue = int.tryParse(e);
intList.add(intValue!);
print(intList);
});
print(a);
}
Or by using for in loop
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
for (var i in stringList){
int? value = int.tryParse(i);
intList.add(value!);
print(intList);
}
}