首页 > 解决方案 > Flutter api使用

问题描述

我对这个行业很陌生,不能使用 api。无论我看多少培训内容,当我尝试自己尝试时都会遇到错误。我无法摆脱这个恶性循环。我将示例代码片段留在下面。请向我解释我应该如何看待这个行业。谢谢

用户模型


class User{
  String userId;
  int id;
  String title;
  String body;

  User({this.userId,this.id,this.title,this.body});

  factory User.fromJson(Map<String, dynamic> parsedJson){
    return User(
      userId: parsedJson["userId"],
      id: parsedJson["id"],
      title: parsedJson["title"],
      body: parsedJson["body"]
    );
  }
} 

用户服务


Future getUser() async{
  var response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));
  final jsonDecode = json.decode(response.body);
  var user = User.fromJson(jsonDecode);
  return user;
  
}

主屏幕

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  User user = User();
  @override
  void initState() {
    super.initState();
    getUser().then((value) {
      setState(() {
        user = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: user == null
            ? CircularProgressIndicator()
            : Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("${user?.id}"),
                    Text("${user?.title}"),
                    Text("${user?.userId}"),
                    Text("${user?.body}"),
                  ],
                ),
            ),
      ),
    );
  }
}

看起来像这样

我在哪里犯错?感谢您的解释性回答。

标签: jsonapiflutter

解决方案


我试过你的代码,它抛出了这个异常:

 Unhandled Exception: type 'int' is not a subtype of type 'String?'

在课堂上的这一行User

String userId;

userId在 json 文件中是一个 int,而不是一个字符串。

将该行更改为:

int userId;

它应该工作。


推荐阅读