美文网首页
Flutter GetX的MVC框架使用

Flutter GetX的MVC框架使用

作者: woniu | 来源:发表于2022-08-02 10:41 被阅读0次

    一、网络请求封装

    创建ApiService用于网络请求数据。

    import 'dart:convert';
    import 'package:dio/dio.dart';
    //model
    import 'package:flutter_getx_example/GetXApiDataExample/MovieModule/Models/MovieModel.dart';
    
    class ApiService {
    //返回类型是MovieModel类型的数组
      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"]));
        }
      }
    
    }
    

    二、定义模型类用于数据转模型

    // 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,
      };
    }
    

    三、Controller控制器对数据进行处理

    对请求回的数据转化成model,并且在请求前增加loading,结束后endLoading。

    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);
        }
      }
    }
    

    四、View视图层展示列表数据

    在view层获取请求到的数据,然后填充数据。
    这里有使用到Get.put(MovieController())获取controller,然后使用obx监控movieList的改变。

    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,
                      )
                    ],
                  );
                },
              );
            }
          }),
        );
      }
    

    相关文章

      网友评论

          本文标题:Flutter GetX的MVC框架使用

          本文链接:https://www.haomeiwen.com/subject/ibyswrtx.html