Uncaught Error: TypeError: 100: type 'JSInt' is not a subtype of type 'String' - flutter

void main() {
String num = "50";
int quantity = 2;
num = (int.parse(num) * quantity) as String;
print("num is "+num);
}
This is giving me error
Actually i want to convert a string to numerical value and perform calculations and update the string back with the updated value.
// Assume the intial value of
// item.quantity = 1, item.cost = 20
-----------------------------------------------------------------
item.quantity++;
item.cost = (int.parse(item.cost) * item.quantity) as String;
-----------------------------------------------------------------
====================================================
expected result item.cost = 40
generated result is 2020
====================================================

By using toString you create a new String value. By casting as T you tell the compiler that an unknown value you want as T value.
void main() {
String numer = "50";
int quantity = 2;
numer = (num.parse(numer) * quantity).toString();
print("sum is $numer"); // sum is 100
}
Note: avoid use names which is reserved by system to avoid conflict.

Related

How to automatically parse out the fields(Protobuf) used in the code?

Given the following trade.proto file:
message Trade {
message ProductInfo {
optional uint64 product_id = 1;
optional String product_name = 2;
repeated int other_field = 3;
}
optional string id = 1;
optional uint64 partition_time = 2;
optional ProductInfo product_info= 3;
}
Given the following code:
def getOtherFieldSize(trade: Trade): Int = {
if (20221205 == trade.getPartitionTime) {
trade.getProductInfo.getOtherFieldList.size
} else {
0
}
}
How to get the fields of trade.proto used in the code? For example:
partition_time
product_info.other_field

Why does the identityHashCode function not work for the built-in type 'int' in Dart?

The documentation of the identityHashCode says:
And it indeed works for my custom type 'Integer':
class Integer {
int num;
Integer(this.num);
#override
int get hashCode {
return num;
}
#override
bool operator ==(Object other) {
if(other is Integer && this.num == other.num) {
return true;
}
return false;
}
}
void main() {
Integer n1 = Integer(1);
print(n1.hashCode); // print "1"
print(identityHashCode(n1)); // print "650939380", a different value!
}
But for the built-in type 'int', identityHashCode(int) seems to always return the same value as int.hashCode, which is the numerical value itself:
void main() {
int n = 1;
print(n.hashCode); // print "1"
print(identityHashCode(n)); // still print "1", the same value as n.hashCode!
}
Anyone know why this is happening? I'm confused now.😵
int is Built-in type (not a usual class)
In documentation identityHashCode has a note:
This hash code is compatible with [identical], which just means that
it's guaranteed to be stable over time.
For compiler all int values are constants. identical for the same constants shows true. So hashCode of int was made by own value (which also int).
print(identical(1, 1)); // true
According to this comment int (and double) has own condition for comparing in identical function.
By the same numeric value
Here's some code for example representation:
void main() {
int a = 1; // '1' is a constant
int b = 1;
int c = 2; // '2' is a constant
print(identical(a, b)); // true
print(identical(a, c)); // false
print(identical(1, 1)); // true
print(identical(1, 2)); // false <= 1 and 2 are constants
print(identical(a, 1)); // true
print(identical(c, 1)); // false
print(identical(c, 2)); // true
print(identityHashCode(a)); // 1
print(identityHashCode(b)); // 1
print(identityHashCode(c)); // 2
print(identityHashCode(1)); // 1
print(identityHashCode(2)); // 2
}

How to hide decimal value when it is = 0

I am currently trying to render the price value of products using a widget in Flutter.
To do so, I pass the state and render it in the argument from the corresponding widget.
What I need to achieve is to hide the 2 decimals of my Double type priceValue and show them if they are != to 0.
Like so, if state.priceValue = 12.00 $ => should show 12
if state.priceValue = 12.30 $ => should show 12.30
String removeZero(double money) {
var response = money.toString();
if (money.toString().split(".").length > 0) {
var decmialPoint = money.toString().split(".")[1];
if (decmialPoint == "0") {
response = response.split(".0").join("");
}
if (decmialPoint == "00") {
response = response.split(".00").join("");
}
}
return response;
}
Edit: I added to check if the string contains a decimal point or not to avoid index out of bounds issue
Try this:
String price = "12.00$"
print(price.replaceAll(".00", ""));
Or refer to this: How to remove trailing zeros using Dart
double num = 12.50; // 12.5
double num2 = 12.0; // 12
double num3 = 1000; // 1000
RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
String s = num.toString().replaceAll(regex, '');
But the second option will remove all trailing zeros so 12.30 will be 12.3 instead
Hello you could use an extension like that:
extension myExtension on double{
String get toStringV2{
final intPart = truncate();
if(this-intPart ==0){
return '$intPart';
}else{
return '$this';
}
}
}
To use the extension:
void main() {
double numberWithDecimals = 10.8;
double numberWithoutDecimals = 10.00;
//print
print(numberWithDecimals.toStringV2);
print(numberWithoutDecimals.toStringV2);
}

ethereum solidity: from concatenated hexadecimal strings to uint64[]

