首页 > 解决方案 > 在 null inFlutter 上调用了方法“getString”

问题描述

我在 Flutter 中创建多屏幕表单。从第一个屏幕我SharedPreferences以这种方式保存表单中的数据:

我的basic_screen.dart

  saveData() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString('firstNameForm', firstNameController.text);
    sharedPreferences.setString('lastNameForm', lastNameController.text);
    sharedPreferences.setString('emailForm', emailController.text);
  }

我的用户界面:

  Widget _buildFirstName() {
    double width = MediaQuery.of(context).size.width;
    return SizedBox(
      width: 0.8 * width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'IMIĘ',
            style: TextStyle(
                fontSize: 12.0, color: Color.fromRGBO(136, 136, 136, 1)),
          ),
          TextFormField(
            controller: firstNameController,
            style: TextStyle(color: Color.fromRGBO(136, 136, 136, 1)),
            decoration: InputDecoration(
              border: UnderlineInputBorder(borderSide: BorderSide()),
              hintStyle: TextStyle(color: Colors.blue),
            ),
            validator: (String value) {
              if (value.isEmpty) {
                return 'Pole wymagane';
              } else
                return null;
            },
            onSaved: (String value) {
              _firstName = value;
            },
          ),
        ],
      ),
    );
  }

在我的按钮上NEXT我使用:

        onPressed: () {
          if (!_formKey.currentState.validate()) {
            return;
          }
          saveData()
           Navigator.push(context,
              MaterialPageRoute(builder: (context) => PasswordScreen()));
        },

在我的第二个屏幕上,password_screen.dart我创建了一个函数来休息 api 请求:

我的休息 api 请求:

  createUserRequest(String firstName, lastName, email, accountName, password) async{
    Map data = {
      "firstName":firstName,
      "lastName":lastName,
      "email":email,
      "accountName":accountName,
      "password":password
    };

    var jsonResponse;
    var url = 'http://10.0.2.2:80/user/';
    var response = await http.post(url, body:data);

    if(response.statusCode == 200){
      jsonResponse = json.decode(response.body);
      print(jsonResponse);     
    }else{
      throw new Exception("Not send data");
    }
  }

和我的用户界面FutureBuilder

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
        .copyWith(statusBarColor: Colors.transparent));

    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot){
        if(!snapshot.hasData){
          return Scaffold(
            body: CircularProgressIndicator()
          );
        }
      return Scaffold(
      body: SingleChildScrollView(
          child: Form(
              key: _formKey,
              child: Column(children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                        padding: EdgeInsets.only(top: 20.0),
                        child: _headerSection())
                  ],
                ),
                Padding(
                    padding: EdgeInsets.all(40.0),
                    child: Column(
                      children: <Widget>[
                        _buildAccountName(),
                        SizedBox(height: 40.0),
                        _buildPasswordOne(),
                        SizedBox(height: 40.0),
                        _buildPasswordTwo(),
                        SizedBox(height: 40.0),
                        _infoText(),
                        SizedBox(height: 40.0),
                        new Container(
                          child: SizedBox(
                            width: MediaQuery.of(context).size.width,
                            height: 55.0,
                            child: RaisedButton(
                              onPressed: () {
                                if (!_formKey.currentState.validate()) {
                                  return;
                                }
                                createUserRequest(sharedPreferences.getString('firstNameForm'),
                                                  sharedPreferences.getString('lastNameForm'),
                                                  sharedPreferences.getString('emailForm'),
                                                  _accountNameController.text,
                                                  _passwordOneController.text
                                                  );
                              },
                              child: Text("ZAŁÓŻ KONTO",
                                  style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                              shape:
                                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(40.0)),
                              color: Colors.red,
                            )
                          )
                        ),
                        SizedBox(height: 40.0),
                        _helpText(),
                      ],
                    ))
              ]))),
      );
    }
    );
  }

在这一点上我有一个问题,单击RaisedButton我的功能在哪里后,createUserRequest我的控制台向我抛出了这种类型的错误:

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

有谁知道为什么我有这个错误?

标签: restapiflutterdart

解决方案


sharedPreferences没有实例化。那就是问题所在。您必须在调用 createUserRequest 之前对其进行实例化。

编辑 :

您可以尝试以下方法:

createUserRequest(string accountName, string password) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    firstName = sharedPreferences.getString('firstNameForm');
    ....
    ....
    Map data = {
      .....
}

编辑 2:另一种方法 -

定义一个全局变量

SharedPreferences _prefs ;

在 initState() 中添加一个函数

@override
  void initState() {
    sharedPrefs();
}

实例化:

Future<void> sharedPrefs() async {
    _prefs = await SharedPreferences.getInstance();
  }

注意:我直接在文本编辑器中编写了代码。你可能需要稍微改变它。


推荐阅读