美文网首页
Flutter十五:文件操作与网络请求

Flutter十五:文件操作与网络请求

作者: Anwfly | 来源:发表于2020-05-26 23:32 被阅读0次

    一、文件操作

    二、网络请求

    1. Http
    2. HTTPClient
    3. 第三方请求dio
      dio(English | 中文简体)是Flutter中文网开源的一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时等...
    • ①添加依赖dio: ^3.0.3
    • ②接口类
    class Apis {
      static const String BASE_HOST = "https://www.wanandroid.com";
      /// 首页轮播
      static const String HOME_BANNER = BASE_HOST + "/banner/json";
      /// 首页列表
      static const String HOME_ARTICLE_LIST = BASE_HOST + "/article/list";
    }
    
    • ③dio方法封装
    ///dio 方法封装
    class ApiService {
      Dio dio = Dio();
    
      ///  获取首页轮播数据
     getBannerList() async {
        try {
          Response response = await dio.get(Apis.HOME_BANNER);
          if (response.statusCode == 200) {
            return response;
          } else {
            throw Exception('网络异常!');
          }
        } catch (e) {
          return print(e);
        }
      }
    

    实现异步有两种方式,Future和async、await,Future实现异步使用的API稍微复杂点,在Dart1.9中加入了async和await关键字,简化了异步写法
    async:申明该方法为异步方法
    await:阻塞式访问

    class BannerModel {
      List<BannerBean> data;
      int errorCode;
      String errorMsg;
    
      BannerModel({this.data, this.errorCode, this.errorMsg});
    
      BannerModel.fromJson(Map<String, dynamic> json) {
        if (json['data'] != null) {
          data = new List<BannerBean>();
          json['data'].forEach((v) {
            data.add(new BannerBean.fromJson(v));
          });
        }
        errorCode = json['errorCode'];
        errorMsg = json['errorMsg'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.data != null) {
          data['data'] = this.data.map((v) => v.toJson()).toList();
        }
        data['errorCode'] = this.errorCode;
        data['errorMsg'] = this.errorMsg;
        return data;
      }
    }
    
    class BannerBean {
      String desc;
      int id;
      String imagePath;
      int isVisible;
      int order;
      String title;
      int type;
      String url;
    
      BannerBean(
          {this.desc,
          this.id,
          this.imagePath,
          this.isVisible,
          this.order,
          this.title,
          this.type,
          this.url});
    
      BannerBean.fromJson(Map<String, dynamic> json) {
        desc = json['desc'];
        id = json['id'];
        imagePath = json['imagePath'];
        isVisible = json['isVisible'];
        order = json['order'];
        title = json['title'];
        type = json['type'];
        url = json['url'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['desc'] = this.desc;
        data['id'] = this.id;
        data['imagePath'] = this.imagePath;
        data['isVisible'] = this.isVisible;
        data['order'] = this.order;
        data['title'] = this.title;
        data['type'] = this.type;
        data['url'] = this.url;
        return data;
      }
    }
    
    • ⑤使用获取的网络数据
    class HomePage extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _HomeScreen();
      }
    }
    
    class _HomeScreen extends State<HomePage> {
      int _page = 0;
      BannerModel banners = BannerModel();
      ArticleModel _articleModel = ArticleModel();
      var scrollController = ScrollController();
    
      @override
      void initState() {
        super.initState();
        getBanners();
        getArticleList();
      }
    
      void getBanners() async {
        await ApiService().getBannerList().then((value) {
          //解码返回数据
          var data = json.decode(value.toString());
          //设置新数据,刷新状态
          setState(() {
            banners = BannerModel.fromJson(data);
          });
        });
      }
    
      void getArticleList() async {
        await ApiService().getArticleList(_page).then((value) {
          //解码返回数据
          var data = json.decode(value.toString());
          //设置新数据,刷新状态
          setState(() {
            _articleModel = ArticleModel.fromJson(data);
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView.builder(
            itemBuilder: itemView,
            controller: scrollController,
            itemCount: _articleModel.data.datas.length + 1,
          ),
        );
      }
    
      Widget itemView(BuildContext context, int index) {
        if (index == 0) {
          return Container(
              width: double.infinity,
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: Swiper(
                  itemBuilder: (BuildContext contxt, int index) {
                    return Image.network(banners.data[index].imagePath,
                        fit: BoxFit.cover);
                  },
                  itemCount: banners.data.length,
                  pagination: SwiperPagination(),
                  //显示indicator
    //                control: SwiperControl(), //显示箭头
                  loop: true,
                  autoplay: true,
                ),
              ));
        }
        ArticleBean item = _articleModel.data.datas[index - 1];
        return ItemArticleList(item: item);
      }
    }
    

    相关文章

      网友评论

          本文标题:Flutter十五:文件操作与网络请求

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