首页 > 解决方案 > 在我计划调用它之前调用 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');
}

标签: firebaseflutterdartgoogle-cloud-firestoreasync-await

解决方案


在查看了代码并进行了一些调整/考虑@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;
  }

这是我用作解决方案的代码。


推荐阅读