【发布时间】:2021-12-20 11:52:23
【问题描述】:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Datafromapi extends StatefulWidget {
const Datafromapi({Key? key}) : super(key: key);
@override
_DatafromapiState createState() => _DatafromapiState();
}
class _DatafromapiState extends State<Datafromapi> {
Future<List<User>> getUserData() async {
var data = await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
var jsonData = jsonDecode(data.body); //the body here means the string of this
//variable call response
List<User> users = []; //the User here means the class model we create and
//the list here is because later json is going to put the string here
for (var u in jsonData) {
User user = User(u['name'], u['email'], u['username']);
users.add(user);
}
print(users.length);
return users;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('json getting data'),
),
body: Container(
child: FutureBuilder(
future: getUserData(),
builder:(BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(child: Center(
child: Text('loading....')
));
} else {
return ListView.builder(itemCount: snapshot.data.length
,itemBuilder: (BuildContext context, index) {
return ListTile(
title: Text(snapshot.data[index].name),
);
});
}
}),),);
}
}
class User {
final int id;
final String name;
final String username;
User(this.id,this.name,this.username);
} //the class model
这是我的代码 基本上我想构建一个从 HTTP 获取数据然后在列表视图中打印但 json 没有运行的应用程序我不知道为什么它不能获取数据 谁能帮忙
我已经尝试了几个代码,但它无法工作。我想也许是 getuserdata 有问题任何人都可以帮助我
【问题讨论】:
-
你有什么错误吗?请更新您的问题并添加您遇到的
jsonData值或错误。 -
你检查
data.statusCode是200了吗?