我是flutter的新手,我正在开发flutter应用程序,必须在列表中显示查看数据库中的数据。
我以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"
}
]
}
问题是我没有加载数据,我不知道该怎么做。
我应该使用数组读取“数据”,但我不知道该怎么做。
有人可以帮我弄清楚怎么做吗?
感谢您的帮助。
PS。我尝试了this教程
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();
},
),
),
),
);
}
}
答案 0 :(得分:0)
此代码可以帮助您了解如何实现此功能。
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"
}
]
}''';
结果:
1 Fare la spesa 2 Portare fuori il cane 3 jhon
使用的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
*/
答案 1 :(得分:0)
我宁愿从fetchPost()返回帖子列表,如下所示:
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');
}
}
并使用 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
);
},
)