rest - 在 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")
有谁知道为什么我有这个错误?
解决方案
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();
}
注意:我直接在文本编辑器中编写了代码。你可能需要稍微改变它。
推荐阅读
- go - 在golang中获取数组的长度并将其存储在const中
- c# - 相机中的 UnassignedReferenceException
- android - 如何将屏幕分成两个区域,同时在中心有一个表格?
- sql - 将日期列添加到 SQL 中的临时表
- python - 如何使用 virtualenv 为 Python 3.7 创建虚拟环境,而无需在我的计算机(Ubuntu 16.04.6 LTS x64)上安装 Python 3.7?
- java - 修改 inputType:number|phone Android Studio
- java - Neo4j 使用密码获取包含微秒或纳秒的系统日期时间
- animation - 散景——如何在将新数据推送到图/图之前清除我的图/图?
- database - 在 django pytest 期间断言没有数据库更新尝试
- laravel - Laravel 路由多个参数