[英]how to load Json to flutter listview
I'm new to flutter and I'm developing a flutter app where I have to show in a listView the data on the database.我是颤振的新手,我正在开发一个颤振应用程序,我必须在列表中显示数据库中的数据。
I get the data in JSON format.我以 JSON 格式获取数据。
{
"data": [
{
"id": “1”,
"testo": "Fare la spesa",
"stato": "1"
},
{
"id": “2”,
"testo": "Portare fuori il cane",
"stato": "1"
},
{
"id": “3”,
"testo": “jhon”,
"stato": "0"
}
]
}
The problem is that I don't load the data, I can't understand how to do it.问题是我没有加载数据,我不明白该怎么做。
I should read 'Data' with an array but I don't know how to do it.我应该用数组读取“数据”,但我不知道该怎么做。
Can anyone help me figure out how to do it?谁能帮我弄清楚如何做到这一点?
Thanks for your help.谢谢你的帮助。
PS.附注。 I tried this tutorial我试过这个教程
Main.dart Main.dart
Future<Post> fetchPost() async {
final response =
await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int id;
final String title;
final String body;
Post({ this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['testo'],
body: json['stato'],
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
I'd rather return List of Post from fetchPost(), like below :我宁愿从 fetchPost() 返回 Post 列表,如下所示:
Future<List<Post>> fetchPost() async {
final response = await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
List responseList = json.decode(response.body);
return responseList.map((data)=>Post.fromJson(data)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
and use ListView.builder instead like this并像这样使用ListView.builder
List<Post> post;
child: ListView.builder(
itemCount: post.length,
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(0),
itemBuilder: (context, index){
return ListAdapter(
id: post[index].id,
title: post[index].title,
body: post[index].body
);
},
)
This code can help you understand how to implement this functionality. 此代码可以帮助您了解如何实现此功能。
import 'dart:convert';
import 'json_objects.dart';
main(List<String> args) {
var json = jsonDecode(_source) as Map<String, dynamic>;
var post = Post.fromJson(json);
for (final element in post.data) {
print(element.id);
print(element.title);
}
}
final _source = '''
{
"data": [
{
"id": "1",
"testo": "Fare la spesa",
"stato": "1"
},
{
"id": "2",
"testo": "Portare fuori il cane",
"stato": "1"
},
{
"id": "3",
"testo": "jhon",
"stato": "0"
}
]
}''';
Result: 结果:
1 Fare la spesa 2 Portare fuori il cane 3 jhon
Used JSON data models (generated by the tool) 使用的JSON数据模型(由工具生成)
class Data {
final String body;
final String id;
final String title;
Data({this.body, this.id, this.title});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
body: json['stato'] as String,
id: json['id'] as String,
title: json['testo'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'stato': body,
'id': id,
'testo': title,
};
}
}
class Post {
final List<Data> data;
Post({this.data});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
data: _toObjectList(json['data'], (e) => Data.fromJson(e)),
);
}
Map<String, dynamic> toJson() {
return {
'data': _fromList(data, (e) => e.toJson()),
};
}
}
List _fromList(data, Function(dynamic) toJson) {
if (data == null) {
return null;
}
var result = [];
for (var element in data) {
var value;
if (element != null) {
value = toJson(element);
}
result.add(value);
}
return result;
}
List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
if (data == null) {
return null;
}
var result = <T>[];
for (var element in data) {
T value;
if (element != null) {
value = fromJson(element as Map<String, dynamic>);
}
result.add(value);
}
return result;
}
/*
Post:
data: List<Data>
Data:
id: String
title.testo: String
body.stato: String
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.