Flutter错误“在null上调用了方法'toLowerCase()'”

时间:2020-01-02 19:25:12

标签: android firebase flutter widget

我正在快速创建Skype克隆应用程序,并且在执行“搜索”功能时遇到错误。我想通过在输入时会更新的列表通过小写返回的用户名或名称搜索我的firebase数据库中的其他用户。但是,在第一次按键时,我遇到此错误:

The method 'toLowerCase' was called on null.
Receiver: null
Tried calling: toLowerCase()

这是搜索屏幕的代码(问题在buildSuggestions下):

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
import 'package:skypeclone1/models/user.dart';
import 'package:skypeclone1/resources/firebase_repository.dart';
import 'package:skypeclone1/utils/universal_variables.dart';
import 'package:skypeclone1/widgets/custom_tile.dart';

class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  FirebaseRepository _repository = FirebaseRepository();

  List<User> userList;
  String query = "";
  TextEditingController searchController = TextEditingController();

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

    _repository.getCurrentUser().then((FirebaseUser user) {
      _repository.fetchAllUsers(user).then((List<User> list) {
        setState(() {
          userList = list;
        });
      });
    });
  }

  searchAppBar(BuildContext context) {
    return GradientAppBar(
      backgroundColorStart: UniversalVariables.gradientColorStart,
      backgroundColorEnd: UniversalVariables.gradientColorEnd,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.white),
        onPressed: () => Navigator.pop(context),
      ),
      elevation: 0,
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(kToolbarHeight + 20),
        child: Padding(
          padding: EdgeInsets.only(left: 20),
          child: TextField(
            controller: searchController,
            onChanged: (val) {
              setState(() {
                query = val;
              });
            },
            cursorColor: UniversalVariables.blackColor,
            autofocus: true,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.white,
              fontSize: 35,
            ),
            decoration: InputDecoration(
              suffixIcon: IconButton(
                icon: Icon(Icons.close, color: Colors.white),
                onPressed: () {
                  WidgetsBinding.instance
                      .addPostFrameCallback((_) => searchController.clear());
                },
              ),
              border: InputBorder.none,
              hintText: "Search",
              hintStyle: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 35,
                color: Color(0x88ffffff),
              ),
            ),
          ),
        ),
      ),
    );
  }

  buildSuggestions(String query) {
    final List<User> suggestionList = query.isEmpty
        ? []
        : userList.where((User user) {
            String _getUsername = user.username.toLowerCase();
            String _query = query.toLowerCase();
            String _getName = user.name.toLowerCase();
            bool matchesUsername = _getUsername.contains(_query);
            bool matchesName = _getName.contains(_query);

            return (matchesUsername || matchesName);


          }).toList();

    return ListView.builder(
      itemCount: suggestionList.length,
      itemBuilder: ((context, index) {
        User searchedUser = User(
            uid: suggestionList[index].uid,
            profilePhoto: suggestionList[index].profilePhoto,
            name: suggestionList[index].name,
            username: suggestionList[index].username);

        return CustomTile(
          mini: false,
          onTap: () {},
          leading: CircleAvatar(
            backgroundImage: NetworkImage(searchedUser.profilePhoto),
            backgroundColor: Colors.grey,
          ),
          title: Text(
            searchedUser.username,
            style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
          subtitle: Text(
            searchedUser.name,
            style: TextStyle(color: UniversalVariables.greyColor),
          ),
        );
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UniversalVariables.blackColor,
      appBar: searchAppBar(context),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: buildSuggestions(query),
      ),
    );
  }
}

如果我从buildSuggestions中省略了toLowerCase()小部件,则会收到类似的错误:

The method 'contains' was called on null.
Receiver: null
Tried calling: contains("h")

* h是我的按键

3 个答案:

答案 0 :(得分:0)

您的构建函数应该类似这样,仅当userList不为空时才运行buildSuggestions。

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UniversalVariables.blackColor,
      appBar: searchAppBar(context),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: userList.isEmpty?Container():buildSuggestions(query),
      ),
    );
  }

答案 1 :(得分:0)

您需要验证输入数据。因为您的某些输入数据可为空,所以会发生错误 您应该检查以下代码:

final List<User> suggestionList = query.isEmpty
        ? []
        : userList.where((User user) {
            String _getUsername = user.username.toLowerCase();
            String _query = query.toLowerCase();
            String _getName = user.name.toLowerCase();
            bool matchesUsername = _getUsername.contains(_query);
            bool matchesName = _getName.contains(_query);

            return (matchesUsername || matchesName);


          }).toList();

或者您可以按以下方式修复:

          userList.where((User user) {
            if (query != null || user.username != null || user.name != null) {
              String _getUsername = user.username.toLowerCase();
              String _query = query.toLowerCase();
              String _getName = user.name.toLowerCase();
              bool matchesUsername = _getUsername.contains(_query);
              bool matchesName = _getName.contains(_query);

            return (matchesUsername || matchesName);
            } else { return false; }

          }).toList()

答案 2 :(得分:0)

嘿上面的代码中的错误 方法'toLowerCase'在null上被调用。

接收者:null尝试调用:toLowerCase()

是由于数据库中的用户数据不规则造成的

要解决此问题,请尝试删除数据库中的用户集合或删除不规则集合并重新登录