四、Flutter轮播图

目录
一、集成flutter_swiper和cached_network_image
二、flutter_swiper
三、图片缓存
四、整体代码
五、flutter run

一、集成flutter_swiper和cached_network_image
pubspec.yaml 中 添加flutter_swiper : ^1.1.6和 cached_network_image: ^1.0.0,并同步 flutter packages get 。
在相应的 .dart 文件中添加引用import 'package:flutter_swiper/flutter_swiper.dart’和import ‘package:cached_network_image/cached_network_image.dart’。

 dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  dio: ^2.1.10
  fluttertoast: ^3.1.0
  flutter_swiper: ^1.1.6
  cached_network_image: ^1.0.0

二、flutter_swiper
可以设置滚动方向,设置为Axis.vertical如果需要垂直滚动。多种布局方式,无限轮播,Android和IOS双端适配。

 ConstrainedBox(
              child: Swiper(
                outer: false,
                itemBuilder: (c, i) {
                  if(swiperDataList!=null){
                    return CachedNetworkImage(
                        imageUrl: "${swiperDataList[i]}",
                       placeholder: (context, url) => new CircularProgressIndicator(),
                      errorWidget: (context, url, error) => new Icon(Icons.error),
                     );
                  }
                },
                pagination:
                    new SwiperPagination(margin: new EdgeInsets.all(5.0)),
                   itemCount: swiperDataList == null ? 0 : swiperDataList.length,
              ),
              constraints:
                  new BoxConstraints.loose(new Size(MediaQuery.of(context).size.width, 180.0)))

三、图片缓存
CachedNetworkImage缓存网络图片,加载时还支持占位图和淡入淡出图片。

CachedNetworkImage(
        imageUrl: "${listData[index]['images']['small']}",
        placeholder: (context, url) => new CircularProgressIndicator(),
        errorWidget: (context, url, error) => new Icon(Icons.error),
        fit: BoxFit.fill,
     )

四、整体代码

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'util/YFHttp.dart';

class IndexPage extends StatefulWidget {
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State {
  List listData;
  List swiperDataList=["https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1562723625662&di=bc7be59dd27706ea65ea33a94c209477&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F12%2F40%2F43%2F18958PICYpQ.jpg",
  "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1562723734494&di=864f7b85f900f0b68e8bc08f1c078eed&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201511%2F02%2F20151102140204_WUSwE.jpeg",
  "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1562723821634&di=e04d14690229411a560ccc6cf0e10f6a&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F15%2F01%2F96%2F56N58PICVWw_1024.jpg"];
  void _loadData() async {
    var result = await YFHttp.request('/v2/movie/in_theaters',
        data: {
          'apikey': "0b2bdeda43b5688921839c8ecb20399b",
        },
        method: YFHttp.GET);

    setState(() {
      listData = result['subjects'];
    });
  }

  @override
  void initState() {
    this._loadData();
    super.initState();
  }

  Widget _getItems(context, index) {
    if (listData.length > 0) {
      return ListTile(
        title: Text(listData[index]["title"]),
        subtitle: Text(listData[index]["mainland_pubdate"]),
        leading:  CachedNetworkImage(
        imageUrl: "${listData[index]['images']['small']}",
        placeholder: (context, url) => new CircularProgressIndicator(),
        errorWidget: (context, url, error) => new Icon(Icons.error),
        fit: BoxFit.fill,
     )
      );
    } else {
      return ListTile();
    }
  }

 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('轮播图'),
      ),
      body: Column(
        children: [
          ConstrainedBox(
              child: Swiper(
                outer: false,
                itemBuilder: (c, i) {
                  if(swiperDataList!=null){
                    return CachedNetworkImage(
                          imageUrl: "${swiperDataList[i]}",
                         placeholder: (context, url) => new CircularProgressIndicator(),
                        errorWidget: (context, url, error) => new Icon(Icons.error),
                     );
                  }
                },
                pagination:
                    new SwiperPagination(margin: new EdgeInsets.all(5.0)),
                   itemCount: swiperDataList == null ? 0 : swiperDataList.length,
              ),
              constraints:
                  new BoxConstraints.loose(new Size(MediaQuery.of(context).size.width, 180.0))),
          Expanded(
            child:  ListView.builder(
              itemCount: listData == null ? 0 : listData.length,
              itemBuilder: this._getItems),
          )
        ],
      ),
    );
  }
}

五、flutter run

四、Flutter轮播图_第1张图片

关注公众号,查看更多内容.jpg

你可能感兴趣的:(Flutter)