如何从列表的未来中获取元素/值

时间:2019-03-07 06:29:27

标签: sqlite dart flutter

我将SQLite用于缓存。一切都很好。但是我不知道如何从这个承诺中体现价值? (display()返回Future<List<Token>>

我想要的东西就像var value = display().refreshToken

打印语句打印列表值

print(await display());

Database.dart

  // Open the database and store the reference
import 'dart:async';

import 'package:path/path.dart';
import 'package:reborn_next_job02/models/Token.dart';
import 'package:sqflite/sqflite.dart';

databaseToken(
    String tokenModel, String refreshTokenModel, String method) async {
  final database = openDatabase(
    join(await getDatabasesPath(), 'tokenDB.db'),
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE tokenTable(id INTEGER PRIMARY KEY, token TEXT, refreshToken TEXT)",
      );
    },
    version: 1,
  );

  Future<void> insert(Token token) async {
    final Database db = await database;
    await db.insert(
      'tokenTable',
      token.toMap(),
      //same use insert multiple times using ConfiictAlgorithm
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<List<Token>> display() async {
    final Database db = await database;
    final List<Map<String, dynamic>> maps = await db.query('tokenTable');

    return List.generate(maps.length, (i) {
      return Token(
        id: maps[i]['id'],
        token: maps[i]['token'],
        refreshToken: maps[i]['refreshToken'],
      );
    });
  }

  Future<void> update(Token token) async {
    final db = await database;

    await db.update(
      'tokenTable',
      token.toMap(),
      where: "id = ?",
      whereArgs: [token.id],
    );
  }

  Future<void> delete(int id) async {
    final db = await database;

    await db.delete(
      'tokenTable',
      where: "id = ?",
      whereArgs: [id],
    );
  }


  if (method == "insert") {
    var token = Token(
      id: 1,
      token: tokenModel,
      refreshToken: refreshTokenModel,
    );
    await insert(token);
    print(await display());
  } else if (method == "update") {
    var token = Token(
      id: 1,
      token: tokenModel,
      refreshToken: refreshTokenModel,
    );
    await update(token);
    print(await display());
  }
}

Model.dart

class Token {
  int id;
  String token;
  String refreshToken;

  Token({this.id,this.token, this.refreshToken});

  factory Token.fromJson(Map<String, dynamic> json){
    return Token(
      id: json['id'],
      token:json['token'],
      refreshToken: json['refreshToken']
    );
  }
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'token': token,
      'refreshToken': refreshToken,
    };
  }

  @override
  String toString() {
    return 'Token{id: $id, token: $token, refreshToken: $refreshToken}';
  }
}

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式获得它 print((await display())?.elementAt(0)?.refreshToken);

display()返回列表的未来,因此您必须先包装(await display()),然后再进行列表操作,例如从列表中获取元素。 list[0]等效于list.elementAt(0),但是list.elementAt(0)?是null安全和超出边界安全的。