前言
在前面的文章中我們對GetX
的基礎知識進行了講解,包括狀態(tài)管理仰挣、路由管理伴逸、依賴管理、國際化等膘壶。
今天我們來將一個小案例用于結合前面學習的知識做一個總結错蝴,這個案例主要是講解網絡數(shù)據請求、模型處理颓芭、GetXController顷锰,用MVC模型來實現(xiàn)。
視頻教程地址
請求網絡數(shù)據
我們新建一個ApiService.dart
用于請求網絡數(shù)據亡问,該數(shù)據是一個新聞列表的數(shù)據。
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_getx_example/GetXApiDataExample/MovieModule/Models/MovieModel.dart';
class ApiService {
static Future<List<MovieModel>> fetchMovie() async {
var response = await Dio().get("http://apis.juhe.cn/fapig/douyin/billboard?type=hot_video&size=50&key=9eb8ac7020d9bea6048db1f4c6b6d028");
if (response.statusCode == 200) {
var jsonString = response.data['result'];
return movieModelFromJson(json.encode(response.data["result"]));
}
}
}
定義模型類
我們新建一個MovieModel.dart
用來對網絡請求回來的數(shù)據進行模型轉換慎框。
// To parse this JSON data, do
//
// final movieModel = movieModelFromJson(jsonString);
import 'dart:convert';
List<MovieModel> movieModelFromJson(String str) => List<MovieModel>.from(json.decode(str).map((x) => MovieModel.fromJson(x)));
String movieModelToJson(List<MovieModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class MovieModel {
MovieModel({
this.title,
this.shareUrl,
this.author,
this.itemCover,
this.hotValue,
this.hotWords,
this.playCount,
this.diggCount,
this.commentCount,
});
String title;
String shareUrl;
String author;
String itemCover;
int hotValue;
String hotWords;
int playCount;
int diggCount;
int commentCount;
factory MovieModel.fromJson(Map<String, dynamic> json) => MovieModel(
title: json["title"],
shareUrl: json["share_url"],
author: json["author"],
itemCover: json["item_cover"],
hotValue: json["hot_value"],
hotWords: json["hot_words"],
playCount: json["play_count"],
diggCount: json["digg_count"],
commentCount: json["comment_count"],
);
Map<String, dynamic> toJson() => {
"title": title,
"share_url": shareUrl,
"author": author,
"item_cover": itemCover,
"hot_value": hotValue,
"hot_words": hotWords,
"play_count": playCount,
"digg_count": diggCount,
"comment_count": commentCount,
};
}
使用控制器對數(shù)據進行處理
我們對請求回來的網絡數(shù)據轉化為Model
严嗜,并在請求前增加一個loading
,當網絡數(shù)據請求回來的時候關閉loading
渗常,我們來看一下代碼
import 'package:flutter_getx_example/GetXApiDataExample/ApiModule/ApiService.dart';
import 'package:flutter_getx_example/GetXApiDataExample/MovieModule/Models/MovieModel.dart';
import 'package:get/get.dart';
class MovieController extends GetxController {
var isLoading = true.obs;
// ignore: deprecated_member_use
var movieList = List<MovieModel>().obs;
@override
void onInit() {
// TODO: implement onInit
fetchMovie();
super.onInit();
}
void fetchMovie() async {
try {
isLoading(true);
var movie = await ApiService.fetchMovie();
if (movie != null) {
movieList.assignAll(movie);
}
} finally {
isLoading(false);
}
}
}
在視圖層展示列表數(shù)據
前面我們對網絡請求、模型踢俄、數(shù)據處理進行了處理抗俄,我們最終的目的是需要把數(shù)據展示到頁面上跟压,那我們接著來看一下視圖的代碼
import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXApiDataExample/MovieModule/Controller/MovieController.dart';
import 'package:get/get.dart';
class MovieListView extends StatelessWidget {
final MovieController movieController = Get.put(MovieController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Movie"),
),
body: Obx(() {
if (movieController.isLoading.value) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: movieController.movieList.length,
itemBuilder: (context, index) {
return Column(
children: [
Row(
children: [
Container(
width: 100,
height: 120,
margin: EdgeInsets.all(10),
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.network(
movieController.movieList[index].itemCover,
width: 150,
height: 100,
fit: BoxFit.fill,
// color: Colors.orange,
// colorBlendMode: BlendMode.color,
),
),
),
Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
movieController.movieList[index].author,
style: TextStyle(
color: Colors.black45,
fontSize: 16
),
)
],
),
),
],
),
Container(
color: Colors.grey.shade300,
height: 2,
)
],
);
},
);
}
}),
);
}
效果展示
image
總結
該案例中最重要的通過繼承自GetxController
分離了UI和業(yè)務邏輯倔监,并通過Get.put
對控制器進行了實例化济丘,然后使用Obx
對數(shù)據進行了一個狀態(tài)刷新疟赊。