Я создаю многоэкранную форму во флаттере. С первого экрана я сохраняю свои данные из форм с помощью SharedPreferences
следующим образом:
my 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);
}
my ui:
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")
Кто-нибудь знает, почему у меня есть эта ошибка?