So currently I'm building apps with Flutter which's still new to me, and I'm stuck at that exception in that title.
The problem is when I tried to call "widget.usernames.length" at ListView.builder, it would return that exception if it's null and no exception when there's data.
What I'm trying to accomplish is the get Length function should return null or 0 value so that the ListView would display nothing when there's no data.
return new Expanded(
child: ListView.builder(
padding: new EdgeInsets.all(8.0),
itemExtent: 20.0,
itemCount: widget.usernames.length,
itemBuilder: (BuildContext context, int index){
return Text("Bank ${widget.usernames[index] ?? " "}");
}
),
);
I already tried
itemCount: widget.usernames.length ?? 0
but still no success.
EDIT**
Thanks to Jeroen Heier this code working well.
var getUsernameLength = 0 ;
if(widget.usernames == null){
return getUsernameLength;
}else{
return widget.usernames.length;
}
If you use constructions like "widget.usernames.length" the programming code can fail on two places:
when widget = null
when widget.username = null (your situation)
You cannot call methods and properties on null-objects; that is why you get this error. So before you call widget.usernames.length you must be sure that both situations cannot occur. How this is done and if the check is really necessary depends on the rest of your program. One way to check is:
return widget?.username?.length ?? 0;
Related
case ConnectionState.done:
{
if (taskData.data != Null) {
return Padding(
padding: EdgeInsets.all(8.0),
child: ListView.builder(
itemCount : taskData.data.length,
itemBuilder: (context, index) {
String task =
taskData.data[index]['task'].toString();
String day = DateTime.parse(
taskData.data[index]['creationDate'])
.day
.toString();
},
),
);
The property 'length' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').
Missing case clause for 'none'.
Try adding a case clause for the missing constant, or adding a default clause.dart
The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
im getting these errors
i checked in an if statement that supposed to be a solution but it didnt fix it
tried Null and null same issue
im still noob im sorry if its simple but couldnt find an answer
edit
child: FutureBuilder(
future: getTasks(),
builder: (_, taskData) {
if (taskData.data != null){
print(taskData.data);
}
}
The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
the error after making taskData
Provide datatype on FutureBuilder/StreamBuilder and use taskData.data?.length on itemCount.
FutureBuilder<List<ModelClass>?>(
builder: (context, taskData) {
//... others
if (taskData.data != null) {
return ListView.builder(
itemCount: taskData.data?.length,
itemBuilder: (context, index) => Text(""),
);
}
// To handle body retun null
return Text("");
},
),
This error message show because you are your FutureBuilder is missing default return.
The body might complete normally, causing 'null' to be returned,
In my flutter app I am storing the URLs from firebase storage inside Firestore. I am expecting there to be null URL's as it is dependent on the user uploading images. In my code I am checking for null values, but for some reason the code still tries to load the null values. How do I correctly prevent flutter from loading the null values in network image. My code for the load is as follows:
Container(
width: 150,
height: 150,
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(8),
itemCount: photoList.length,
itemBuilder: (BuildContext context, int index) {
print(photoList[index]);
return photoList[index] != null ? Image.network(photoList[index]) : Container(height:400,child: Text('No Images to Display'));
}
),
),
Debug give the following for the print above when there is no image:
I/flutter (27038): url - null
When there is a image then there is a proper URL and the image loads without any issue.
So not quite sure why Flutter is still trying to load the null even though in that case of null I would like a text box instead
It looks like the value of photoList[index] is not consistent. As it prints "url - null" when it's expected to contain a null value and when it's not null, it contains an actual url that loads an image.
You can the either of the following:
Ensure your null images are actually null instead of "url - null" and the null check will work.
Use the errorBuilder property of the Image.network widget to display your error widgets like this:
Image.network(photoList[index],
errorBuilder: (context, error, stackTrace) {
return Container(height:400,child: Text('No Images to Display'));
}
)
What type of data stores in photoList? If String there is a chance "null" value is actually a string but not null.
I'm trying to migrate an existing, small Flutter app to Flutter 2.12. The null safety thing is new and still confusing to me. For the most part I have been successful in resolving the errors from the migration, but I haven't found a solution for this problem. Here we go:
I have a simple ProductListclass defined as so:
class ProductList {
int count = 0;
List<Product> rows = [];
}
No errors exist in the class. In my main.dart class I am using a ListView to view the list. In the method that creates the ListTile, both of the lines that refer to the productList.rows variable show an error. Here is the code:
eturn ListView.separated(
separatorBuilder: (context, index) => Divider(
color: Colors.black,
),
shrinkWrap: true,
padding: const EdgeInsets.all(2.0),
itemCount: productList.***rows***.length,
itemBuilder: (context, i) {
return _buildRow(productList.***rows***[i]);
});
The error message for those lines is:
The property 'rows' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').
I have peppered those lines with every combination of '?' and '!' over time, and still no luck. I'm sure I'm overlooking something simple, but I have no idea what that is. I'm new to null safety so Im still at the bottom of the learning curve and most of the official documentation I've found reminds me of reading the K&R (obscure reference for the old programmers in the crowd). Hat am I doing wrong?
change your productList declaration to late ProductList productList;
I have some problems understanding the StreamBuilder using the new null-aware operators.
As a learning project I am implementing a sign-in flow with the BloC pattern. For my email sign-in form I have created a model class which I access through a StreamBuilder. Without the use of initialData it makes complete sense that snapshot.data can be null. However, setting the initialData to a predefined empty model, snapshot.data could never be null right? Here is my code snippet:
#override
Widget build(BuildContext context) {
return StreamBuilder<EmailSignInModel>(
stream: widget.bloc.modelStream,
initialData: EmailSignInModel(),
builder: (context, snapshot) {
final EmailSignInModel model = snapshot.data;
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: _buildChildren(),
),
);
});
}
The compiler warns me that snapshot.data is of type <EmailSignModel?> which is not equal to . I could fix this with snapshot.data ?? EmailSignModel() but this would be redundant with initialData right?
What is the proper way of handling this situation and taken care of the null-awareness of Dart?
Diving into the source code, I found the following:
https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/async.dart
/// The latest data received by the asynchronous computation.
///
/// If this is non-null, [hasData] will be true.
///
/// If [error] is not null, this will be null. See [hasError].
///
/// If the asynchronous computation has never returned a value, this may be
/// set to an initial data value specified by the relevant widget. See
/// [FutureBuilder.initialData] and [StreamBuilder.initialData].
final T? data;
/// Returns latest data received, failing if there is no data.
///
/// Throws [error], if [hasError]. Throws [StateError], if neither [hasData]
/// nor [hasError].
T get requireData {
if (hasData)
return data!;
if (hasError)
throw error!;
throw StateError('Snapshot has neither data nor error');
}
AsyncSnapshot actually has a requireData getter, which will ensure non-null or will throw an error. So just replace snapshot.data with snapshot.requireData
This still requires some manual work where the use of initialData and requireData need to be kept in sync. You could also just use snapshot.data! which basically does the same.
I just replace the snapshot.data! with snapshot.requireData
I have this code in my index file:
_ontapd(_navigationLink,BuildContext context){
print(_navigationLink);
}
ListView.builder(
padding: EdgeInsets.only(top: 20),
itemCount: pages.length,
itemBuilder: (context, index) {
return ProfileCard(pages[index],_ontapd(_navigations[index],context));
}),
And this code in "ProfileCard" widget:
String cardText;
Function _onTapFunc;
ProfileCard(#required this.cardText, this._onTapFunc);
GestureDetector(
onTap: _onTapFunc,
...
)
Now whenever I refresh the app, the _onTapFunc gets called for each item in the pages list. Why does this happen?
It's being called because you're calling it in your itemBuilder. It's odd that you're not getting a static analysis error here.
In the line return ProfileCard(pages[index],_ontapd(_navigations[index],context));, you're calling the _ontapd method. Note the parentheses, this means you're calling the method and passing the return value, not passing a reference to it. This value is then being passed to the ProfileCard.
To fix this you need to remove the parentheses. Just pass _ontapd
return ProfileCard(pages[index],_ontapd);
This does result in other issues however. onTap does not have the same parameters your _ontapd method requires, so it cannot be used without modification.
In your current implementation _ontapd just prints the first parameter passed to it, it doesn't even use the second parameter. So a better solution here would be to pass the value of _navigationLink to ProfileCard and define the onTap to print that value. _ontapd could then be completely removed
onTap: () {
print(parameterPassed);
}
The example you provide may be simplified, in which case you hopefully have enough understanding of the error to come to a solution yourself or you'll have to provide more details.