Flutter学习10 - Json解析与Model使用
warning:
这篇文章距离上次修改已过184天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: JsonParsePage(),
);
}
}
class JsonParsePage extends StatefulWidget {
@override
_JsonParsePageState createState() => _JsonParsePageState();
}
class _JsonParsePageState extends State<JsonParsePage> {
List<User> _users;
@override
void initState() {
super.initState();
_loadUsers();
}
_loadUsers() async {
String jsonString =
'[{"id": 1, "name": "John", "email": "john@example.com"}, {"id": 2, "name": "Jane", "email": "jane@example.com"}]';
final jsonResponse = json.decode(jsonString);
setState(() {
_users = jsonResponse.map((e) => User.fromJson(e)).toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Json解析与Model使用'),
),
body: ListView.builder(
itemCount: _users?.length ?? 0,
itemBuilder: (context, index) {
return ListTile(
title: Text(_users[index].name),
subtitle: Text(_users[index].email),
);
},
),
);
}
}
class User {
final int id;
final String name;
final String email;
User({this.id, this.name, this.email});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
}
这段代码首先定义了一个User模型类,并实现了从Json解析的工厂构造函数。然后在_JsonParsePageState
的initState
中调用了异步方法_loadUsers
来解析一个包含用户信息的Json字符串,并更新UI显示。这个例子展示了如何在Flutter中处理Json数据和使用Model类,是学习Flutter网络和数据处理的一个很好的起点。
评论已关闭