颤振不返回价值

时间:2020-07-02 19:59:56

标签: flutter

我正在尝试在Flutter上获取数据,但是我的应用显示错误:

The getter 'length' was called on null. Receiver: null Tried calling: length.

如果我在result.statusCode中插入日志,则我的值将返回到控制台。

我试图查阅其他项目和文档,但是没有任何效果。我需要将数据应用于标签甚至文本并返回,但这是我的主要问题。

我的代码:


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
        }
    ]
} ```

1 个答案:

答案 0 :(得分:1)

if (snapshot.hasData)返回false时,您仍在.length上调用snapshot.data,这就是收到错误的原因。

...
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){
...

以其他方式设置itemCount,例如使用常量itemCount: 1或不为null的变量。