【问题标题】:The getter 'length' was called on null exception in flutter在颤振中调用了 getter 'length'
【发布时间】:2021-02-26 07:29:15
【问题描述】:

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

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

用户界面 -

这里是代码-

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

【问题讨论】:

    标签: android flutter dart exception


    【解决方案1】:

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

    要修复它,只需用一个空列表预设它。

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

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

    【讨论】:

    • 谢谢兄弟,它起作用了,但没有使用 - new List(); (因为它在新版本的颤振中被贬值了)我们应该简单地使用列表文字,即 [ ],并且一切正常。
    • 好吧 - 我不同意颤振。在这两种情况下效果是相同的 - 没有空引用。我很高兴能帮上忙。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2021-07-21
      • 2020-01-21
      • 2021-08-11
      • 2021-02-23
      • 2021-12-10
      • 2018-12-03
      相关资源
      最近更新 更多