标签:create item home 序列化 title bsp string code 习题
lib文件夹分了三个文件
getdiodata.dart
model.dart
main.dart
注意点:Dio().get()返回的数据是List或者Map,http().get()返回的数据是json数据;Dio().get()比http更方便的地方就是返回的数据是List或者Map,而http().get()返回的数据是json数据需要用jsonDecode()来解码成为List或者Map数据;
main.dart:
import ‘package:flutter/material.dart‘;
import ‘getdiodata.dart‘;
import ‘model.dart‘;
void main()=>runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘‘),),
body: FutureBuilder(
future: GetDio().getData(),
builder: (context,snapshot){
print(snapshot.data);
if(!snapshot.hasData){
return Center(child: CircularProgressIndicator(),);
}else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder:(context,index){
return ListTile(
title: Text(‘${snapshot.data[index][‘title‘]}‘),
subtitle: Text(‘${snapshot.data[index][‘body‘]}‘),
);
},);
}
}),
);
}
}
model.dart
class PostModel{
//下面两个数据要根据实际的Json数据填写;
final int userId;
final int id;
final String title;
final String body;
PostModel(
this.userId,
this.id,
this.title,
this.body,
);
//PostModel.fromJson(Map json)输入的参数是一个Map类型Map json;输出的是PostModel类型数据;
PostModel.fromJson(Map json)
:userId = json[‘userId‘],
id = json[‘id‘],
title = json[‘title‘],
body = json[‘body‘];
// Map toJson()返回的是Map类型数据,是将Post类数据序列化为Json;
Map toJson() => {
‘userId‘:userId,
‘id‘:id,
‘title‘:title,
‘body‘:body,
};
}
getdiodata.dart
import ‘package:dio/dio.dart‘;
class GetDio{
getData()async{
Response response = await Dio().get(‘http://jsonplaceholder.typicode.com/posts‘);
if(response.statusCode == 200){
return response.data;
}
}
}
标签:create item home 序列化 title bsp string code 习题
原文地址:https://www.cnblogs.com/braveheart007/p/10952877.html