how to format string data like this '[1,fish#, 15,bird#, 4,horse#]' to '1,fish#15,bird#4,horse#' - flutter

how to format string data like this '[1,fish#, 15,bird#, 4,horse#]'
to '1,fish#15,bird#4,horse#'

You need to create the model and map the list to the model
In your case your model class looks like this
class User {
final int user;
final String tag;
User({ required this.user, required this.tag,
});
}
List like this
final List<User> userlist = [User(user: 4, tag: "ahmed#"),User(user: 15, tag: "up#"),];
when you need to get data use like this
userlist[0].tag,//0 is index
example
print(userlist[0].tag,) //this will print **ahmed#**

Simply using join and replaceAll.
export default function App() {
const encode = (source: string[]): string => {
return source.join(",").replaceAll("#,", "#");
};
const decode = (source: string): string[] => {
return source
.split(",")
.reduce((p, n) => [...p, ...n.split("#")], new Array<string>())
.map((e, i) => (i % 2 === 0 ? e : `${e}#`))
.filter((e) => !!e);
};
let source = ["1", "fish#", "15", "bird#", "4", "horse#"];
let sourceEncoded = encode(source);
console.log("encode", sourceEncoded);
// -> 1,fish#15,bird#4,horse#
let sourceDecoded = decode(sourceEncoded);
console.log("decode", sourceDecoded);
// -> ["1", "fish#", "15", "bird#", "4", "horse#"]
return (
<div className="App">
...
</div>
);
}
Code sanbox sample (console).

Related

Flutter Dart The getter '' was called on null

