Reputation: 3
I'm trying to make a Fetch Data on Flutter but my app gives the error:
The getter 'length' was called on null. Receiver: null Tried calling: length.
If I insert a log in result.statusCode
, my value return in console.
I tried to consult other projects and documentation, but nothing works. I need the data to be applied to a label or even a text and return, but this is my main problem.
My code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class UserList extends StatelessWidget{
final String apiUrl = "myAPI";
Future<List<dynamic>> fetchUsers() async {
var result = await http.get(apiUrl,
headers: {HttpHeaders.authorizationHeader: "Bearer TOKEN"});
if(result.statusCode == 200){
return json.decode(result.body)['results'];
} else{
throw Exception('Não foi possível funcionar');
}
}
bool _sucess(dynamic sucess){
return sucess['sucess'];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User List 1'),
),
body: Container(
child: FutureBuilder<List<dynamic>>(
future: fetchUsers(),
// ignore: missing_return
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
print(_sucess(snapshot.data[0]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
return
Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
title: Text(_sucess(snapshot.data[index]).toString()),
)
],
),
);
});
}
else {
print(_sucess(snapshot.data[3]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
return
Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
title: Text(_sucess(snapshot.data[index]).toString()),
)
],
),
);
});
}
},
),
),
);
}
} ```
My JSON:
{
"success": true,
"data": [
{
"id": 15014,
"itens": [
{
"data": "2020-06-23T14:38:03.000Z",
"pac": 6816608,
}
],
"podeImprimir": true
}
]
} ```
Upvotes: 0
Views: 412
Reputation: 341
When if (snapshot.hasData)
returns false, you are still calling .length
on snapshot.data
, which is why you're receiving an error.
...
else { // This code is executing because (snapshot.hasData) has returned false
print(_sucess(snapshot.data[3]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length, // This is causing the error, snapshot.data is null
itemBuilder: (BuildContext context, int index){
...
Set your itemCount
some other way, like with a constant- itemCount: 1
, or with a variable that is not null.
Upvotes: 1