Home > OS >  Dart receiving 'Instance of' instead of value
Dart receiving 'Instance of' instead of value

Time:10-11

Trying to show the id logged in, this is what I am receiving from my API:

{ user_id: '10001', iat: 1633915047, exp: 1633922247 }

This is how I am getting it:

Future<User> fetchUsers() async {
  var url = Uri.http('localhost:8000', "/home");
  var prefs = await SharedPreferences.getInstance();
  var token = prefs.getString('token');
  var res = await http.get(url, headers: {'x-access-token': token!});

  return User.fromJson(jsonDecode(res.body));
}

This is the User class:

class User {
  final String id;

  User({
    required this.id,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(id: json['user_id'] as String);
  }
}

This is my initState:

 void initState() {
    super.initState();
    futureUser = fetchUsers();
  }

This is my Widget Builder. Adding the following line fixed it: fetchUsers().then((value) {return value.id;

Widget build(BuildContext context) {
    return FutureBuilder(
        future: fetchUsers()**.then((value) {return value.id;**
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            print(snapshot.error);
            return const Center(
              child: Text('Error'),
            );
          } else if (snapshot.hasData) {
            print(snapshot.data.toString());
            return Scaffold(
              appBar: AppBar(
                title: Text('Bienvenido ${snapshot.data}'),
                backgroundColor: Colors.green[300],
              ),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        });
  }

Just trying to show the ID on line title: Text('Bienvenido ${snapshot.data}'),

But I am getting a Instance of 'User' instead of the id...

Any clue on what I am doing wrong?

CodePudding user response:

snapshot.data is the whole response ( user instance )

If you want to access id,

Text('Bienvenido ${snapshot.data!.id}'),

Since snapshot.data is User?, use ! to indicate it is not null. ( if snapshot.hasData is true snapshot.data is not null )

Try this,

Widget build(BuildContext context) {
    return FutureBuilder<User>(
             future: fetchUsers(),
             builder: (context, snapshot) {
               if (snapshot.hasError) {
                 print(snapshot.error);
                 return const Center(
                   child: Text('Error'),
                 );
               } else if (snapshot.hasData) {
                 print(snapshot.data.toString());
                 return Scaffold(
                   appBar: AppBar(
                     title: Text('Bienvenido ${snapshot.data!.id}'),
                     backgroundColor: Colors.green[300],
                   ),
                 );
               } else {
                 return const Center(
                   child: CircularProgressIndicator(),
                 );
               }
             },
           );
  }

CodePudding user response:

Can you give just fetchUsers() as a future to your futurebuilder. After that you should access to id with just snapshot.data.id. Also I dont think

futureUser = fetchUsers();

is necessary in initState since its Future function and await keyword will not work in initState.

  • Related