Issue
I'm new to flutter and getting an Error in passing the String and looked everywhere and finally adding this in StackOverflow
the error is
Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
void errorSnackBar(BuildContext context, String? text) {
ScaffoldMessenger.of(context).showSnackBar(new SnackBar(
duration: new Duration(seconds: 4),
content: new Row(
children: <Widget>[
Icon(
Icons.error,
color: Colors.red,
),
Padding(
padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 0),
child: new Text(text),
),
],
),
));
}
Solution
Text()
requires a String
as its first parameter (i.e. not null
). null
is not a valid value for the type String
, just like 123
is not a valid value for the type String
.
If your error message is a String?
, you need to handle the case where it is null
before you can pass it to Text()
. Some options are:
- Check if it is null and return early:
void errorSnackBar(BuildContext context, String? text) {
if (text == null) return;
// dart uses "type promotion" to know that text is definitely not null here
final textWidget = Text(text); // this is fine
ScaffoldMessenger.of(context) ... // show snackbar
}
- If you know that you only call
errorSnackBar
whentext
is non-null, try changing it's type:
void errorSnackBar(BuildContext context, String text) {
// rest of the method the same
}
Answered By - cameron1024
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.