본문 바로가기

Flutter

Flutter Swiper

참고 https://pub.dev/packages/flutter_swiper

 

flutter_swiper | Flutter Package

The best swiper(carousel) for flutter, with multiple layouts, infinite loop. Compatible with Android & iOS.

pub.dev

기본세팅

project > test > pubspec.yaml file의 dependencies하위에 flutter_swiper : ^[version] 을 추가해준 후 저장
(왼쪽) dart file로 돌아와서 상단에 보이는 Upgrade dependencies를 클릭하거나 (오른쪽) AndroidStudio Terminal에서 flutter packages get을 실행한다

전체코드

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  SwipeSample createState() => SwipeSample();
}

class SwipeSample extends State<MyHomePage>{
  @override
  Widget build(BuildContext context){
    double appBarHeight = 50.0;
    return MaterialApp(
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(appBarHeight),
          child:AppBar(
            title: Text('Swipe Demo'),
            backgroundColor: Colors.cyan,
          ),
        ),
        body: BookSwipe([Red(), Blue(), Green()]),
      ),
    );
  }
}

//book swipe widget
class BookSwipe extends StatelessWidget{
  List<Widget> widgetList = List<Widget>();
  BookSwipe([this.widgetList]);
  @override
  Widget build(BuildContext context){
    if(widgetList == null){
      widgetList = [Red(), Green(), Blue()];
    }
    return Container(
      color: Colors.white,
      child: new LayoutBuilder(builder: (context, constraint) {
        return new Swiper(
          loop: true,
          pagination: new SwiperPagination(),
          itemCount: widgetList.length,
          itemBuilder: (BuildContext context, int index){
            return widgetList[index];
          },
          viewportFraction: 0.8,
          scale: 0.9,
          layout: SwiperLayout.STACK,
          itemWidth: constraint.biggest.width*0.8,
          itemHeight: constraint.biggest.height*0.8,
          index: 1,
        );
      })
    );
  }
}

// Card 위젯 구현
class Red extends StatelessWidget {
  @override
  Widget build(BuildContext context){
    return Card(color: Colors.red);
  }
}

// Text 위젯 구현
class Green extends StatelessWidget {
  @override
  Widget build(BuildContext context){
    return new LayoutBuilder(builder: (context, constraint) {
      double min = (constraint.biggest.width < constraint.biggest.height)
          ? constraint.biggest.width : constraint.biggest.height;
      return Container(
        width: constraint.biggest.width,
        height: constraint.biggest.height,
        color: Colors.green,
        child: Center(
          child: Text('GREEN',
            style: TextStyle(fontSize: min / 4, color: Colors.white, decoration: TextDecoration.none, fontWeight: FontWeight.normal)
          )
        )
      );
    });
  }
}

// Icon 위젯 구현
class Blue extends StatelessWidget {
  @override
  Widget build(BuildContext context){
    return new LayoutBuilder(builder: (context, constraint) {
      double min = (constraint.biggest.width < constraint.biggest.height)
          ? constraint.biggest.width : constraint.biggest.height;
      return Container(
        width: constraint.biggest.width,
        height: constraint.biggest.height,
        color: Colors.blue,
        child: Icon(Icons.access_alarms, size: min / 2, color: Colors.white),
      );
    });
  }
}

Red, Green, Blue 에 대한 설명은 https://cdl-dev.tistory.com/10 참조

 

Flutter 기본 Widget 구현

전체코드 import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildCo..

cdl-dev.tistory.com

BookSwipe

class BookSwipe extends StatelessWidget{
  List<Widget> widgetList = List<Widget>();
  BookSwipe([this.widgetList]);
  @override
  Widget build(BuildContext context){
    if(widgetList == null){
      widgetList = [Red(), Green(), Blue()];
    }
    return Container(
      color: Colors.white,
      child: new LayoutBuilder(builder: (context, constraint) {
        return new Swiper(
          loop: true,
          pagination: new SwiperPagination(),
          itemCount: widgetList.length,
          itemBuilder: (BuildContext context, int index){
            return widgetList[index];
          },
          viewportFraction: 0.8,
          scale: 0.9,
          layout: SwiperLayout.STACK,
          itemWidth: constraint.biggest.width*0.8,
          itemHeight: constraint.biggest.height*0.8,
          index: 1,
        );
      })
    );
  }
}

**[] : 타 객체지향 언어와 달리 Flutter 는 생성자를 단 하나만 정의 할 수 있기 때문에 필요한 매개변수가 다른경우 [] 를 통해 매개변수를 option화 할 수 있다. 위에서는 BookSwipe([this.widgetList]) 에서 사용되었다. 매개변수를 받은 경우 List<Widget> widgetList 에 할당되고 할당되지 않은 경우 if(widgetList == null) 에서 widgetList = [Red(), Green(), Blue()] 가 실행된다.

- Swiper

 flutter_swiper 에 있는 Widget이다.

loop : true이면 전체 Widget이 반복, false이면 마지막page에서 끝.

itemCount : int형 변수를 넣어 Swipe할 Widget이 총 몇개인지 명시.

itemBuilder : Widget의 List를 반환. int형 매개변수를 명시하여 Swiper 내부에서 자동으로 swipe에 따라 출력할 Widget을 조절한다.

viewportFraction, scale : 뒤에 표시되는 Widget의 투명도와 크기배율인것 같으나 조작을해도 변하지 않음..

layout : 기존에 만들어져있는 STACK, TINDER 적용가능, CUSTOM을 통해 직접 만든 동작구현가능

itemWidth, itemHeight : 제일 앞에 출력되는 Widget의 가로세로 길이 지정.

index : 시작 Widget 설정. (위에서는 Red가 첫번째 Widget이므로 Red부터 시작)

(cmd + B) Swiper의 요소들
(왼쪽) SwiperLayout.STACK / (오른쪽) SwiperLayout.TINDER

 

Tip 요약

**[] : 매개변수의 option화

'Flutter' 카테고리의 다른 글

Flutter Hero  (0) 2020.07.24
Flutter TabBar  (0) 2020.07.21
Flutter 기본 Widget 구현  (0) 2020.07.17
Flutter 기본예제  (0) 2020.07.15
Flutter + ARFoundation 기본세팅 (Windows)  (0) 2020.06.19