Let's use this code snippet as an example. The data model is very simple:
class Dog {
final int id;
final String name;
final int age;
Dog({this.id, this.name, this.age});
}
To update the information, I'm using this function:
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
await updateDog(Dog(id: 0, name: 'Fido', age: 42));
It works really fine and there aren't any problems. Now the question is, how to update only the field age without using name? So basically I want to do something like this
await updateDog(Dog(id: 0, age: 35));
and expect as a result "name: Figo, age: 35". But instead it removes Fido in null. So I get this as a result: "name: null, age: 35".
The example in the documentation looks like this:
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: fido.name,
age: fido.age + 7,
);
await updateDog(fido);
You either approach it with the raw SQL query like in chunhunghan's answer, or
query the Dog with the id, then override the fields, then update.
Why?
Lets look at your update code:
await updateDog(Dog(id: 0, age: 35));
When the update line is called, Dog.toMap() will be called and it will look like you are updating the name to null.
For you to do what you want here is the code:
Future<Dog> getDog(int id) async {
List<Map> result = await database.query(..... whereArgs: [id]);
if (result.length > 0) {
return new Dog.fromMap(result.first);
}
return null;
}
// Now in code
fido = await getDog(id);
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: fido.name,
age: 35, //<--
);
await updateDog(fido);
You can copy paste run full code below
Example code has two records to demo update effect
Solution 1 : You can use rawUpdate
code snippet
int count = await db.rawUpdate('UPDATE dogs SET age = ? WHERE id = ?', [35, 0]);
Solution 2 : You can revise toMap to only return id and age
Future<void> updateDog1(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap1(),
...
Map<String, dynamic> toMap1() {
return {
'id': id,
'age': age,
};
}
fido = Dog(
id: fido.id,
name: "not care",
age: 35,
);
await updateDog1(fido);
output
I/flutter ( 6570): [Dog{id: 0, name: Fido, age: 42}, Dog{id: 1, name: abc, age: 10}]
I/flutter ( 6570): updated: 1
I/flutter ( 6570): [Dog{id: 0, name: Fido, age: 35}, Dog{id: 1, name: abc, age: 10}]
full code solution 1
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
void main() async {
// Avoid errors caused by flutter upgrade.
// Importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'doggie_database.db'),
// When the database is first created, create a table to store dogs.
onCreate: (db, version) {
return db.execute(
"CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
Future<void> insertDog(Dog dog) async {
// Get a reference to the database.
final Database db = await database;
// Insert the Dog into the correct table. Also specify the
// `conflictAlgorithm`. In this case, if the same dog is inserted
// multiple times, it replaces the previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Dog>> dogs() async {
// Get a reference to the database.
final Database db = await database;
// Query the table for all The Dogs.
final List<Map<String, dynamic>> maps = await db.query('dogs');
// Convert the List<Map<String, dynamic> into a List<Dog>.
return List.generate(maps.length, (i) {
return Dog(
id: maps[i]['id'],
name: maps[i]['name'],
age: maps[i]['age'],
);
});
}
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
Future<void> deleteDog(int id) async {
// Get a reference to the database.
final db = await database;
// Remove the Dog from the database.
await db.delete(
'dogs',
// Use a `where` clause to delete a specific dog.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
var fido = Dog(
id: 0,
name: 'Fido',
age: 42,
);
var fido1 = Dog(
id: 1,
name: 'abc',
age: 10,
);
// Insert a dog into the database.
await insertDog(fido);
await insertDog(fido1);
// Print the list of dogs (only Fido for now).
print(await dogs());
/*
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: fido.name,
age: fido.age + 7,
);
await updateDog(fido);
// Print Fido's updated information.
print(await dogs());*/
final Database db = await database;
int count =
await db.rawUpdate('UPDATE dogs SET age = ? WHERE id = ?', [35, 0]);
print('updated: $count');
print(await dogs());
/*// Delete Fido from the database.
await deleteDog(fido.id);
// Print the list of dogs (empty).
print(await dogs());*/
}
class Dog {
final int id;
final String name;
final int age;
Dog({this.id, this.name, this.age});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'age': age,
};
}
// Implement toString to make it easier to see information about
// each dog when using the print statement.
#override
String toString() {
return 'Dog{id: $id, name: $name, age: $age}';
}
}
full code solution 2
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
void main() async {
// Avoid errors caused by flutter upgrade.
// Importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'doggie_database.db'),
// When the database is first created, create a table to store dogs.
onCreate: (db, version) {
return db.execute(
"CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
Future<void> insertDog(Dog dog) async {
// Get a reference to the database.
final Database db = await database;
// Insert the Dog into the correct table. Also specify the
// `conflictAlgorithm`. In this case, if the same dog is inserted
// multiple times, it replaces the previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Dog>> dogs() async {
// Get a reference to the database.
final Database db = await database;
// Query the table for all The Dogs.
final List<Map<String, dynamic>> maps = await db.query('dogs');
// Convert the List<Map<String, dynamic> into a List<Dog>.
return List.generate(maps.length, (i) {
return Dog(
id: maps[i]['id'],
name: maps[i]['name'],
age: maps[i]['age'],
);
});
}
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
Future<void> updateDog1(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap1(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
Future<void> deleteDog(int id) async {
// Get a reference to the database.
final db = await database;
// Remove the Dog from the database.
await db.delete(
'dogs',
// Use a `where` clause to delete a specific dog.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
var fido = Dog(
id: 0,
name: 'Fido',
age: 42,
);
var fido1 = Dog(
id: 1,
name: 'abc',
age: 10,
);
// Insert a dog into the database.
await insertDog(fido);
await insertDog(fido1);
// Print the list of dogs (only Fido for now).
print(await dogs());
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: "not care",
age: 35,
);
await updateDog1(fido);
// Print Fido's updated information.
print(await dogs());
/*final Database db = await database;
int count =
await db.rawUpdate('UPDATE dogs SET age = ? WHERE id = ?', [35, 0]);
print('updated: $count');
print(await dogs());*/
/*// Delete Fido from the database.
await deleteDog(fido.id);
// Print the list of dogs (empty).
print(await dogs());*/
}
class Dog {
final int id;
final String name;
final int age;
Dog({this.id, this.name, this.age});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'age': age,
};
}
Map<String, dynamic> toMap1() {
return {
'id': id,
'age': age,
};
}
// Implement toString to make it easier to see information about
// each dog when using the print statement.
#override
String toString() {
return 'Dog{id: $id, name: $name, age: $age}';
}
}
Related
I am developing a Flutter app with Firebase Database. This is a chat app. The database structure I need is as the following.
So, I first create a chat room and then add its members. Here please consider the key 900 as a key in chat_room (i know its not in this example), acting as the foreign key in members node. According to the current structure, I can add any number of members to a chat room and I can easily find them without downloading lot of data. This is achievable by the following code.
fire_database_service.dart
import 'package:firebase_database/firebase_database.dart';
class FireDatabaseService
{
final DatabaseReference _chatRoomReference = FirebaseDatabase.instance.reference().child('chat_room');
//Create chat_room
Future<String> createChatRoom({String lastMessage, String chatMode}) async {
var newChatRoomRef = _chatRoomReference.push();
var newChatRoomKey = newChatRoomRef.key;
await newChatRoomRef.set({
'last_message': lastMessage,
'chat_mode': chatMode,
'timestamp': DateTime.now().millisecondsSinceEpoch,
});
return newChatRoomKey;
}
Future<void> addChatMembers(List<ChatMember> chatMembers, String chatRoomID) async
{
for(int i=0; i<chatMembers.length; i++)
{
ChatMember chatMemeber = chatMembers[i];
var newChatMemberReference = FirebaseDatabase.instance.reference().child('members/$chatRoomID/').push();
var newChatMemberKey = newChatMemberReference.key;
await newChatMemberReference.set({
'email': chatMemeber.email,
'userID': chatMemeber.userID,
'user_role': chatMemeber.userRole,
});
}
return null;
}
}
chat.dart
void initState() {
super.initState();
FireDatabaseService firebaseDatabase = FireDatabaseService();
String chatRoomID="";
firebaseDatabase.createChatRoom(
lastMessage: "Test",
chatMode: "Supplier").then((value) async{
print("CHAT ID: "+value);
ChatMember member1 = new ChatMember(
email: "someone#test.com",
userRole: "customer",
userID: 30
);
ChatMember member2 = new ChatMember(
email: "anotherone#test.com",
userRole: "supplier",
userID: 50
);
List<ChatMember> chatMemberList = [member1, member2];
print("BEFORE");
await firebaseDatabase.addChatMembers(chatMemberList, "900");
print("AFTER");
});
}
Please note that in this line await firebaseDatabase.addChatMembers(chatMemberList, "900"); I am hardcoding the value 900. Instead of this, if I pass the unique key of the chat room node, I get this structure, which is completely incorrect of what i need.
I actually need this unique key of chat room to be in members node, so it will act as the foreign key in members node.
Why is this happening and how can I fix this?
I fixed this issue. It was because the chatRoomID is not getting the unique key, it was empty. I fixed it in the following way.
void initState() {
super.initState();
FireDatabaseService firebaseDatabase = FireDatabaseService();
firebaseDatabase
.createChatRoom(lastMessage: "Test", chatMode: "Supplier")
.then((value) async {
print("CHAT ID: " + value);
ChatMember member1 = new ChatMember(
email: "someone#test.com",
userRole: "customer",
userID: 30,
profilePic: "");
ChatMember member2 = new ChatMember(
email: "anotherone#test.com", userRole: "supplier", userID: 50);
List<ChatMember> chatMemberList = [member1, member2];
print("BEFORE");
await firebaseDatabase.addChatMembers(chatMemberList, value);
print("AFTER");
});
}
I've already read the related article and solution + mentioned method, but still I don't get it what should I add to my code for importing csv to sqlite table List<<Map<String, dynamic>. I need to replace existing table with a new one and insert each lines of converted csv. How can I solve it? Here's my code below.The problem is importVoca() of db.dart.
db.dart
class DBHelper {
var _db;
// create database
Future<Database> get database async {
if (_db != null) return _db;
_db = openDatabase(
join(await getDatabasesPath(), 'vocas.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE vocas(id TEXT PRIMARY KEY, word TEXT, meaning TEXT, createTime TEXT)",
);
},
version: 1,
);
return _db;
}
// insert voca
Future<void> insertVoca(Voca voca) async {
final db = await database;
await db.insert('vocas', voca.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace);
}
// Voca list
Future<List<Voca>> vocas() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('vocas');
return List.generate(maps.length, (i) {
return Voca(
id: maps[i]['id'],
word: maps[i]['word'],
meaning: maps[i]['meaning'],
createTime: maps[i]['createTime']);
});
}
//update voca list
Future<void> updateVoca(Voca voca) async {
final db = await database;
await db.update(
'vocas',
voca.toMap(),
where: "id = ?",
whereArgs: [voca.id],
);
}
//delete voca
Future<void> deleteVoca(String id) async {
final db = await database;
await db.delete(
'vocas',
where: "id = ?",
whereArgs: [id],
);
}
//find voca to edit
Future<List<Voca>> findVoca(String id) async {
final db = await database;
final List<Map<String, dynamic>> maps =
await db.query('vocas', where: 'id = ?', whereArgs: [id]);
return List.generate(maps.length, (i) {
return Voca(
id: maps[i]['id'],
word: maps[i]['word'],
meaning: maps[i]['meaning'],
createTime: maps[i]['createTime'],
);
});
}
//export voca to csv
Future exportVoca() async {
var year = DateFormat('yy').format(DateTime.now());
var month = DateFormat('MM').format(DateTime.now());
var day = DateFormat('d').format(DateTime.now());
final db = await database;
var result = await db.query('vocas');
var csv = mapListToCsv(result);
final directory = await getApplicationDocumentsDirectory();
final pathOfFile = await directory.path;
File file = File("$pathOfFile/dontForget_$year$month$day.csv");
file.writeAsString(csv);
}
//import csv to sqlite
Future importVoca() async {
File file = await FilePicker.getFile(
type: FileType.custom, allowedExtensions: ['csv']);
final data = file.openRead();
final fields = await data
.transform(utf8.decoder)
.transform(new CsvToListConverter())
.toList();
Database _db = await openDatabase(
join(await getDatabasesPath(), 'vocas.db'),
version: 1, onCreate: (Database db, int version) async {
await db.execute("DROP TABLE IF EXISTS vocas");
await db.execute(
"CREATE TABLE vocas(id TEXT PRIMARY KEY, word TEXT, meaning TEXT, createTime TEXT)");
});
}
}
I have a file named database_services.dart. This file have a class with various methods. The first method open the database and store the reference, while the other methods make inclusions, updates and deletes on this database. The problem is that the other methods are unable to see the database created by the first method. What am I missing?
Here is the code:
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'counter.dart';
class DatabaseServices {
initDatabase() async {
// Open the database and store the reference.
final Future<Database> database = openDatabase(
// Set the path to the database.
join(await getDatabasesPath(), 'counter_database.db'),
// When the database is first created, create a table to store counters;
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
"CREATE TABLE counters(id INTEGER PRIMARY KEY, name TEXT, value INTEGER)",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
}
// Define a function that inserts counters into the database.
Future<void> insertCounter(Counter counter) async {
// Get a reference to the database.
final Database db = await database;
// Insert the Counter into the correct table. Here, if a counter is inserted twice,
// it replace any previous data.
await db.insert(
'counters',
counter.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
}
// A method that retrieves all the counters from the counters table.
Future<List<Counter>> counters() async {
// Get a reference to the database.
final Database db = await database;
// Query the table for all the Counters.
final List<Map<String, dynamic>> maps = await db.query('counters');
// Counvert the List<Map<String, dynamic>> into a List<Counter>
return List.generate(maps.length, (i) {
return Counter(
id: maps[i]['id'],
name: maps[i]['name'],
value: maps[i]['value'],
);
});
}
// Method to update a Counter in the database
Future<void> updateCounter(Counter counter) async {
final db = await database;
await db.update(
'counters',
counter.toMap(),
where: "id = ?",
whereArgs: [counter.id],
);
}
//Delete a Counter from the database
Future<void> deleteCounter(int id) async {
final db = await database;
await db.delete(
'counters',
where: "id = ?",
whereArgs: [id],
);
}
}
The database variable is only stored in the initDatabase method instead of on the DatabaseServices class, which means that it will only be accessible from the initDatabase method.
The code sample below shows how you could store the database as a property on the DatabaseServices class, which would allow it to be used by all the methods inside that class.
class DatabaseServices {
Future<Database> _db;
Future<void> initDatabase() async {
// Open the database and store the reference.
_db = openDatabase(
// Set the path to the database.
join(await getDatabasesPath(), 'counter_database.db'),
// When the database is first created, create a table to store counters;
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
"CREATE TABLE counters(id INTEGER PRIMARY KEY, name TEXT, value INTEGER)",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
}
// Define a function that inserts counters into the database.
Future<void> insertCounter(Counter counter) async {
// Get a reference to the database.
final db = await _db;
// Insert the Counter into the correct table. Here, if a counter is inserted twice,
// it replace any previous data.
await db.insert(
'counters',
counter.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// A method that retrieves all the counters from the counters table.
Future<List<Counter>> counters() async {
// Get a reference to the database.
final db = await _db;
// Query the table for all the Counters.
final List<Map<String, dynamic>> maps = await db.query('counters');
// Counvert the List<Map<String, dynamic>> into a List<Counter>
return List.generate(maps.length, (i) {
return Counter(
id: maps[i]['id'],
name: maps[i]['name'],
value: maps[i]['value'],
);
});
}
// Method to update a Counter in the database
Future<void> updateCounter(Counter counter) async {
final db = await _db;
await db.update(
'counters',
counter.toMap(),
where: "id = ?",
whereArgs: [counter.id],
);
}
//Delete a Counter from the database
Future<void> deleteCounter(int id) async {
final db = await _db;
await db.delete(
'counters',
where: "id = ?",
whereArgs: [id],
);
}
}
You can find more information about opening a database here.
I've followed this easy example from the flutter documentation. However, this is wrote in a separate file (db_test.db). I'm aiming to convert data into a ListView at some point. So, how would I use CRUD operations like retrieving data in my main.dart? I could add this to my main.dart file but I'd like to keep it clean and separate.
Official Flutter tutorial
My db.dart file
void main () async {
final database = openDatabase(
join(await getDatabasesPath(), 'to_do.db'),
onCreate: (db, version) {
return db.execute("CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT, created TEXT, INTEGER is_complete)");
},
version: 1,
);
Future<void> insertTask (Task task) async {
final Database db = await database;
await db.insert(
'tasks',
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}
Future<List<Task>> tasks () async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('tasks');
return List.generate(maps.length, (i) {
return Task(
id: maps[i]['id'],
title: maps[i]['title'],
created: maps[i]['created'],
isComplete: maps[i]['is_complete']
);
});
}
Future<void> updateTask(Task task) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'tasks',
task.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [task.id],
);
}
Future<void> deleteTask(int id) async {
// Get a reference to the database.
final db = await database;
// Remove the Dog from the database.
await db.delete(
'tasks',
// Use a `where` clause to delete a specific dog.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
}
You can create a new file containing Class with static members to help. Static members ensure that only one instance of database is created in your whole app.
class DatabaseHelper {
static Database _database;
///Returns db instance if already opened
///else call the initDatabase
static Future<Database> getDBConnector() async {
if (_database != null) {
return _database;
}
return await _initDatabase();
}
///Open DB Connection, returns a Database instance.
///
static Future<Database> _initDatabase() async {
_database = await openDatabase(
join(await getDatabasesPath(), "my_path.db"),
onCreate: (db, version) async {
//on create
},
version: 1,
);
return _database;
}
//put your CRUD in static function
static Future<void> insertTask (Task task) async {
final Database db = await getDBConnector();
await db.insert(
'tasks',
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}
//the same with edit, delete
}
Then in your other file (like main.dart) you can just call it like this:
import "./databaseHelper.dart";
void caller() async{
//create task
//insert
await DatabaseHelper.insertTask(task);
}
Make sure the caller is asynchronous.
I used SQLite for the cache. Everything is working well. But I don't know how to display value from this promise? (display() returns Future<List<Token>>)
What I want is properly something like var value = display().refreshToken
print statement printing List values
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}';
}
}
You can get it with
print((await display())?.elementAt(0)?.refreshToken);
display() returns a future of list, so you have to wrap (await display()) before doing list manipulation, such as get an element from a list. list[0] is equivalent to list.elementAt(0), but list.elementAt(0)? is null-safe and out-of-bound-safe.