Why I am getting this error while doing Method Cascade in Dart? - flutter

I have a single line code which removes trailing and leading whitespaces, and also replaces multiple spaces in between with a single space. (from a string)
value = value..trim()..split(" +")..join(" ");
However I am getting the following error.
The method 'join' isn't defined for the type 'String'.
Try correcting the name to the name of an existing method, or defining a method named 'join'.(dartundefined_method)
What i am doing wrong?

You don't need cascade notation there:
value = value.split(' ').where((x) => x.isNotEmpty).map((x) => x.trim()).join(" ")

I forgot adding RegExp.
value = value.trim().split(RegExp(" +")).join(" ");
is working!!

Related

vscode shows error in JSX attribute name that has colon

In my JSX code I have attribute name that has colon in its name but vscode shows error. Even after formatting my code, vscode automatically create a space after colon. How to solve these two problems?
By not having colon in your attribute name. While technically possible, attribute names should be camelCase.
If you can't get around this, you could create and object and destructure it onto props.
const A = () => {
const fooProps = {
'on:resize': onResize
}
return <Foo {...fooProps} />
}

The argument type 'String?' can't be assigned to the parameter type 'String'

when I upgrade my flutter to 2.0.1, shows this error:
The argument type 'String?' can't be assigned to the parameter type 'String'.
this is my code:
enum SubStatus {
SUB,
UNSUB,
}
extension ResponseStatusExtension on SubStatus{
static const statusCodes = {
SubStatus.SUB: "sub",
SubStatus.UNSUB: "unsub",
};
String? get statusCode => statusCodes[this];
}
This is how to use it:
String url = "/post/sub/source/" + subStatus.statusCode + "/" + channelId;
this is the error UI:
what should I do to fix it? I tried to return String but in the enum code tell me should return String?:
what should I do?
Change the return type of statusCode to String and provide a default value.
String get statusCode => statusCodes[this] ?? '';
When accessing a map, there is a chance that you will get a null return value if the key does not exist in the map. Simply providing a default value will allow this code to compile. That default value should never be used unless you add something to the enum without adding a value to the map as well.
Edit:
After the comment from #Christopher Moore, I realized my mistake. So, I am going to directly use his solution over here as it is the correct one.
This is because of the new null-safety feature of Dart.
You will need to make the following change in the code and it will work:
String get statusCode => statusCodes[this] ?? '';
With new null-safety rules, the following data-type? x, the data type is followed by a question mark, means that the value x can be null. However, without the '?', it means that data-type x, it cannot be null.
So, basically String and String? are two different data types. That is why you get the error.
You can learn more here.
restart analysis server
add !
like this
subStatus.statusCode!

Multi if statement in class parameters setting

I know that in the latest version of dart we can use if else statements inside the build method. Does anyone know if we can use also if else statement when we setting class parameters? I know I can do inline statement there but inline is a bit hard to read when there are multiple conditions
const int i = 0;
class Person {
// NewClass n = NewClass(a: i == 0 ? 'a' : 'b'); //<- inline statement working
NewClass n = NewClass(a: if(i == 0) 'a' else 'b'); //<- if statement doesn't
}
class NewClass {
final String a;
const NewClass({this.a});
}
Edit:
Basically in my case I've got an TextField widget where I set its's type parameter from enum (Type.text, Type.numeric...) According to this parameter I want to set The textField parameters (textCapitalization, maxLength and so on)
As per your comment, you are already creating an enum for specifying the type of the fields.
enum Type {text, numeric}
Now for specifying the properties of that particular type, you can add an extension on this enum, as shown below:
extension TextFieldProperties on Type {
int get maxLength {
if (this == Type.text) {
return 10;
}
return 12;
}
}
So in your field class you already have a type defined, you can use that type variable to get the properties of that particular type of field.
Type type = Type.text;
print(type.maxLength); // Will print 10
type = Type.numeric;
print(type.maxLength); // Will print 12
Note: It will work only in Dart 2.7 and above
You want the conditional expression (?:), not the conditional statement or literal entry (if), as you have already discovered.
The reason if doesn't work is that if only works as a statement or as a collection literal entry. It doesn't work in arbitrary expressions.
The reason for the distinction is that the if syntax allows you to omit the else branch. That only makes sense in places where "nothing" is a valid alternative. For a statement, "doing nothing" is fine. For a collection, "adding nothing" is also fine.
In an expression context, you must evaluate to a value or throw. There is no reasonable default that we can use instead of "nothing", so an if is not allowed instead of an expression.
Doesn't work because this syntax doesn't exist in Dart. The only way to do what you would like to do is to use the ternary operator.
If you try it in the DartPad you will get an error.
I suggest you to use a function to return the right value.

