标签:sub listt asd 示例 序列化 根据 index enter mod
示例有3个文件:
main.dart
import ‘package:flutter/material.dart‘;
import ‘httpgetdata.dart‘;
import ‘modelpost.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(‘demoModel&Dio‘),),
body: FutureBuilder(
future: GetData().getData(),
builder: (context,snapshot){
if(snapshot.hasData){
var listData = snapshot.data.map((item)=>PostModel.fromJson(item)).toList();
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context,index){
return ListTile(
title: Text(‘${listData[index].title}‘),
subtitle: Text(‘${listData[index].body}‘),
);
},
);
}else{
return Center(child: CircularProgressIndicator(),);
}
},),
);
}
}
httpgetdata.dart
import ‘package:http/http.dart‘ as http;
import ‘package:dio/dio.dart‘;
import ‘dart:convert‘;
class GetData{
String url = ‘http://jsonplaceholder.typicode.com/posts‘;
var backData;
getData()async{
Response response = await Dio().get(url);
if(response.statusCode==200){
return response.data;
}else{
return [‘there is no data get from website‘];
}
}
}
modelpost.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() => {
‘id‘:id,
‘userId‘:userId,
‘title‘:title,
‘body‘:body,
};
}
标签:sub listt asd 示例 序列化 根据 index enter mod
原文地址:https://www.cnblogs.com/braveheart007/p/10961602.html