【问题标题】:Future<List> to List with Objects in FlutterFuture<List> 列出 Flutter 中的对象
【发布时间】:2020-11-23 10:50:10
【问题描述】:

我最近开始使用 Flutter。 我的应用程序运行一个 sqflite 数据库,我想从中获取所有数据并将其显示在我的应用程序的行小部件中。

我知道如何获取数据,也知道如何构建小部件。 我很困惑,我不知道如何将从数据库中获取的数据转换为列表(我可以使用它来构建我的小部件)。

所以我得到了未来清单,但我需要清单饮料

看看:

我的对象:

class Drink {
  int id;
  String time;
  int amount;

  Drink({this.id, this.time, this.amount});
}

数据库:

Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnTime TEXT NOT NULL,
            $columnAmount INTEGER NOT NULL
          )
          ''');
  }

我如何获得输出:

Future<List> raw() async {
    Database db = await instance.database;
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM $table");
    List<Map<String, dynamic>> r = result.toList();
    return r;
  }

【问题讨论】:

标签: flutter dart sqflite


【解决方案1】:

model 中创建工厂构造函数

class Drink {
  int id;
  String time;
  int amount;

  Drink({this.id, this.time, this.amount});

  factory Drink.fromJson(Map<String, dynamic> json) {
        return Drink(
            id: json['columnId'],
            time: json['columnTime'], 
            amount: json['columnAmount'], 
        );
    }
}

稍后,您可以像这样将获取的数据库数据映射到Drink

Future<List<Drink>> fetchDrinks() async {
    Database db = await instance.database;
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM $table");
    List<Map<String, dynamic>> r = result.toList().map((data) => Drink.fromJson(data));
    return r;
  }

您可以在fetchDrinks 上使用await 方法来获取您的Drink 对象列表。

我没有测试过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2020-06-01
    • 2019-07-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2021-02-09
    • 2020-04-16
    相关资源
    最近更新 更多