Remove several elements from Postgres array with jOOQ

I'm trying to use jOOQ to create a function akin to arrayRemove but that allows removing several elements at once from a PostgreSQL column of type uuid[].
So my first attempt was:
private Field<UUID[]> arrayRemoveAll(final Field<UUID[]> field, final Set<UUID> elements) {
return select(field("array_agg(tab.col)", UUID[].class))
.from(unnest(field).as("tab", "col"))
.where(field("tab.col", UUID.class).notIn(elements))
.asField();
}
Which succeeds at removing every requested element, but has the problem of returning null instead of an empty array if I attempt to remove every element.
So I added a coalesce to my code to make it return an empty array:
private Field<UUID[]> arrayRemoveAll(final Field<UUID[]> field, final Set<UUID> elements) {
final Field<UUID[]> newArray = select(field("array_agg(tab.col)", UUID[].class))
.from(unnest(field).as("tab", "col"))
.where(field("tab.col", UUID.class).notIn(elements))
.asField();
return coalesce(newArray, field("{}", UUID[].class));
}
But running this code threw this exception:
org.jooq.exception.DataAccessException: SQL [<<confidential SQL removed>>]
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
This is the part of the SQL exception it is complaining about (notice the trailing comma and missing 2nd parameter in the coalesce):
coalesce((select array_agg(tab.col)
from unnest("my_schema"."my_table"."my_field") as "tab"("col")
where tab.col not in (?, ?)), )
Is this a bug in jOOQ?
I found that I had a mix of field and val in the code above, changing field("{}", UUID[].class) to val(new UUID[0]) solves the problem.
Also check Lukas Eder's answer about how to solve the issue using field.
So the final code, with generics, looks like this:
private <T> Field<T[]> arrayRemoveAll(final Field<T[]> field, final Set<T> elements, final T[] emptyArray) {
final Field<T[]> newArray = select(field("array_agg(tab.col)"))
.from(unnest(field).as("tab", "col"))
.where(field("tab.col").notIn(elements))
.asField();
return coalesce(newArray, val(emptyArray));
}
And you can use it in your statements like this:
using(configuration)
.update(MY_TABLE)
.set(MY_TABLE.MY_COLUMN,
arrayRemoveAll(MY_TABLE.MY_COLUMN, someElements, new UUID[0]))
.where(MY_TABLE.ID.eq(...))
.execute();
Your field("{}") does not generate the {} string in the SQL, but is considered a part of jOOQ's plain SQL templating language, which unfortunately doesn't allow for escaping those braces:
https://www.jooq.org/doc/latest/manual/sql-building/plain-sql-templating
Luckily, PostgreSQL supports a more formal, standards-compliant way to create an empty array literal:
field("array[]::uuid[]", UUID.class)

String.isSubstring dosnt work - sml

I want to check if a line contains a specific word, so I tried to use the String.isSubstring function with the line and the specific word. But somehow that function dosn't work for me.
String.isSubstring("Hi my name is...", "name");
stdIn:2.1-2.47 Error: operator and operand don't agree [tycon mismatch]
operator domain: string
operand: string * string
in expression:
String.isSubstring ("Hi my name is...","name")
-
I will love if some one can tell me what did i do wrong?
Thanx
String.isSubstring is a curried function -- that is, its arguments are passed in separately, not as a tuple.
Try
String.isSubstring "Hi my name is..." "name"