Study harmoniously! Don’t be impatient!! I’m your old friend, Xiao Qinglong
-
HTTP and DIO libraries are the most commonly used web libraries for Flutter. HTTP is used as an example in this paper.
-
There are two ways to convert json to a model:
-
json_annotation
-
Online tool QuickType
-
1. How to collect third-party librarieshttp
?
- Open theThird Party Open Source librarySearch,
http
Clicking it copies the library name + version number
Go to our project directory, find and open pubspec.yaml
2. How to use third-party librarieshttp
?
Import where you need to use the network
import 'package:http/http.dart' as http;
Copy the code
And then in initState
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
// Omit irrelevant code here. } @overridevoid initState() {
super.initState();
// Send a get request
sendHttp();
}
void sendHttp() async {
var url = Uri.parse('http://rap2api.taobao.org/app/mock/293606/api/chat/list');
var response = await http.get(url);
print(ReasonPhrase ->${response.reasonPhrase}');
print(Request -> ${response.request}');
print(StatusCode -> ${response.statuscode}');
print(${response.contentLength}');
print(Headers -> ${response.headers}');
print(IsRedirect -> ${response.isRedirect}');
print('print see persistentConnection - > ${response. PersistentConnection}');
print(${response.body}'); }}Copy the code
Print result:
Json string to data model (json_annotation
)
Previously, we have successfully obtained the Json string data returned by the network request, so how to convert it into our defined model class?
3.1, configuration,pubspec.yaml
We’re going to use a couple of libraries here
-
json_annotation
-
build_runner
-
json_serializable
Open pubspec.yaml and start configuring and loading third-party libraries
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.02.
http: ^0.134.
json_annotation: ^4.3. 0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^1.0. 0
json_serializable: ^6.01.
build_runner: ^1.8. 0
Copy the code
3.2. Configure the data model
Create a Student. dart file and fill it out using the template below. You can write other model data the same way later
import 'package:json_annotation/json_annotation.dart';
part 'student.g.dart';
@JsonSerializable()
class StudentRoot {
String code;
List<Student> list;
StudentRoot({required this.code, required this.list});
factory StudentRoot.fromJson(Map<String, dynamic> json) =>
_$StudentRootFromJson(json);
Map<String, dynamic> toJson() => _$StudentRootToJson(this);
}
@JsonSerializable()
class Student {
String studentName;
int studentAge;
int studentId;
Student(
{required this.studentName,
required this.studentAge,
required this.studentId});
factory Student.fromJson(Map<String, dynamic> json) =>
_$StudentFromJson(json);
// Map<String, dynamic> toJson(Student instance) => _$StudentToJson(instance);
Map<String, dynamic> toJson() => _$StudentToJson(this);
}
Copy the code
We find part ‘student.g.art ‘; This line is an error, so don’t worry about that.
3.3. Prepare the test interface
http://rap2api.taobao.org/app/mock/293606/api/flutter/jsonmodel
Copy the code
3.4. Window execution commands
Open the Terminal window in the lower left corner of Android Studio
Enter the following command and press Enter
flutter pub run build_runner build
Copy the code
This is what happens when it’s done
Of course, some partners may find the execution finished:
-
part ‘student.g.dart’; This line still reports an error
-
The student.g.art file was not generated either
Xiaobian has also encountered this problem, might as well try the following methods:
-
Close those file creations and rerun the project
-
Restart the Android studio
3.5, use,
The first few steps are foreshadowing, the next is our main play.
Method of use
void sendHttp() async {
var url = Uri.parse(
'http://rap2api.taobao.org/app/mock/293606/api/flutter/jsonmodel');
var response = await http.get(url);
print('JsonPage print look body->${response.body}');
/ / turn StudentRoot Json
Map mapJson = jsonDecode(response.body);
String data = utf8.decode(response.bodyBytes);
StudentRoot studentRoot = StudentRoot.fromJson(json.decode(data));
/ / StudentRoot Json
String jsonAfter = jsonEncode(studentRoot);
// Here is the test code ~ ~
print(${studentroot. code}');
print(${studentroot. list}');
for (var listChild in studentRoot.list) {
print(${listChild.studentName} -${listChild.studentName});
}
print('StudentRoot to Json print $jsonAfter');
}
Copy the code
Running results:
How to useOnline tool QuickType
The above screenshot forgot to mark, the class name can be in the upper left cornerStuRoot place
changes
Copy the code, create a new model file, stu.dart, and paste it
Go to our jSON_page.dart test file and import the header file
import 'package:ssj_wechat_demo/models/stu.dart';
Copy the code
It is also very simple to use
// StudentRoot studentRoot = StudentRoot.fromJson(json.decode(data)); StuRoot studentRoot = stuRootFromJson(Response.body); stuRootFromJson(response.body);Copy the code