type 'Null' is not a subtype of type 'bool' in type cast - flutter

I have Created a Map<String,bool>(in which the key are of type String and the values are of type Boolean) in flutter and When I want to use the bool values in if condition it give me error saying "A nullable expression can't be used as a condition.
Try checking that the value isn't 'null' before using it as a condition."
When I use "as bool" then the error is gone but the program is not executed properly and give me the error in the pic
//this is the code
Map<String, bool> _userFilters = {
"gluten": false,
"lactose": false,
"vegan": false,
"vegetarian": false,
};
List<Meal> filteredMeal = DUMMY_MEALS;
void saveFilters(Map<String, bool> filteredData) {
setState(() {
_userFilters = filteredData;
filteredMeal = DUMMY_MEALS.where(
(meal) {
if (_userFilters['gluten']as bool) { // _userFilter['gluten'] is giving error
return false;
}
if (_userFilters['lactose']as bool) {
return false;
}
if (_userFilters['vegan']as bool) {
return false;
}
if (_userFilters['vegetarian'] as bool) {
return false;
}
return true;
},
).toList();
});
}

No need to cast your map entries to booleans. use an exclamation mark at the end of your variable (e.g, _usedFilters['gluten']!) to treat it as non-nullable.
Rewrite all your conditions like this (if you're sure that the value won't be null):
if (_userFilters['gluten']!) {
return false;
}
if (_userFilters['lactose']!) {
return false;
}
if (_userFilters['vegan']!) {
return false;
}
if (_userFilters['vegetarian']!) {
return false;
}
From Dart.dev:
“Casting away nullability” comes up often enough that we have a new
shorthand syntax. A postfix exclamation mark (!) takes the expression
on the left and casts it to its underlying non-nullable type.

Related

forEach -> return true; // error The return type 'bool' isn't a 'void', as required

Hello I try to make null safety migration, but I have an error with a forEach loop who return return true. I don't know how to write correctly in null stafety. Thank you
String sanitize(
String input, List<String> possibleStart, List<String> possibleEnd) {
final String start = possibleStart.join("|");
final String end = possibleEnd.join("|");
final RegExp exp = RegExp("(?<=$start)(.*?)(?=$end)");
final Iterable<Match> matches = exp.allMatches(input);
matches.forEach((match) {
input =
input.replaceFirst(match.group(0)!, match.group(0)!.replaceAll(",", "§").replaceAll(":", "ø").replaceAll("/", "å"));
return true; // error The return type 'bool' isn't a 'void', as required by the closure's context dart flutter
});
return input;
}
function forEach isn't supposed to return anyting, you can see it from iterable.dart
void forEach(void action(E element)) {
for (E element in this) action(element);
}

how to pass uncertain parameter to method flutter

I have a method like following:
void reverseWeekdayStatus({alarmClock,sundayIsSelected}){
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected ?? false;
update();
}
alarmClock is a model:
class AlarmClock {
bool sundayIsSelected;
bool mondayIsSelected;
bool tuesdaySelected;
bool wednesdayIsSelected;
bool thursdayIsSelected;
bool fridayIsSelected;
bool saturdayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
this.mondayIsSelected = false,
this.tuesdaySelected = false,
this.wednesdayIsSelected = false,
this.thursdayIsSelected = false,
this.fridayIsSelected = false,
this.saturdayIsSelected = false,
});
}
so for this method I want to not just sundayIsSelected also the rest like mondayIsSelected could be reversed if I implement this method, what I did is following:
void reverseWeekdayStatus({alarmClock,whichDay}){
alarmClock.whichDay = !alarmClock.whichDay ?? false;
update();
}
And pass mondayIsSelected for example to whichDay, and then I got an error since whichDay does not exist in alarmClock, another way I thought is to create separate methods like from monday to sunday, is there a smarter way to do this job? thanks!
class AlarmClock {
bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
}
On current mode, you are providing default for each field. If you don't pass any value for sundayIsSelected it will get default value false. But sundayIsSelected is not nullable. It can't be null.
Therefore, alarmClock.sundayIsSelected ?? false will never get false.
To reverse, you just like to change the value then do
void reverseWeekdayStatus({
alarmClock,
}) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
...
}
It will switch the bool when ever gets call. You can do conditional state on update case, and it is an optional parameter with default value.
void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
if (switchSundayState) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
}
}
Another technic is using copyWith constructor, it is nullable (optional) named constructor, use current value if we don't pass value for field.
class AlarmClock {
final bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
AlarmClock copyWith({
bool? sundayIsSelected,
}) {
return AlarmClock(
sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
);
}
}
And use cases
alarmClock = alarmClock.copyWith(sundayIsSelected: true);

