Check name of list key and change it - flutter

I am trying to check the name of a key in a list and then change the name if it meets a certain criteria.
My code so far is:
String convert(double key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.key = convert(entry.key); //This seems to be incorrect
if (entry.key == "One") {
//do somehting
}
}
The error I get is this one:
The argument type 'String' can't be assigned to the parameter type 'double'.
I know I can do if (entry.key == "1") but later in the code I need entry.key to be a string One and not 1, so I would like to change the name before starting the if else check.

The problem is your code entry.key is a double variable and not a string. I would suggest adding a new field to the entry class called stringKey and store this value there. That would be something like
String convert(String key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.stringKey= convert(str(entry.key)); //This seems to be incorrect
if (entry.stringKey== "One") {
//do somehting
}
}

Related

Solidity method taking in bytes32 and hashing but values with previous hash don't match

Here's the code:
function playGame(bytes32 hashedMove) public returns (bool) {
require(
playerOne != address(0x0) && playerTwo != address(0x0),
"Game needs more players to join first"
);
require(
msg.sender == playerOne || msg.sender == playerTwo,
"You did not join the game as a player"
);
if (msg.sender == playerOne && hashedPlayerOneMove == "") {
hashedPlayerOneMove = hashedMove;
emit PlayerMadeMove(playerOne);
} else if (msg.sender == playerTwo && hashedPlayerTwoMove == "") {
hashedPlayerTwoMove = hashedMove;
emit PlayerMadeMove(playerTwo);
} else {
return false;
}
return true;
}
The above method takes in a hashedMove argument which I am using the following site to get: https://emn178.github.io/online-tools/keccak_256.html
I send a value of 2test2 hashed which is 0x0698472c4668bddd0c694601ca101551bd7b5cfe6dc780ab37bccfc99ad22e4c
Now another method takes in the constituents of the hash which are 2 and test2 to compare it with the stored hash:
function revealPlayerChoice(uint256 move, bytes32 password)
public
returns (uint256)
{
require(
hashedPlayerOneMove != bytes32(0x0) &&
hashedPlayerTwoMove != bytes32(0x0),
"The game is still running!"
);
bytes32 hashedAnswer = getSaltedHash(move, password);
console.logBytes32(hashedAnswer);
console.logBytes32(hashedPlayerOneMove);
if (msg.sender == playerOne && hashedAnswer == hashedPlayerOneMove) {
playerOneMove = move;
} else if (
msg.sender == playerTwo && hashedAnswer == hashedPlayerTwoMove
) {
playerTwoMove = move;
}
if (playerOneMove != 0 && playerTwoMove != 0) {
getGameOutcome();
}
}
I'm sending 2 as uint and 0x0000000000000000000000000000000000000000000000000000007465737432 (test2 in bytes) to the revealPlayerChoice method. However the values I'm getting from the console log are different. hashedAnswer is the hash I'm calculating in the method and hashedPlayerOneMove is the hash stored in playGame method.
for example, The console log outputs are
0x566d7dd4e9dc72e9beef887f2982703a0d0f9dd1b6505ee3ff5310c7383637bd
0x0698472c4668bddd0c694601ca101551bd7b5cfe6dc780ab37bccfc99ad22e4c
I would like to understand why the values are different? I'm using keccak256 to hash in solidity (pragma solidity ^0.8.0;) as well:
function getSaltedHash(uint answer, bytes32 salt) pure returns (bytes32) {
return keccak256(abi.encodePacked(answer, salt));
}
The key to your problem might be what abi.encodePacked(answer, salt) is returning.
When you pass the following arguments:
uint256 answer = 2
bytes32 salt = 0x0000000000000000000000000000000000000000000000000000007465737432
abi.encodePacked(answer, salt) returns:
0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000007465737432
And then, if you run the keccak256(bytes) with the previous value, it returns:
0x566d7dd4e9dc72e9beef887f2982703a0d0f9dd1b6505ee3ff5310c7383637bd

Don't execute assignment if value is null

