【问题标题】:The method 'getString' was called on null inFlutter在 Flutter 中,方法 'getString' 在 null 上被调用
【发布时间】:2020-08-01 04:33:18
【问题描述】:

我在 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")

有人知道我为什么会出现这个错误吗?

【问题讨论】:

  • 这个sharedPreferences是从哪里来的(在password_screen中)?
  • SharedPreferences sharedPreferences; 我在 passwrd_screen 中创建了这个
  • 但是你没有在任何地方初始化它。初始化SharedPreferences sharedPreferences = SharedPreferences.getInstance();

标签: rest api flutter dart


【解决方案1】:

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();
  }

注意:我直接在文本编辑器中编写了代码。您可能需要稍微修改一下。

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2020-06-12
    • 2020-06-07
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多