why scala in this case can't use single abstract method?

i use spring boot's RedisTemplate with scala, and i write this code:
redisTemplate1.executePipelined(new RedisCallback[String] {
override def doInRedis(connection: RedisConnection): String = {
MyCode......
null
}
}, redisTemplate1.getValueSerializer)
usually, it's can be wrote like this:
redisTemplate1.executePipelined((connection: RedisConnection) => {
MyCode......
null
}, redisTemplate1.getValueSerializer)
and this style is running well in java:
redisTemplate1.executePipelined((RedisConnection conn) -> {
MyCode......
return null;
}, redisTemplate1.getValueSerializer());
but when i compile in this style with scala, i get an error, so why this happend and how can i use single abstract method in this case?
overloaded method value executePipelined with alternatives:
(x$1: org.springframework.data.redis.core.RedisCallback[_],x$2: org.springframework.data.redis.serializer.RedisSerializer[_])java.util.List[Object] <and>
(x$1: org.springframework.data.redis.core.SessionCallback[_],x$2: org.springframework.data.redis.serializer.RedisSerializer[_])java.util.List[Object]
cannot be applied to (org.springframework.data.redis.connection.RedisConnection => Null, org.springframework.data.redis.serializer.RedisSerializer[?0(in method syncSegmentSrc)])
redisTemplate1.executePipelined((connection: RedisConnection) => {
the executePipelined function source code like this:
#Override
public List<Object> executePipelined(SessionCallback<?> session, #Nullable RedisSerializer<?> resultSerializer) {
Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(session, "Callback object must not be null");
RedisConnectionFactory factory = getRequiredConnectionFactory();
// bind connection
RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
try {
return execute((RedisCallback<List<Object>>) connection -> {
connection.openPipeline();
boolean pipelinedClosed = false;
try {
Object result = executeSession(session);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}
List<Object> closePipeline = connection.closePipeline();
pipelinedClosed = true;
return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer);
} finally {
if (!pipelinedClosed) {
connection.closePipeline();
}
}
});
} finally {
RedisConnectionUtils.unbindConnection(factory);
}
}
#Override
public List<Object> executePipelined(RedisCallback<?> action, #Nullable RedisSerializer<?> resultSerializer) {
return execute((RedisCallback<List<Object>>) connection -> {
connection.openPipeline();
boolean pipelinedClosed = false;
try {
Object result = action.doInRedis(connection);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}
List<Object> closePipeline = connection.closePipeline();
pipelinedClosed = true;
return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer);
} finally {
if (!pipelinedClosed) {
connection.closePipeline();
}
}
});
}
In cases like this, it should help to specify the type explicitly:
redisTemplate1.executePipelined({ connection =>
YourCode…
}: RedisCallback[String], redisTemplate1.getValueSerializer)
Note the type ascription : RedisCallback[String].

A value of type 'Null' can't be returned from the method 'fetchById' because it has a return type of 'Location'

static Location fetchById(int id) {
List<Location> locations = Location.fetchAll();
for (var i = 0; i < locations.length; i++) {
if (locations[i].id == id) {
return locations[i];
}
}
return null;
}
// if the condition is not true then return null when I try to return null or false it gives the error 'A value of type 'Null' can't be returned from the method 'fetchById' because it has a return type of 'Location'.
With null-safety feature in the dart language, you have to explicitly tell if you want to make a value nullable.
Define the return type with a ?, so dart knows that return value can be null.
static Location? fetchById(int id)
{
/// function body
}

The return type 'bool' isn't a 'void', as required by the closure's context dart flutter

I am getting the below error when using the forEach loop for the items when used in the function when returning the values.
bool validatedValues(List<String> values){
values.forEach((i){
if (i.length > 3){
return true;
}
});
return false;
}
Im using dart null safety sdk version: ">=2.12.0 <3.0.0"
Complete error:
The return type 'bool' isn't a 'void', as required by the closure's context.dartreturn_of_invalid_type_from_closure
The problem is caused by the return true inside your forEach. forEach is expecting a void Function(T) not a bool Function(T).
I think that what you try to achieve is:
bool validatedValues(List<String> values){
bool result = false;
values.forEach((i){
if (i.length > 3){
result = true;
}
});
return result;
}
Or, probably more elegant:
bool validatedValues(List<String> values) => values.any((i) => i.length > 3);
bool any(bool test(E element));
This returns true if at least one item of the List is validated by test. ref
bool every(bool test(E element));
This return true if all the items of the List are validated by func. ref