I am still coming up to speed with dart and wanted to know if there was an easier way to not execute a statement if the value is null. See example below:
I can always do the if statements below for setting field3 and field4, but felt like something like field5 should work. But when I try to do that, it complains that a null check operator is used on a null value.
Also I don't want to change the Map to have a dynamic value.
Is there a single one liner to do what I am trying to do, or do I just need to check for null before setting the value.
Map<String, Object> myMap = {};
print('running now');
try {
myMap['field1'] = DummyClass.getString('hello');
myMap['field2'] = DummyClass.getString('good');
//Is there a more concise way to do this than the 2 options below?
if (DummyClass.getOptionalString('goodbye') != null) {
myMap['field3'] = DummyClass.getOptionalString('goodbye')!;
}
String? temp = DummyClass.getOptionalString('go');
if (temp != null) {
myMap['field4'] = temp;
}
// This gives an error 'null check operator used on a null value'
// myMap['field5'] ??= DummyClass.getOptionalString('to')!;
} catch (e) {
print('error condition, $e');
}
print(myMap);
}
class DummyClass {
static String getString(String? strParam) {
String? retString = getOptionalString(strParam);
if (retString == null) {
throw ('nulls are not allowed');
}
return retString;
}
static String? getOptionalString(String? strParam) {
if (strParam == null || strParam.length < 3) {
return null;
}
return strParam;
}
}
There's no built-in way to do what you want, but you could write a function (or extension method) to do it. For example:
extension MapTrySet<K, V> on Map<K, V> {
void trySet(K key, V? value) {
if (value != null) {
this[key] = value;
}
}
}
and then you could do:
myMap.trySet('field3', DummyClass.getOptionalString('goodbye'));
myMap.trySet('field4', DummyClass.getOptionalString('go'));
Alternatively, if you really want to use normal Map syntax, you could create your own Map class that has a void operator []=(K key, V? value) override and does nothing when the value is null, but that probably would not be worth the effort.
The issue is that the ??= operator assigns to the left if it is null. Expanded, it would look something like this:
a ??= b;
// Equivalent to:
if (a == null) {
a = b;
}
Which is not something that you're trying to achieve. AFAIK, there is no such operator yet in Dart. However, you can try this:
final possiblyNullValue = '';
final myMap = <String, String>{};
myMap['key'] = possiblyNullValue ?? myMap['key'];
// Equivalent to:
if (possiblyNullValue != null) {
myMap['key'] = possiblyNullValue;
}
// or:
myMap['key'] = possiblyNullValue != null? possiblyNullValue : myMap['key'];
Which would work in your case as a one-liner.
You could create your map with all entries, even null, and then filter the null values out:
void main() {
try {
final myMap = <String, dynamic>{
'field1': DummyClass.getString('hello'),
'field2': DummyClass.getString('good'),
'field3': DummyClass.getOptionalString('goodbye'),
'field4': DummyClass.getOptionalString('go'),
}..removeWhere((k, v) => v == null);
print(myMap);
} catch (e) {
print('error condition, $e');
}
}

"receiver can be null" when it can't?

I just finished my nullsafe migration. I'm finding that wrapping code with a null check only sometimes removes the need for the nullcheck ! operator? E.g.,
class MyClass {
double divideBy4(double numerator) {
return numerator / 4;
}
double quarteredWorks(double? value) {
if (value != null)
return divideBy4(value); // <- no intellisense warning
else
return 0;
}
double quarteredDoesntWork(double? value) {
return divideBy4(value); // <- intellisense: "double? can't be assigned to double"
}
double? value;
double divideBy2() {
if (value != null)
return value / 2; // <- intellisense: "receiver can be null"
else
return .0;
}
}
EDIT
Changed my example to show an example of wrapping with a null check that works

How can I give string to translate?

I am using key - value translation-S.of(context).translation_key- but I need something like "Translation string".translate() or translate("Translation string")
How can I do this ?
I am using localizely plugin.
Flutter version is lastest.
Attention: I am not asking for translate("key") I am asking translate("Translate String")
I want to give a value and get current translation value.
I'd suggest you to do it the other way:
String _localeCode = 'en';
Your method:
String translate(String key) {
if (_localeCode == 'en') {
if (key == 'key1') return 'English translation for key1';
else if (key == 'key2') return 'English translation for key2';
} else if (_localeCode == 'es') {
if (key == 'key1') return 'Spanish translation for key1';
else if (key == 'key2') return 'Spanish translation for key2';
}
}
And you'd use it:
void main() {
var translatedString = translate('key1');
}
For simplicity I hardcoded the things, but a better solution is to load the keys through a json file, here's a better approach

Getting WorkbookPart from row

I am writing and extension for OpenXML like shown in the sample. I would like to avoid having to pass the WorkbookPart as parameter. Is there any way to get the WorkbookPart directly from the row?
public static string GetCellTextValue(this Row row, WorkbookPart workbookPart, string column)
{
var cells = row.Elements<Cell>();
var cell = cells.Where(p => p.CellReference == column + row.RowIndex.ToString()).FirstOrDefault();
if (cell.DataType != null)
{
if (cell.DataType == CellValues.SharedString)
{
int id = -1;
if (Int32.TryParse(cell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
return item.Text.Text;
}
else if (item.InnerText != null)
{
return item.InnerText;
}
else if (item.InnerXml != null)
{
return item.InnerXml;
}
}
}
}
return string.Empty;
}
Unfortunately, none of the strongly-typed classes of the Open XML SDK (e.g., Workbook, Worksheet, Row) have properties pointing back to the OpenXmlPart (e.g., WorkbookPart, WorksheetPart) in which they are contained or any other part related to their immediate container. Unless you amend your API in other ways, you will have to pass that WorkbookPart.