I want my API to return an array of uint64 to my on-chain contract.
I tried 2 response formats for my API:
The array of uint64 itself (BN string here, but I need it in true uint64 not strings in my contract):
{"data":["629343835796877311","629343835797458943","629343835797471231"]}
concatenated hexadecimal strings (a new value every 16 chars):
{"data":"08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff"}
I discarded using the first approach because having ["629343835796877311","629343835797458943","629343835797471231"] as bytes is actually difficult to extract. I might be wrong! Maybe there is a base64 approach to encode and decode the data back into solidity data types, maybe?
I will use the second approach bellow.
Chainlink will pass the response as bytes memory _data:
function fulfill(bytes32 _requestId, bytes memory _data)
public
recordChainlinkFulfillment(_requestId)
{
data = string(_data);
}
Those bytes memory _data are successfully received and converted to a string (in storage data). The string value looks like this
08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff ...
In this example each 16 chars represent a uint64 number.
The first one: 08bbe0e25e412fff is 629343835796877311 for instance.
In solidity, I need to split the string each 16 chars and then convert it into their uint64 value.
I could use the bytes memory _data instead of the string(_data) if the code would be simpler or consume less gas. I am not sure
Please I need help with this I have been struggling.
Thanks
I got this contract working
COMMENTS:
the method hexBytesToInt is going to get a string representing hexa value like ffa0 for instance and return it's decimal value.
the method getSlice is just going to slice a string. In my case I have a new hexa value every 16 chars so I need to slice (0,16) than (16,32) etc...
the method hexStringToIntArray is managing the increments to slice every 16 chars and call the hexBytesToInt to transform the hex string in uint.
If you really want to dig into this solution, you are better off starting by understanding the test cases.
pragma solidity >=0.4.22 <0.8.11;
contract Serializer {
function hexStringToIntArray(string memory s) public pure returns (uint64[] memory) {
uint size = bytes(s).length / 16;
uint64[] memory result = new uint64[](size);
for (uint i = 0; i< size; i++) {
string memory strSlice = getSlice(i*16, (i+1)*16, s);
result[i] = hexStringToInt(strSlice);
}
return result;
}
function getSlice(uint startIndex, uint endIndex, string memory str) public pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
function hexBytesToInt(bytes memory ss) public pure returns (uint64){
uint64 val = 0;
uint8 a = uint8(97); // a
uint8 zero = uint8(48); //0
uint8 nine = uint8(57); //9
uint8 A = uint8(65); //A
uint8 F = uint8(70); //F
uint8 f = uint8(102); //f
for (uint i=0; i<ss.length; ++i) {
uint8 byt = uint8(ss[i]);
if (byt >= zero && byt <= nine) byt = byt - zero;
else if (byt >= a && byt <= f) byt = byt - a + 10;
else if (byt >= A && byt <= F) byt = byt - A + 10;
val = (val << 4) | (byt & 0xF);
}
return val;
}
function hexStringToInt(string memory s) public pure returns (uint64) {
bytes memory ss = bytes(s);
uint64 val = hexBytesToInt(ss);
return val;
}
}
the tests:
const Serializer = artifacts.require("Serializer");
const truffleAssert = require("truffle-assertions");
const fs = require("fs");
const { readLines } = require("./utils.js");
const BN = web3.utils.BN;
contract("Serializer", (accounts) => {
const [deployerAddress, tokenHolderOneAddress, tokenHolderTwoAddress] = accounts;
it("hexStringToInt", async () => {
let s = await Serializer.deployed();
let result = await s.hexStringToInt.call("08bbe0e25e412fff");
let expected = new BN("629343835796877311");
assert.equal(result.toString(10), expected.toString(10));
result = await s.hexStringToInt.call("08bbe0e25e4a0fff");
expected = new BN("629343835797458943");
assert.equal(result.toString(10), expected.toString(10));
result = await s.hexStringToInt.call("08bbe0e25e4a3fff");
expected = new BN("629343835797471231");
assert.equal(result.toString(10), expected.toString(10));
});
it("getSlice1", async () => {
let s = await Serializer.deployed();
let result = await s.getSlice.call(0, 16, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
let expected = "08bbe0e25e412fff";
assert.equal(result, expected);
});
it("getSlice2", async () => {
let s = await Serializer.deployed();
const result = await s.getSlice.call(16, 32, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
const expected = "08bbe0e25e4a0fff";
assert.equal(result, expected);
});
it("getSlice3", async () => {
let s = await Serializer.deployed();
const result = await s.getSlice.call(32, 48, "08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
const expected = "08bbe0e25e4a3fff";
assert.equal(result, expected);
});
it("hexStringToIntArray", async () => {
let s = await Serializer.deployed();
let result = await s.hexStringToIntArray.call("08bbe0e25e412fff08bbe0e25e4a0fff08bbe0e25e4a3fff");
console.log(result);
let expected = [
new BN("629343835796877311").toString(),
new BN("629343835797458943").toString(),
new BN("629343835797471231").toString(),
];
const resultS = result.map((x) => x.toString());
assert.deepEqual(resultS, expected);
});
});

Flutter double to Time in hours

I'm trying to convert a double value (e.g. 9.5) to a corresponding hour/minute value (e.g. 9.30). I also want to perform calculations using this value, but handle it like a time value (e.g. adding 23 and 2 should result in 1 as the hours should wrap around at 24 hours).
I already tried to convert the value to DateTime, but it says "invalid date format".
This should do it
void main() {
print(getTimeStringFromDouble(9.5)); // 9:30
print(getTimeStringFromDouble(25.0)); // 1:0
}
String getTimeStringFromDouble(double value) {
if (value < 0) return 'Invalid Value';
int flooredValue = value.floor();
double decimalValue = value - flooredValue;
String hourValue = getHourString(flooredValue);
String minuteString = getMinuteString(decimalValue);
return '$hourValue:$minuteString';
}
String getMinuteString(double decimalValue) {
return '${(decimalValue * 60).toInt()}'.padLeft(2, '0');
}
String getHourString(int flooredValue) {
return '${flooredValue % 24}'.padLeft(2, '0');
}