【问题标题】:Dart receiving 'Instance of' instead of valueDart 接收“实例”而不是值
【发布时间】:2021-11-29 20:24:13
【问题描述】:

试图显示登录的 id,这是我从我的 API 收到的:

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

这就是我得到它的方式:

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));
}

这是用户类:

class User {
  final String id;

  User({
    required this.id,
  });

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

这是我的初始化状态:

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

这是我的小部件生成器。添加以下行修复它: 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(),
            );
          }
        });
  }

只是想在title: Text('Bienvenido ${snapshot.data}'),线上显示ID

但我得到的是 Instance of 'User' 而不是 id...

关于我做错了什么的任何线索?

【问题讨论】:

    标签: json flutter api dart


    【解决方案1】:

    您能否仅将fetchUsers() 作为您的未来构建者的未来。之后,您应该只使用 snapshot.data.id 访问 id。 我也不觉得

    futureUser = fetchUsers();
    

    在 initState 中是必需的,因为它的 Future 函数和 await 关键字在 initState 中不起作用。

    【讨论】:

      【解决方案2】:

      snapshot.data 是整个响应(user 实例)

      如果你想访问id

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

      由于snapshot.dataUser?,使用! 表示它不为空。 (如果snapshot.hasData 为真snapshot.data 不为空)

      试试这个,

      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(),
                       );
                     }
                   },
                 );
        }
      

      【讨论】:

      • 感谢您的回复,如果我将id 添加到该行,它会给我:The getter 'id' isn't defined for the type 'Object'. Try importing the library that defines 'id', correcting the name to the name of an existing getter, or defining a getter or field named 'id'.
      • 您需要定义 Futurebuilder 返回的数据类型,如下所示:FutureBuilder()
      • 谢谢,这已经解决了!
      猜你喜欢
      • 2021-08-21
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2020-02-13
      • 2017-05-30
      相关资源
      最近更新 更多