sqflite + Flutter : map((e) => .... returns [Instance of Class]

586 Views Asked by At

I am currently using Sqflite with Flutter for a small app being developed.

My model Class for User is as follows:

class User {
  static const tblUser = 'users';
  static const colUserId = 'id';
  static const colUserName = 'name';
  static const colUserMail = 'mail';
  static const colUserPhone = 'phone';

  User({this.id, this.name, this.mail, this.phone});

  int id;
  String name;
  String mail;
  String phone;

  User.fromMap(Map<String, dynamic> map) {
    this.id = map[colUserId];
    this.name = map[colUserName];
    this.mail = map[colUserMail];
    this.phone = map[colUserPhone];
  }

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      colUserName: name,
      colUserMail: mail,
      colUserPhone: phone
    };
    if (id != null) {
      map[colUserId] = id;
    }
    return map;
  }
}

In the database_helper class, I create the database and the tables, which work correctly:

class DatabaseHelper {
  static const _databaseName = 'FinmanDatabase.db';
  static const _databaseVersion = 1;

  DatabaseHelper._();

  static final DatabaseHelper instance = DatabaseHelper._();

  Database _database;

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await _initDatabase();
    return _database;
  }

  _initDatabase() async {
    Directory dbDirectory = await getApplicationDocumentsDirectory();
    String dbpath = join(dbDirectory.path, _databaseName);
    return await openDatabase(dbpath,
        version: _databaseVersion, onCreate: _onCreateDB);
  }

  Future _onCreateDB(Database db, int version) async {
    await db.execute(''' 
    CREATE TABLE ${User.tblUser} (
      ${User.colUserId} INTEGER PRIMARY KEY AUTOINCREMENT,
      ${User.colUserName} TEXT NOT NULL,
      ${User.colUserMail} TEXT NOT NULL,
      ${User.colUserPhone} TEXT NOT NULL
    )
    ''');
  }}

However, when I try to fetch the Users to flutter, the program returns 'Instance of User' instead of the contents. The function to fetch the Users is as follows:

  Future<List<User>> fetchAllUser() async {
    Database db = await database;
    List<Map> userslist = await db.query(User.tblUser);
    int count = userslist.length;
    print('Printing $userslist from DBHelper + Length: $count');
    return userslist.length == 0 ? [] : userslist.map((e) => User.fromMap(e)).toList();
  }

And here is how I am calling this in Flutter:

class _HomeState extends State<Home> {
  User user = User();
  List<User> _users;
  String _dbExists;
  DatabaseHelper _dbhelper;
  int count = 0;

  @override
  void initState() {
    super.initState();
    setState(() {
      _dbhelper = DatabaseHelper.instance;
    });
    _refreshUserList();
  }

  _refreshUserList() async {
    List<User> x = await _dbhelper.fetchAllUser();
    setState(() {
      _users = x;
      print(_users);
      count = _users.length;
      print(count);
      if (count > 0) {
        _dbExists = 'Database exists';
      } else {
        _dbExists = 'Create a new Database';
      }
    });
  }}

While the print(count) returns 1 (which is the number of records in the User Table), print(_users) returns [Instance of User]??

Any help is appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

when I try to fetch the Users to flutter, the program returns 'Instance of User' instead of the contents

Because x is List<User>.

To get the content, you can use for-loop

for(var i in x){
   print(i.name); // it will print out the name
}