0

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
        }
    ]
} ```
4
  • Can you paste the json that you get from apiUrl? It seems that results is null Commented Jul 2, 2020 at 20:07
  • {"success": true, "data": [ { "id": 15014, "itens": [ { "data": "2020-06-23T14:38:03.000Z", "pac": 6816608, } ], "podeImprimir": true } ] } Commented Jul 2, 2020 at 20:33
  • You don't have results in there. What do you expect when executing json.decode(result.body)['results']? Commented Jul 2, 2020 at 20:37
  • I was thinking that you could return the value in print (_sucess (snapshot.data [0])); Commented Jul 2, 2020 at 20:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I change this and change the return too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.