The return type 'bool' isn't a 'void', as required by the closure's context dart flutter - 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

Related

Dart Factory class for creating variables with type

The problem is the following.
I had a typescript factory class that I attempted to do in Dart:
class FactoryClass{
factory FactoryClass(dynamic types, String className, dynamic defaultValue){
if(types[className] != null ){
return types[className](defaultValue);
}
else{
throw Exception("");
}
}
}
In TS it was used like this:
let variable= new FactoryClass([String, Number, etc...], "Number", "42")
That in TypeScript would give back a Number type variable with the value 42
However, it's not gonna work in Dart since types have no constructor for this. So I can't do something like
final myString = new String("def_value")
So the question arises, how can I go about it in dart?
You can do similar in Dart with just functions:
typedef Factory = dynamic Function(dynamic value);
dynamic create(Map<String, Factory> types, String className, dynamic defaultValue) {
if (types.containsKey(className)) {
return types[className]!(defaultValue);
} else {
throw Exception("no factory for $className");
}
}
final factories = <String, Factory>{
'String': (s) => s.toString(),
'int': (i) => i is int ? i : int.parse('$i'),
'bool': (b) => b is bool ? b : ('$b' == 'true'),
};
show(v) => print('Value $v has type ${v.runtimeType}');
main() {
show(create(factories, 'String', 'foo'));
show(create(factories, 'int', '42'));
show(create(factories, 'bool', 'false'));
}
Prints:
Value foo has type String
Value 42 has type int
Value false has type bool

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);
}

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

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.

Cannot return Null from a non-nullable type function

This is the error message I am getting:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
on the following code:
Product findProductById(String prodId) {
_productsList.firstWhere((element) {
return prodId == element.id;
});
}
I want to find the Product by its id but if its not found what should I return?
You're not returning inside the findProductById function:
Product findProductById(String prodId) {
return _productsList.firstWhere((element) {
return prodId == element.id;
});
}
From Dart 2.12 and up, we need to specify whether if a type is nullable or non-nullable.
In your case, you should add '?' question mark after the type name Product as you can see below, which will tell the compiler that your function can return a nullable product.
Also you forgot to return the filtered product from the productList.
Product? findProductById(String prodId) {
return _productsList.firstWhere((element) {
return prodId == element.id;
});
You can return a empty Product it's not found.
Product findProductById(String productId) {
return productList.firstWhere((element) => element.id == productId,
orElse: () => Product() // make a empty product using default constructor);
}

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
}