firebase - 在我计划调用它之前调用 async
问题描述
我正在为我的代码的当前功能而苦苦挣扎。我正在尝试一次将一组数据上传到我创建的本地 SQL 数据库和 firebase。他们都拥有相同的确切字符串。出于某种原因,当我上传到 Firebase 时,字符串值有值并且上传没有问题。然而,进入数据库的完全相同的字符串作为空值传入。
当我按下提交按钮时,此validateAndSubmit()
方法被调用
void validateAndSubmit() async {
setState(() {
_errorMessage = "";
_isLoading = true;
});
print("Auth: " + widget.auth.getUserId());
if (validateAndSave()) {
try {
String _uid = widget.auth.getUserId();
uploadImage(imageToUpload: _image, title: _uid + "_profile_pic");
final databaseReference = Firestore.instance;
print("name: " + _nameF);
await _save(NewUser(1,_nameF,_nameL,_age, _grad,_highschool,_state,_city,_heightFeet,_heightInch,_weight,_hand,_position,_club,'PL'));
await databaseReference.collection("users").document(_uid).setData({
'nameF': _nameF,
'nameL': _nameL,
'age': _age,
'grade': _grad,
'highschool': _highschool,
'state': _state,
'city': _city,
'heightFeet': _heightFeet,
'heightInch': _heightInch,
'weight': _weight,
'hand': _hand,
'position': _position,
'club': _club,
'type': 'PL',
});
await databaseReference.collection("players").document(_uid).setData({
'Type': "Player",
});
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new HomePage(
userId: _uid, auth: widget.auth, logoutCallback: null,)),
);
}
catch (e) {
print(e.message);
}
}
setState(() {
_isLoading = false;
});
}
当我调用 await 来上传 firebase 时,它会按预期上传。当我打电话给_save
我时,所有字符串的值都是空的。我什至尝试在字符串之前添加一个打印语句,_save
并且字符串的值为空。有什么理由他们会在不同的时间被调用吗?
这是代码_save:
_save(NewUser user) async {
DatabaseHelper helper = DatabaseHelper.instance;
print(user.toString());
int id = await helper.insertUser(user);
print('inserted row: $id');
}
解决方案
在查看了代码并进行了一些调整/考虑@jamesdlin 所说的之后,我注意到数据库初始化是唯一需要异步的部分。然后,我将数据库的 init 语句分离为与插入分开的方法,并将插入更改为原始插入。我用这种方法找到了成功。谢谢!
_save() {
database.rawInsert('INSERT INTO user(name, age) VALUES(?, ?, ?,?, ?, ?, ?, ?,?, ?, ?,? , ?, ?)', [_nameF,_nameL,_age, _grad,_highschool,_state,_city,_heightFeet,_heightInch,_weight,_hand,_position,_club,'PL']);
}
_intiDatabase() async{
database = await DatabaseHelper.instance.database;
}
这是我用作解决方案的代码。
推荐阅读
- c# - Get List of AWS S3 Directory Name from .net core application
- java - Spring Boot 应用程序不会为 JPA @Table 注释创建模式
- opentok - 无法获取 iPhone/iPad 的相机访问权限
- owl - OWL 限制:定义依赖于概念层次结构的类
- razor-pages - 使用 Razor Pages 生成锚标记
- c# - 重命名 Sftp 文件问题
- ios - 由于“内部”保护级别 swift 4,扩展初始化程序不可访问
- azure - 首次加载时显示的 Azure AD B2C 自定义 UI 错误标签
- java - 意外的排序列表
- macos - 应用程序在 MacOS 中终止后在后台运行定期任务