首页 > 解决方案 > 错误:运行 Flutter 应用程序时,“在 null 上调用了方法 'contains'。接收方:null”

问题描述

在我的颤振应用程序中,我将我的 JSON 数据存储到两个字符串列表(化学名称和化学哈希)中。我正在使用这些字符串列表来检查 TextFormField 中输入的文本是否与 chemnames 字符串列表中的字符串之一匹配。但是,当我调用该.contains()方法时,我在控制台中收到一条错误消息:

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

为了修复此错误,我需要添加什么?

这是我的代码:

import 'dart:ffi';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//import 'package:html/parser.dart'


class chemPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {

    return new chemicalResearchPage();
  }
}

class chemicalResearchPage extends State<chemPage>{
  final searchText = TextEditingController();
  var crText = TextEditingController();
  String chemText;
  bool _value = false;
  List<String> chemnames;
  List<String> chemhashes;
  List<String> chemnamesCleaned;


  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    searchText.dispose();
    super.dispose();
  }


  Future<String> getData(String hash) async{

    var queryParameters = {
      "chemID" :  hash //just one of the hashes (example)
    };

    var uri =
    Uri.https('www.myWebsite.com', '/api/getWebsite', queryParameters);

    Icon searchIcon = Icon(Icons.search);
    var objMapUrl = "https://MyWebsite.com/website";
    Map data;
    Map queryData;
    http.Response response  = await http.get(
        Uri.encodeFull(objMapUrl),
        headers: {

          "key" : "fuiwefuiewfuqwf8uff"
        }
    );

    var queryParams = await http.get(uri, headers: {
      "key" : "fuiwefuiewfuqwf8uff"

    });

    data = json.decode(response.body);
//
//    print(data["hashes"]);
//    print( data["chem names"]);
//    // print(data); //prints hashes

    chemhashes = new List<String>.from(data["hashes"]);
    chemnames =  new List<String>.from(data["chem names"]);

//    for(int i = 0; i < chemnames.length; i++){
//      chemnamesCleaned[i] = chemnames[i].substring(chemnames.lastIndexOf("1"));
//    }

    print(chemhashes[10]);
    print(chemnames);

//
    //query parameters

    queryData = json.decode(queryParams.body);
   // print(queryData);

   // print(chemnamesCleaned[5]);

    chemText = queryData.toString();
    //print(chemText);

    setState(() {
      crText.text = chemText;
    });

    return "Success";

  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      resizeToAvoidBottomPadding: false,

      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        automaticallyImplyLeading: false,
        title: Container(
          margin: EdgeInsets.symmetric(horizontal: 1.0, vertical: 8.0),
          decoration: BoxDecoration(
            color: Colors.lightBlueAccent,
            borderRadius: BorderRadius.all(Radius.circular(12.0)),

          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,

            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.0),
                  child: TextFormField(
                    controller: searchText,
                   // textInputAction: TextInputAction.done,
                    onFieldSubmitted: (term){
                        if(chemnames.contains(searchText.text)){  //check if searchText is something
                          var index = chemnames.indexOf(searchText.text); //finds index of the c hemical name searched
                          getData(chemhashes[index]); //relates the index to find corresponding hash
                        }else{
                         AlertDialog dialog = new AlertDialog(
                           shape: RoundedRectangleBorder(
                               borderRadius: BorderRadius.all(Radius.circular(15.0))),
                           title: Text("Chemical not found", style: TextStyle(fontSize: 20.0),),
                            content: new Container(
                              width: 5.0,
                              height: 5.0,
                            ),
                           actions: <Widget>[
                              new FlatButton(onPressed: (){
                                Navigator.pop(context);
                              }, child: new Text("Ok", style: TextStyle(fontSize: 20.0),))
                           ],

                         );
                         showDialog(context: context, child: dialog);
                        }

                    },
                    cursorColor: Colors.white,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "Enter Chemical Name",
                      hintStyle: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ),
//              Expanded(
//                flex: 0,
//                child: Container(
//                  padding: EdgeInsets.symmetric(horizontal: 0.0),
//                  child: Row(
//                    children: <Widget>[
//                      IconButton(
//                        onPressed: null,
//                        icon: Icon(Icons.search, color: Colors.white),
//                      ),
//                    ],
//                  ),
//                ),
//              ),
            ],
          ),
        ),
      ),

      body: new Container(
        child: SingleChildScrollView(
          padding: new EdgeInsets.fromLTRB(25.0, 30.0, 25.0, 0.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text("Chemical Research", style: TextStyle(fontSize: 20, fontWeight: FontWeight.normal, color: Colors.lightBlue)),
              new TextField(
                decoration: new InputDecoration(
                  border: const OutlineInputBorder(
                    borderSide: const BorderSide(
                      color: Colors.blueGrey, width: 2.0
                    )
                  )
                ),
               //textfield text needs to change to the text recieved from json.decode(queryParams.body) or chemText
               controller: crText,
                maxLines: 20,

              ),
              Expanded(
                flex: 0,
                child: SingleChildScrollView(
                  padding: new EdgeInsets.fromLTRB(0.0, 45.0, 0.0, 0.0),
                  child: Align(
                    alignment: FractionalOffset.bottomCenter,
                    child: Container(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: <Widget>[
                          new RaisedButton(onPressed: () {
                            if (chemnames.contains(searchText.text)){
                              var index = chemnames.indexOf(searchText.text); //finds index of the chemical name searched
                              getData(chemhashes[index]); //relates the index to find corresponding hash
//                              print(chemnamesCleaned[index]);
                            }else{
                              AlertDialog dialog = new AlertDialog(
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(15.0))),
                                title: Text("Chemical not found", style: TextStyle(fontSize: 20.0),),
                                content: new Container(
                                  width: 5.0,
                                  height: 5.0,
                                ),
                                actions: <Widget>[
                                  new FlatButton(onPressed: (){
                                    Navigator.pop(context);
                                  }, child: new Text("Ok", style: TextStyle(fontSize: 20.0),))
                                ],

                              );
                              showDialog(context: context, child: dialog);
                            }
                          },

                            elevation: 2.0,
                            color: Colors.lightBlue,
                            child: Text("Search", style: TextStyle(color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)),
                            shape: RoundedRectangleBorder(
                                borderRadius: new BorderRadius.circular(15)
                            ) ,
                          ),

                        ],
                      ),
                    ),
                  ),
              ),)

            ],
          ),

        ),
      ),


    );
  }

}

.contains()方法的实现在这个代码片段中也可以在上面的onSubmitted.

if(chemnames.contains(searchText.text)){  //check if searchText is something
                          var index = chemnames.indexOf(searchText.text); //finds index of the c hemical name searched
                          getData(chemhashes[index]);

标签: listflutterdart

解决方案


推荐阅读