Flutter compile error: non-null value must be returned since the return type 'String' doesn't allow null - displayString - flutter

My tests are failing to compile and run in a Dart only project that is referenced by my Flutter project. I'm receiving the following error message
Failed to precompile test:test:
../../../../../../../../../.pub-cache/hosted/pub.dartlang.org/analyzer-1.0.0/lib/src/error/best_practices_verifier.dart:1952:14: Error: A non-null value must be returned since the return type 'String' doesn't allow null.
String get displayString {
Any ideas please?
Flutter 2.2.1 (current stable channel)
Tools • Dart 2.13.1
(I've asked the question in Flutter's github here also)
https://github.com/flutter/flutter/issues/83683

There was a component using analyzer version 1.0.0
Upgrading this component to use analyzer version 1.7 or above seemed to fix the problem for me.

go to this file: flutter/.pub-cache/hosted/pub.dartlang.org/analyzer-1.5.0/lib/src/error/best_practices_verifier.dart:1978:14.
and add below:-
default:
return '';

Please check the function displayString to make sure that it returns non-null string variable. There are some use cases that I guess you might face with
Use "required" if you get the variable from parameters (ex: String displayString(required String var)).
If the variable is optional parameter, then you need to check if it is null or not. Then, you could "return var!;" to let the function knows that you already confirmed the variable content.
If you want to return nullable String, then you should change the function to "String? displayString".

Related

Flutter-> Error: The argument type 'Column' can't be assigned to the parameter type 'Widget?'

I just upgrade my flutter version few days ago. Now i got error in Column widget.
Here is my error.
And here is my pubspec.yaml
HELP ME TO SOLVE THIS.
This error is misleading, just simplify your column as suggested in the comments by stacktrace2234 to see what really is going on.
Did you update it from a non null safety to a null safety dart version?

Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null

when i made flutter upgrade then run my app this error occurs.
../../../development/tools/flutter/.pub-cache/hosted/pub.dartlang.org/responsive_sizer-3.0.6+1/lib/src/helper.dart:56:33: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('../../../development/tools/flutter/packages/flutter/lib/src/widgets/binding.dart').
pixelRatio = WidgetsBinding.instance!.window.devicePixelRatio;
and also the app is getting me warning but still running normally
Error here
This is a warning not an error. In Flutter 3 the instance property on bindings such as WidgetsBinding and SchedulerBinding is now non-nullable, hence using the null-aware operator ? or the null assertion operation ! will lead to this warning.
If this warning originates from an external package as in your case, you could reach out to the developer and file an issue. Although for your specific package it should already be solved in version 3.0.7 or later as discussed here. So upgrading the package should solve the issue.
As far as your own code is concerned, you can run dart fix --apply and remove any null-aware or null assertion operators. E. g. change
SchedulerBinding.instance!.addPostFrameCallback(...);
to
SchedulerBinding.instance.addPostFrameCallback(...);
This page from the Flutter docs describes your options in greater detail.
If you need to fix this issue in a package and still want to support Flutter 2 it's actually better to bypass this issue like so:
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
// See https://github.com/flutter/flutter/issues/64830
T? _ambiguate<T>(T? value) => value;
_ambiguate(SchedulerBinding.instance)!.addPostFrameCallback((_) {
// ...
}
However, as soon as you ditch Flutter 2 support for further development, you should apply the accepted solution.
Ref: https://github.com/flutter/packages/pull/546/files

Dart: Null-safety and retrieving values from maps

there is one thing I can't quite wrap my head around concerning null-safety in Dart, and that concerns how to safely retrieve values from Map<String,dynamic> (I've read the FAQ from the Dart docs).
Basically, the following code in the DartPad with null-safty enabled is valid:
void main() {
int i;
Map<String, dynamic> map = {"key": 1};
i = map["key"];
print(i);
}
Which I do not understand. Why can I assign map["key"] to i without the compiler shouting at me? From the docs:
Code should be safe by default. If you write new Dart code and don’t
use any explicitly unsafe features, it never throws a null reference
error at runtime.
But exactly this is happening. If, in the code above, the key is not in the map, or contains some random type, the program will crash on runtime, which I though is what should never happen with null safety.
I'm particular interested in this since I'm writing a Flutter app and don't understand how to properly deserialize the JSON data I fetch from the DB (try..catch? Special syntax like ??= ?). Even though I don't have the 'non-nullable' language feature enabled (I can't even write int? val without getting a warning), the compiler does not seem to mind that I assign nullable values to non-nullable variables, and will happily crash on runtime if they are null.
Basically, my question does not only concern null-safety, but the type system in general, since from my understanding it shouldn't be possible to assign a dynamic value to an int variable, but obviously this works with Map. Any explanation is greatly appreciated!
A dynamic variable can contain any data type, "dynamic" keyword is used when you don't know the specific data type that might be returned.
and what you're actually doing here:
i = map["key"];
is assigning a "dynamic" variable to an "int" variable and since dynamic in this case the value in the key/value pair of your Map is an integer which matches the data type "int" of variable "i" it won't crash because of type inference done at runtime and not compile time. if the "dynamic" variable was a String it would crash at runtime because of a type mismatch. Hope this is explanatory.

A value of type 'List<int>' can't be assigned to a variable of type 'Iterable<int>'

I don't know if this was happening before my switch to the beta channel in Flutter but I don't understand why this is an error. A List is an Iterable right? I took the example from the official docs.
Iterable<int> example() {
Iterable<int> iterable = [1, 2, 3];
return iterable;
}
VSCode marks the list with a red underline telling me:
A value of type 'List<int>' can't be assigned to a variable of type 'Iterable<int>'.
Try changing the type of the variable, or casting the right-hand type to 'Iterable<int>'. dart(invalid_assignment)
I think the problem is the as is more of an assertion and not a cast. To perform the cast you need to use the .cast function:
https://api.flutter.dev/flutter/dart-core/List/cast.html
E.g.
# ...
.toList().cast<Iteratable<File>>()
You can read more from this answer covering when/why to cast: https://stackoverflow.com/a/49542401/931209
Alternatively, you can probably call the iterator property on the list (but the above is likely the more correct solution):
https://api.dart.dev/stable/2.10.4/dart-core/Iterable/iterator.html
I don't know what was the problem but I tried removing the Flutter and Dart extensions from VSCode, restarting the whole computer and installing them again (in that order) and now the same code works!
As BeefPapa said in a comment, the code was absolutely correct.
Who knows what happened.
You need convert again the results to List adding .toList() in the end because Dart changes the type of the variable.

How to debug the Null Safety default value type error on double question mark '??'

I recently run into some strange behavior when using double question mark.
Here is the example code:
void main() {
String strA;
String strB;
print('start');
strB = strA ?? 5; // wrong use of default value type. It should be a String here.
print('end');
}
The program never run to the end and even not throwing out any error message.
Is the behavior expected?
How you're running this code?
When I run it, I get this output:
▶ dart test.dart
start
Unhandled exception:
type 'int' is not a subtype of type 'String'
#0 main (file:///Users/renato/programming/projects/test.dart:6:3)
As I expected.
What Dart version are you using (run dart --version)? Make sure you have an up-to-date version like 2.10.
If you still have issues, you might have a local analysis_options.yaml file which overrides the Dart compiler checks to be more lenient, in which case it might not check the types (I am not sure which option would enable this, but I suppose it's possible).
Check how analysis options work here.
I suggest you always enable "strong mode" by adding this to your analysis options file:
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
By the way, if you want to try the new Dart NNBD (Not-Null-By-Default) experimental feature, you need to use the Dart dev channel releases and run your program with dart --enable-experiment=non-nullable file.dart.
To learn how to enable NNBD, check the null-safety tech preview 2 blog post about it.