I'm sending response.body and country name with slash as like germany/ as parameter and converting it to Germany in parser and returning. But if i use parameter, i'm getting error of the getter 'vacTotal' was called on null. If i write "Germany"to countryDataVac["Germany"] the code works correctly. Is it the problem on {"Global": new CountryDataVac()}? The default value is "Global".
main.dart:
Map<String, CountryDataVac> countryDataVac = {"Global": new CountryDataVac()};
static Map<String, CountryDataVac> getCountryDataVac(String body, var countryname) {
Map<String, CountryDataVac> countryDataVac = {};
responseVac1Day = await http.get("https://disease.sh/v3/covid-19/vaccine/coverage?fullData=true&lastdays=1"); //vaccine number info
countryDataVac = Parser.getCountryDataVac(responseVac1Day.body, "germany/"); //vaccine number info
Parser.dart:
var usera = CountryDataVac.fromJson(jsonDecode(result));
countryDataVac[capitalize(countryname).replaceAll("/", "")] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //gives 'germany/' as 'Germany' but getting error if i get the countryname by parameter
countryDataVac["Germany"] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //works
}
CountryDataVac.dart (created by json to dart)
import 'dart:convert';
List<CountryDataVac> countryDataVacFromJson(String str) => List<CountryDataVac>.from(json.decode(str).map((x) => CountryDataVac.fromJson(x)));
String countryDataVacToJson(List<CountryDataVac> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryDataVac {
CountryDataVac({
this.vacTotal = 0,
this.vacDaily = 0,
this.vactotalPerHundred = 0,
this.vacdailyPerMillion = 0,
this.date = "",
});
int vacTotal = 0;
int vacDaily = 0;
int vactotalPerHundred = 0;
int vacdailyPerMillion = 0;
String date = "";
factory CountryDataVac.fromJson(Map<String, dynamic> json) => CountryDataVac(
vacTotal: json["total"],
vacDaily: json["daily"],
vactotalPerHundred: json["totalPerHundred"],
vacdailyPerMillion: json["dailyPerMillion"],
date: json["date"],
);
Map<String, dynamic> toJson() => {
"total": vacTotal,
"daily": vacDaily,
"totalPerHundred": vactotalPerHundred,
"dailyPerMillion": vacdailyPerMillion,
"date": date,
};
}
use
countryname.replaceFirst(countryname[0], countryname[0].toUpperCase()).replaceAll("/", "");
instead of
capitalize(countryname).replaceAll("/", "")
i think there is something wrong with your capitalize method

override object properties in createAsyncThunk method

I have a function like this
export const fetchChildrenNews = createAsyncThunk('news/fetch1', async ([item, news]) => {
const res = await Promise.all(item.kids.map(id => {
let url = `https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`;
return fetch(url);
}));
const jsons = await Promise.all(res.map(r => r.json()));
let users = {...item, kids: jsons};
item.kids = []//doesn't work
item.id = 0 //doesn't work
//I want to find a branch in the original tree and replace it
const tree = (obj) => {
for (let key in obj) {
if (key === "id" && obj[key] === users.id) {
obj = users;
}
if (key == "kids") {
tree(obj);
}
}
}
tree(item);
where item is a nested object record: {by: 'nullzzz', descendants: 47, id: 28808556, kids: Array(13), score: 117}. kids property contains array of ids and in the users variable it becomes an array of records. and my goal change record.kids = [0, 7, 14] to record.kids = users ([{by: '...', id:4848,..], [{by: 'adasd'], [{by: 'zzz}] ). the variable news is a whole tree while item its branches.
I just started working with the toolkit, so I don't fully understand this
Since item is probably an object from your Redux store, that thunk would try to modify a reference to your store - and modifying the store is only allowed in reducers.
Generally, you should be doing logic like this in reducers, not in a thunk.
So, do
export const fetchChildrenNews = createAsyncThunk('news/fetch1', async ([item, news]) => {
const res = await Promise.all(item.kids.map(id => {
let url = `https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`;
return fetch(url);
}));
const jsons = await Promise.all(res.map(r => r.json()));
return jsons
})
and then in your slice, add the logic:
builder.addCase(fetchChildrenNews, (state, action) => {
const jsons = action.payload
// here, do not modify `items`, but modify `state` - I would assume `items` is somewhere in here anyways?
})

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 create a List of Object in Back4App?

I'm using back4app in my application and I have a class like this called Meal:
and this is my code snippet :
class EatenMeals with ChangeNotifier {
List<Meal> _eatenMeals = [];
List<Meal> get eatenMeals {
return [..._eatenMeals];
}
void addMeal(Meal meal) {
var newMeal = Meal(
id: meal.id,
cal: meal.cal,
catId: meal.catId,
title: meal.title,
duration: meal.duration,
affordability: meal.affordability,
imageUrl: meal.imageUrl,
ingredients: meal.ingredients,
isBreakfast: meal.isDinner,
isDinner: meal.isDinner,
isLunch: meal.isLunch,
steps: meal.steps);
_eatenMeals.add(newMeal);
}
}
Now I want to create a class that contain list of Meals object.
and attach to users how do I achieve this?
Checkout Parse Server Custom Objects. Here is an example for your case how to create a Custom Object for Meal.
class Meal extends ParseObject implements ParseCloneable {
Meal() : super(_keyTableName);
Meal.clone() : this();
/// Looks strangely hacky but due to Flutter not using reflection, we have to
/// mimic a clone
#override
clone(Map map) => Meal.clone()..fromJson(map);
/// Colum names
static const String _keyTableName = 'Meal';
static const String keyCatId = 'catId';
static const String keyTitle = 'title';
static const String keyImgUrl = 'imgUrl';
static const String keyIngredients = 'ingredients';
static const String keySteps = 'steps';
static const String keyCalorie = 'calorie';
static const String keyDuration = 'duration';
static const String keyAffordability = 'affordability';
static const String keyIsBreakfast = 'isBreakfast';
static const String keyIsLunch = 'isLunch';
static const String keyIsDinner = 'isDinner';
/// Getter & Setters
List<String> get catId => get<List<String>>(keyCatId);
set name(List<String> catId) => set<List<String>>(keyCatId, catId);
String get title => get<String>(keyTitle);
set title(String title) => set<String>(keyTitle, title);
Strin> get imgUrl => get<String>(keyImgUrl);
set imgUrl(String imgUrl) => set<String>(keyImgUrl, imgUrl);
List<String> get ingredients => get<List<String>>(keyIngredients);
set ingredients(List<String> ingredients) => set<List<String>>(keyIngredients, ingredients);
List<String> get steps => get<List<String>>(keySteps);
set steps(List<String> steps) => set<List<String>>(keySteps, steps);
num get calorie => get<num>(keyCalorie);
set calorie(num calorie) => set<num>(keyCalorie, calorie);
num get duration => get<num>(keyDuration);
set affordability(num duration) => set<num>(keyDuration, duration);
String get affordability => get<String>(keyAffordability);
set name(String affordability) => set<String>(keyAffordability, affordability);
bool get isBreakfast => get<bool>(keyIsBreakfast);
set isBreakfast(bool isBreakfast) => set<bool>(keyIsBreakfast, isBreakfast);
bool get isLunch => get<bool>(keyIsLunch);
set isLunch(bool isLunch) => set<bool>(keyIsLunch, isLunch);
bool get isDinner => get<bool>(keyIsDinner);
set isDinner(bool isDinner) => set<bool>(keyIsDinner, isDinner);
}
Then you have to register this subclass.
Parse().initialize(
...,
registeredSubClassMap: <String, ParseObjectConstructor>{
'Meal': () => Meal(),
},
);

How to compare the type variable in "is" operator in Dart

I couldn't find a way to store the Type value in Map so that I could use it in is operator to check the validity of type using this map later on. Also, can is operator accept Type as a variable?
For eg, Below is hypothetical code solving the problem but it's invalid.
Map<String, Type> map = {
"sku": String,
"price": double,
"quantity": int,
};
dynamic value = 10;
if(value is map["quantity"]){
print("value is of type int and int is expected for quantity value");
}
You can do something like this:
class TypeCheck<T> {
const TypeCheck();
bool typeCheck(dynamic value) => value is T;
}
void main() {
Map<String, TypeCheck> map = {
"sku": TypeCheck<String>(),
"price": TypeCheck<double>(),
"quantity": TypeCheck<int>(),
};
dynamic value = 10;
if (map["quantity"]!.typeCheck(value)) {
print("value is of type int and int is expected for quantity value");
}
}
Im not sure I fully understand I understand what you are trying to do but why don't you try something like.
bool _validate(Map productDetails){
if (productDetails.containsKey("sold_individually") && productDetails["sold_individually"] is bool) {
//return true or false
}
else if (productDetails.containsKey("stock_quantity") && productDetails["stock_quantity"] is int){
//return true or false
}
else if (productDetails.containsKey("tax_class") && productDetails["tax_class"] is String && productDetails["tax_class"].isNotEmpty) {
//return true or false
} else {
//return true or false
}
}
As for the other part of your question you wont get an error but you will always return false. In contrast if you check if a variable is dynamic it will always return true.
I don't really understand your end goal. But from what you have, I don't think you are taking advantage of the strongly-typed nature of dart.
Assuming you are getting your map from an API, you could enforce
typing manually in your code as follows;
Map<String, Type> map = {
"sku": json['key'] as String,
"price": json['key'] as double,
"quantity": json['key'] as int,
};
And avoid using dynamic when declaring variables.
OR
In the case you have a user-defined type you what to compare, you can use the equatable package on a class for instance as follows;
class CustomMap extends Equatable {
String sky;
double price;
int quantity;
// here you put the fields of a class you want for two instances of a class to be equal.
#overide
List<Object> get props => [sky, price, quantity];
}
Update from your comment
You should have a custom class for the API objects for instance;
class Item extends Equatable {
String sku;
double price;
int quantity;
Item({this.sky, this.price, this.quantity});
// factory constructor
factory Item.fromMap(Map<String, dynmic> json) {
final sku = json['sku'] as String,
final price = (json['price'] as num) as double,
final quantity = json['quantity'] as num,
return Item(sku: sku, price: price, quantity: quantity);
}
// define equatable objects
#override
List<Object> get props => [sku, price, quantity];
}
Now you can use it as follows;
Future<Item> objectsFromService(Map<String, dynamic> json ) async {
http.Response response = http.get(url);
if(response.status == 200) {
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}else{
print('Error fetch data');
return null;
}
}
Hope it helps