I am trying to fetch data from an API but unable to get because of this length error. "The property 'length' can't be unconditionally accessed because the receiver can be 'null'.\nTry making the access conditional (using '?.') or adding a null check to the target ('!').",
When i put null check it is giving the error below: The getter 'length' isn't defined for the type 'Object'. Try importing the library that defines 'length', correcting the name to the name of an existing getter, or defining a getter or field named 'length'.
Here is the Code :
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class api extends StatefulWidget {
const api({Key? key}) : super(key: key);
@override
_apiState createState() => _apiState();
}
class _apiState extends State<api> {
getuser() async {
var users = [];
var response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
var jsonData = jsonDecode(response.body);
for (var i in jsonData) {
UserModel user = UserModel(i['name'], i['username'], i['email']);
users.add(user);
}
return users;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getuser(),
builder: (context, snapshot) {
if (snapshot.data != null) {
return Container(
child: Text("Nothing in API"),
);
} else
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: Text((snapshot.data as dynamic)[i].name),
);
});
}),
);
}
}
class UserModel {
var name;
var username;
var email;
UserModel(this.name, this.username, this.email);
}
Resolved the Error by adding AsyncSnapshot before snapshot in FutureBuilder-builder and also replacing the line from if (snapshot.data != null) to if (snapshot.data == null).
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class api extends StatefulWidget {
const api({Key? key}) : super(key: key);
@override
_apiState createState() => _apiState();
}
class _apiState extends State<api> {
getuser() async {
var users = [];
var response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
var jsonData = jsonDecode(response.body);
for (var i in jsonData) {
UserModel user = UserModel(i['name'], i['username'], i['email']);
users.add(user);
}
return users;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getuser(),
builder: (context,AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Nothing in API"),
);
}
else return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(snapshot.data[i].name),
subtitle: Text(snapshot.data[i].username),
);
});
}),
);
}
}
class UserModel {
var name;
var username;
var email;
UserModel(this.name, this.username, this.email);
}