Home > Net >  How do I print this object to the console so I can access each value on the object by specifying the
How do I print this object to the console so I can access each value on the object by specifying the

Time:05-25

My code looks like this. This is the function that is returning an object of MyUser.

class MyUser{
  final String name;
  String matric;
  final String email;
  final String userType;
  MyUser({
    required this.name, 
    this.matric='', 
    required this.email, 
    required this.userType});

  static Future<Object?> editProfile() async {
    return MyUser(name: 'name', email: 'email', userType: 'userType');
  }
}

And the code receiving it aims to print the received object of MyUser like so:

Future? editProfile() async {
      Object? userRes = await MyUser.editProfile();
      print(await userRes);
      return null;
    }

I want to print the object so I can use the keys to fetch values individually like user['name'] and it should print out name. But all I get is Instance of MyUser. Please help me out here. Thanks.

P.S: I want to know how to print objects like this on an async function.

CodePudding user response:

You should specify the right class, not just Object. then you can do this

static Future<MyUser> editProfile() async {
  return MyUser(name: 'name', email: 'email', userType: 'userType');
}

Future? editProfile() async {
  MyUser userRes = await MyUser.editProfile();
  print(userRes.name);
  return null;
}

CodePudding user response:

You can do like this to check all the fields of your custom data:

  1. Your case
class MyUser{
  String name, email, userType;
  
  MyUser({required this.name, required this.email, required this.userType});

}

void main(){
  MyUser user = MyUser(name: 'test', email: '[email protected]', userType: 'test');
  print(user);
}

And output

Instance of 'MyUser'
  1. New one
class MyUser{
  String name, email, userType;
  
  MyUser({required this.name, required this.email, required this.userType});
  
  @override
  String toString(){
    return 'name:'   name   ', email:'   email   ', userType:'   userType;
  }
}

void main(){
  MyUser user = MyUser(name: 'test', email: '[email protected]', userType: 'test');
  print(user);
}

And output

name:test, email:[email protected], userType:test
  • Related