Search code examples
flutteradditionsqflite

How to fetch single record from SQLite in flutter and store in model class for use


I am not good in flutter but learning it . I am working with SQLite and want to fetch single record and want to map it to model class then want to show it in text widget.

Need help and thanks in advance.

Regards


Solution

  • Future<User> fetchUser(String email) async {
        final db = await instance.database;
    
        final map = await db.rawQuery(
          "SELECT * FROM $tableName WHERE email = ?",[email]
        );
    
        if (map.isNotEmpty) {
          return User.fromJson(map.first);
        } else {
          throw Exception("User: $email not found");
        }
      }
    

    To use it in a Text widget:

      //Create a variable of your model class
      User? user;
      
      //call this method in init to fetch user by email
      void getUser()async{
        
        //call your Database fetch method
        user = await database.instance.fetchUser("[email protected]");
      }
      
      //Use it like this in a Text Widget
      Text("${user.email}" ?? "NA"),