现在的APP几乎没有单机版的,大部分APP都需要联网。现在采用的主流的前后端交互方式是json,flutter在处理json方面也提供了相应的方案。
新建一个flutter应用,然后在pubspec.yaml添加依赖
dependencies:
flutter:
sdk: flutter
json_annotation: ^2.0.0
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.0.0
json_serializable: ^2.0.0
build_verify: ^1.0.0
废话不多说,贴代码
import 'package:json_annotation/json_annotation.dart';
part 'User.g.dart';
@JsonSerializable()
class User {
final int code;
final String status;
final String msg;
@JsonKey(nullable: false)
List<Item> data;
User(this.code, this.status, this.msg, {List<Item> data})
: data = data ?? <Item>[];
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
@JsonSerializable(includeIfNull: false)
class Item {
String title;
List<UserDetail> data;
Item();
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
@JsonSerializable()
class UserDetail {
int id;
String name;
UserDetail();
factory UserDetail.fromJson(Map<String, dynamic> json) =>
_$UserDetailFromJson(json);
Map<String, dynamic> toJson() => _$UserDetailToJson(this);
}
@JsonLiteral('user.json')
Map get glossaryData => _$glossaryDataJsonLiteral;
首先,我们根据json串生成响应的model
其次,执行flutter packages pub run build_runner build 生成需要的文件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'dart:convert';
import 'User.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: new _MyAppWidget(),
);
}
}
class _MyAppWidget extends StatefulWidget {
@override
State createState() {
return new _MyAppState();
}
}
class _MyAppState extends State<_MyAppWidget> {
String jsonStr;
var userData;
void _loadJson() async {
rootBundle.loadString('assets/data/user.json').then((val) {
var user = json.decode(val);
setState(() {
userData = user['data'];
});
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: new Center(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new IconButton(
icon: new Icon(Icons.refresh),
onPressed: () {
_loadJson();
if (jsonStr != null) {
var user = json.decode(jsonStr);
print(user['data']);
}
},
),
new Expanded(
child: userData == null
? new Text("$jsonStr")
: new ListView.builder(
itemBuilder: (context, index) {
return new Column(
children: <Widget>[
new ListTile(
title: new Text('${userData[index]['title']}'),
),
],
);
},
itemCount: userData.length,
),
),
],
),
),
);
}
}
参考文章
json处理
老规矩github上代码
网友评论