【问题标题】:Using an async constructor in Flutter在 Flutter 中使用异步构造函数
【发布时间】:2020-06-07 20:02:42
【问题描述】:

我想在工厂构造函数中解析一些东西,但一个属性将由未来给出。不幸的是,Flutter 告诉我不允许向工厂构造函数添加等待/异步。有什么好办法解决这个问题吗?

非常感谢您的帮助!

这是我的代码:

class ClothDetails{

  final int clothId;
  final String title;
  final String image_path;
  bool pressed;

  ClothDetails(
      {this.clothId, this.title, this.image_path, this.pressed}
      );

  factory ClothDetails.fromJson(Map<String, dynamic> aJson) {

    return ClothDetails(
        clothId: int.parse(aJson['id']),
        title: aJson['title'],
        image_path: aJson['image_path'],
        pressed: isPressed(int.parse(aJson['id'])),
    );
  }

Future<bool> isPressed(int curId) async {
    bool help;
    final DatabaseHelper dbHelper = DatabaseHelper.instance;
    List<Map<String, dynamic>> a = await dbHelper.queryRowsById(curId);
        if(a.isEmpty){
          help =false;
        }else{
          help= true;
        }
    return help;
  }
}

【问题讨论】:

  • Constructor({}){}你试过这个吗?

标签: flutter async-await factory


【解决方案1】:

你不能这样做

因为承包商只传递了你的类的一个实例ClothDetails

您无法返回 Future&lt;ClothDetails&gt;,因为它不受支持

但是你可以在你的类中创建一个方法Future

我希望你明白了

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 2018-09-16
    • 2012-08-05
    • 2017-04-14
    • 2013-12-27
    • 2014-10-28
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多