在颤振中对空异常调用了 getter 'length'

时间:2021-02-26 07:29:15

标签: android flutter dart exception

我编译了我的代码,并收到了这个错误。我的联系人不是空的(正如您在图片中看到的),它仍然给我一个被称为 null 的错误。

还有一点很重要。正如您在我的用户界面中看到的,我的联系人的长度或数量,即 3 正在显示,尽管有例外,并且没有显示“联系人”一词。有人也可以给我解释一下吗?? (参考代码的第 38 行,我在“接触次数/长度”后面写了“接触”这个词)。

用户界面 -

The UI of given Code

这是代码-

import 'package:flutter/material.dart';
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter_whatsapp/Widgets/new_contact_card.dart';
import 'package:flutter_whatsapp/Widgets/specific_card.dart';

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {

  Iterable<Contact> _contacts;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getContacts();
  }

  Future<void> getContacts() async {
    final Iterable<Contact> contacts = await ContactsService.getContacts();
    setState(() {
      _contacts=contacts;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Select contact'),
            Text(
              _contacts.isNotEmpty ? '${_contacts.length} contacts' : 'No Contacts yet',
              style: TextStyle(
                fontSize: 10.0,
              ),
            )
          ],
        ),
        actions: [
          IconButton(
            icon: Icon(
              Icons.search,
            ),
            onPressed: (){},
          ),
          PopupMenuButton<String>(onSelected: (value) {
            print(value);
          }, itemBuilder: (BuildContext context) {
            return [
              PopupMenuItem(
                child: Text("Invite a friend"),
                value: "Invite a friend",
              ),
              PopupMenuItem(
                child: Text("Contacts"),
                value: "Contacts",
              ),
              PopupMenuItem(
                child: Text("Refresh"),
                value: "Refresh",
              ),
              PopupMenuItem(
                child: Text("Help"),
                value: "Help",
              ),
            ];
          }),
        ],
      ),
      body: _contacts != null
          ? ListView.builder(
        itemCount: _contacts.length ?? 0,
        itemBuilder: (BuildContext context, int index) {
          Contact contact = _contacts?.elementAt(index);
          if (index == 0 ) {
            return Column(
              children: [
                SpecificCard(
                  iconData: Icons.group,
                  name: "New Group",
                ),
                SpecificCard(
                  iconData: Icons.person_add,
                  name: "New Contact",
                ),
                NewContactCard(uint8list: contact.avatar, text: contact.initials(), color: Theme.of(context).accentColor, name: contact.displayName),
              ],
            );
          }
          return NewContactCard(uint8list: contact.avatar, text: contact.initials(), color: Theme.of(context).accentColor, name: contact.displayName);
        },
      ) : Center(child: CircularProgressIndicator(),),
    );
  }
}

这是错误/异常 -

The following NoSuchMethodError was thrown building ContactsPage(dirty, state: _ContactsPageState#c06d4):
The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was: 
  ContactsPage file:///C:/Users/Hp/AndroidStudioProjects/flutter_whatsapp/lib/Pages/chat_page.dart:74:75
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _ContactsPageState.build (package:flutter_whatsapp/Pages/contacts_page.dart:38:28)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
...
====================================================================================================

2 个答案:

答案 0 :(得分:2)

_contactsasync 方式加载/初始化,简单地说,当第一次绘制/初始化 UI 时,它不会立即初始化。

要修复它,只需使用空列表预设即可。

Iterable<Contact> _contacts=new List<Contact>();

用非空值初始化状态字段总是一个好主意(除非空值指定了某个状态)

答案 1 :(得分:1)

您应该使用 FutureBuilder 来调用 getContacts()