我的应用程序无法在Flutter中运行carousel包

xkrw2x1b  于 2023-10-22  发布在  Flutter
关注(0)|答案(2)|浏览(168)

我添加了“carousel_pro:^1.0.0”在我的pubspec.yaml文件中的依赖项下,并使用“import 'package:carousel_pro/carousel_pro. dart'”导入到我想要的文件中;“.
这是全部文件

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

    class CarouselImages extends StatefulWidget {

      final List<String> imagesListUrl;

      CarouselImages(this.imagesListUrl);

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

    class _CarouselImagesState extends State<CarouselImages> {
      @override
      Widget build(BuildContext context) {

        Size size = MediaQuery.of(context).size;

        return Container(
          height: size.height * 0.35,
          child: Carousel(
            dotSize: 5,
            dotBgColor: Colors.transparent,
            autoplay: false,
            images: [
              AssetImage(widget.imagesListUrl[0],),
              AssetImage(widget.imagesListUrl[1],),
              AssetImage(widget.imagesListUrl[2],),
              AssetImage(widget.imagesListUrl[3],),
              AssetImage(widget.imagesListUrl[4],),
              AssetImage(widget.imagesListUrl[5],),
            ],
          ),
        );
      }
    }

但是代码没有运行,我在导入和carousel小部件处加了一条红线。将鼠标悬停在导入代码上,它说:URI的目标不存在:'package:carousel_pro/carousel_pro.dart'.dart(uri_does_not_exist)
当我将鼠标悬停在小部件上时,它说:方法'Carnival'不是为_CarouselImagesState'.dart(undefined_method)类型定义的。快速修复告诉我创建类、方法或函数。
帮我解决这个
我试着升级和降级flutter和dart版本,还有carousel包。我也试过从carousel_pro改为carousel_slider,但仍然不起作用。
我希望这将解决这个问题,有一个更稳定的版本的 dart 和Flutter或依赖

llew8vvj

llew8vvj1#

1.最新版本的flutter不支持这个库
2.in问题的描述你没有说明你的电脑上安装的flutter的版本
3.我建议尝试另一个库,例如这个one
screenshot from pub dev

hgb9j2n6

hgb9j2n62#

carousel包在一些旧版本的Flutter上。让我帮忙创建您自己的carousel文件。代码如下:

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';

enum DotPosition {
  topLeft,
  topCenter,
  topRight,
  bottomLeft,
  bottomCenter,
  bottomRight
}

class Carousel extends StatefulWidget {
  //All the images on this Carousel.
  final List? images;

  //All the images on this Carousel.
  final dynamic defaultImage;

  //The transition animation timing curve. Default is [Curves.ease]
  final Curve animationCurve;

  //The transition animation duration. Default is 300ms.
  final Duration animationDuration;

  // The base size of the dots. Default is 8.0
  final double dotSize;

  // The increase in the size of the selected dot. Default is 2.0
  final double dotIncreaseSize;

  // The distance between the center of each dot. Default is 25.0
  final double dotSpacing;

  // The Color of each dot. Default is Colors.white
  final Color dotColor;

  // The background Color of the dots. Default is [Colors.grey[800].withOpacity(0.5)]
  final Color? dotBgColor;

  // The Color of each increased dot. Default is Colors.white
  final Color dotIncreasedColor;

  // Enable or Disable the indicator (dots). Default is true
  final bool showIndicator;

  //Padding Size of the background Indicator. Default is 20.0
  final double indicatorBgPadding;

  //How to show the images in the box. Default is cover
  final BoxFit boxFit;

  //Enable/Disable radius Border for the images. Default is false
  final bool borderRadius;

  //Border Radius of the images. Default is [Radius.circular(8.0)]
  final Radius? radius;

  //Indicator position. Default bottomCenter
  final DotPosition dotPosition;

  //Move the Indicator Horizontally relative to the dot position
  final double dotHorizontalPadding;

  //Move the Indicator Vertically relative to the dot position
  final double dotVerticalPadding;

  //Move the Indicator From the Bottom
  final double moveIndicatorFromBottom;

  //Remove the radius bottom from the indicator background. Default false
  final bool noRadiusForIndicator;

  //Enable/Disable Image Overlay Shadow. Default false
  final bool overlayShadow;

  //Choose the color of the overlay Shadow color. Default Colors.grey[800]
  final Color? overlayShadowColors;

  //Choose the size of the Overlay Shadow, from 0.0 to 1.0. Default 0.5
  final double overlayShadowSize;

  //Enable/Disable the auto play of the slider. Default true
  final bool autoplay;

  //Duration of the Auto play slider by seconds. Default 3 seconds
  final Duration autoplayDuration;

  //On image tap event, passes current image index as an argument
  final void Function(int)? onImageTap;

  //On image change event, passes previous image index and current image index as arguments
  final void Function(int, int)? onImageChange;

  const Carousel({
    Key? key,
    this.images,
    this.animationCurve = Curves.ease,
    this.animationDuration = const Duration(milliseconds: 300),
    this.dotSize = 8.0,
    this.dotSpacing = 25.0,
    this.dotIncreaseSize = 2.0,
    this.dotColor = Colors.white,
    this.dotBgColor,
    this.dotIncreasedColor = Colors.white,
    this.showIndicator = true,
    this.indicatorBgPadding = 10.0,
    this.boxFit = BoxFit.cover,
    this.borderRadius = false,
    this.radius,
    this.dotPosition = DotPosition.bottomCenter,
    this.dotHorizontalPadding = 0.0,
    this.dotVerticalPadding = 0.0,
    this.moveIndicatorFromBottom = 0.0,
    this.noRadiusForIndicator = false,
    this.overlayShadow = false,
    this.overlayShadowColors,
    this.overlayShadowSize = 0.5,
    this.autoplay = true,
    this.autoplayDuration = const Duration(seconds: 3),
    this.onImageTap,
    this.onImageChange,
    this.defaultImage,
  }) : super(key: key);

  @override
  State createState() => CarouselState();
}

class CarouselState extends State<Carousel> {
  Timer? timer;
  int _currentImageIndex = 0;
  PageController? _controller = PageController();

  @override
  void initState() {
    super.initState();

    if (widget.images != null && widget.images!.isNotEmpty) {
      if (widget.autoplay) {
        timer = Timer.periodic(widget.autoplayDuration, (_) {
          if (_controller!.hasClients) {
            if (_controller!.page!.round() == widget.images!.length - 1) {
              _controller!.animateToPage(
                0,
                duration: widget.animationDuration,
                curve: widget.animationCurve,
              );
            } else {
              _controller!.nextPage(
                  duration: widget.animationDuration,
                  curve: widget.animationCurve);
            }
          }
        });
      }
    }
  }

  @override
  void dispose() {
    _controller!.dispose();
    _controller = null;
    timer?.cancel();
    timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> listImages = (widget.images != null &&
            widget.images!.isNotEmpty)
        ? widget.images!.map<Widget>(
            (netImage) {
              if (netImage is ImageProvider) {
                return Container(
                  decoration: BoxDecoration(
                    borderRadius: widget.borderRadius
                        ? BorderRadius.all(
                            widget.radius ?? standardBorderRadius as Radius,
                          )
                        : null,
                    image: DecorationImage(
                      //colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
                      image: netImage,
                      fit: widget.boxFit,
                    ),
                  ),
                  child: widget.overlayShadow
                      ? Container(
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.bottomCenter,
                              end: Alignment.center,
                              stops: [0.0, widget.overlayShadowSize],
                              colors: [
                                widget.overlayShadowColors != null
                                    ? widget.overlayShadowColors!
                                        .withOpacity(1.0)
                                    : Colors.grey[800]!.withOpacity(1.0),
                                widget.overlayShadowColors != null
                                    ? widget.overlayShadowColors!
                                        .withOpacity(0.0)
                                    : Colors.grey[800]!.withOpacity(0.0)
                              ],
                            ),
                          ),
                        )
                      : Container(),
                );
              } else if (netImage is FadeInImage) {
                return ClipRRect(
                  borderRadius: widget.borderRadius
                      ? BorderRadius.all(
                          widget.radius ??
                              const Radius.circular(
                                borderDouble,
                              ),
                        )
                      : standardBorderRadius,
                  child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.bottomCenter,
                          end: Alignment.center,
                          stops: [0.0, widget.overlayShadowSize],
                          colors: [
                            widget.overlayShadowColors != null
                                ? widget.overlayShadowColors!.withOpacity(1.0)
                                : Colors.grey[800]!.withOpacity(1.0),
                            widget.overlayShadowColors != null
                                ? widget.overlayShadowColors!.withOpacity(0.0)
                                : Colors.grey[800]!.withOpacity(0.0)
                          ],
                        ),
                      ),
                      child: netImage),
                );
              } else {
                return netImage;
              }
            },
          ).toList()
        : [
            widget.defaultImage is ImageProvider
                ? Container(
                    decoration: BoxDecoration(
                      borderRadius: widget.borderRadius
                          ? BorderRadius.all(
                              widget.radius ?? const Radius.circular(8.0))
                          : null,
                      image: DecorationImage(
                        //colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
                        image: widget.defaultImage,
                        fit: widget.boxFit,
                      ),
                    ),
                    child: widget.overlayShadow
                        ? Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment.bottomCenter,
                                end: Alignment.center,
                                stops: [0.0, widget.overlayShadowSize],
                                colors: [
                                  widget.overlayShadowColors != null
                                      ? widget.overlayShadowColors!
                                          .withOpacity(1.0)
                                      : Colors.grey[800]!.withOpacity(1.0),
                                  widget.overlayShadowColors != null
                                      ? widget.overlayShadowColors!
                                          .withOpacity(0.0)
                                      : Colors.grey[800]!.withOpacity(0.0)
                                ],
                              ),
                            ),
                          )
                        : Container(),
                  )
                : widget.defaultImage,
          ];

    final bottom = [
      DotPosition.bottomLeft,
      DotPosition.bottomCenter,
      DotPosition.bottomRight
    ].contains(widget.dotPosition)
        ? widget.dotVerticalPadding
        : null;
    final top = [
      DotPosition.topLeft,
      DotPosition.topCenter,
      DotPosition.topRight
    ].contains(widget.dotPosition)
        ? widget.dotVerticalPadding
        : null;
    double? left = [DotPosition.topLeft, DotPosition.bottomLeft]
            .contains(widget.dotPosition)
        ? widget.dotHorizontalPadding
        : null;
    double? right = [DotPosition.topRight, DotPosition.bottomRight]
            .contains(widget.dotPosition)
        ? widget.dotHorizontalPadding
        : null;

    if (left == null && right == null) {
      left = right = 0.0;
    }

    return Stack(
      children: <Widget>[
        Builder(
          builder: (_) {
            Widget pageView = PageView(
              physics: const AlwaysScrollableScrollPhysics(),
              controller: _controller,
              children: listImages,
              onPageChanged: (currentPage) {
                if (widget.onImageChange != null) {
                  widget.onImageChange!(_currentImageIndex, currentPage);
                }

                _currentImageIndex = currentPage;
              },
            );

            if (widget.onImageTap == null) {
              return pageView;
            }

            return GestureDetector(
              child: pageView,
              onTap: () => widget.onImageTap!(_currentImageIndex),
            );
          },
        ),
        widget.showIndicator
            ? Positioned(
                bottom: bottom,
                top: top,
                left: left,
                right: right,
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.8)
                      ],
                    ),
                    borderRadius: widget.borderRadius
                        ? (widget.noRadiusForIndicator
                            ? null
                            : BorderRadius.only(
                                bottomLeft:
                                    widget.radius ?? const Radius.circular(8.0),
                                bottomRight:
                                    widget.radius ?? const Radius.circular(8.0)))
                        : null,
                  ),
                  padding: EdgeInsets.all(widget.indicatorBgPadding),
                  child: Center(
                    child: DotsIndicator(
                      controller: _controller!,
                      itemCount: listImages.length,
                      color: widget.dotColor,
                      increasedColor: widget.dotIncreasedColor,
                      dotSize: widget.dotSize,
                      dotSpacing: widget.dotSpacing,
                      dotIncreaseSize: widget.dotIncreaseSize,
                      onPageSelected: (int page) {
                        _controller!.animateToPage(
                          page,
                          duration: widget.animationDuration,
                          curve: widget.animationCurve,
                        );
                      },
                    ),
                  ),
                ),
              )
            : Container(),
      ],
    );
  }
}

/// An indicator showing the currently selected page of a PageController
class DotsIndicator extends AnimatedWidget {
  const DotsIndicator(
      {Key? key,
      required this.controller,
      this.itemCount,
      this.onPageSelected,
      this.color,
      this.increasedColor,
      this.dotSize,
      this.dotIncreaseSize,
      this.dotSpacing})
      : super(key: key, listenable: controller);

  // The PageController that this DotsIndicator is representing.
  final PageController controller;

  // The number of items managed by the PageController
  final int? itemCount;

  // Called when a dot is tapped
  final ValueChanged<int>? onPageSelected;

  // The color of the dots.
  final Color? color;

  // The color of the increased dot.
  final Color? increasedColor;

  // The base size of the dots
  final double? dotSize;

  // The increase in the size of the selected dot
  final double? dotIncreaseSize;

  // The distance between the center of each dot
  final double? dotSpacing;

  Widget _buildDot(int index) {
    double selectedness = Curves.easeOut.transform(
      max(
        0.0,
        1.0 - ((controller.page ?? controller.initialPage) - index).abs(),
      ),
    );
    double zoom = 1.0 + (dotIncreaseSize! - 1.0) * selectedness;
    final dotColor = zoom > 1.0 ? increasedColor : color;

    return SizedBox(
      width: dotSpacing,
      child: Center(
        child: Material(
          color: dotColor,
          type: MaterialType.circle,
          child: SizedBox(
            width: dotSize! * zoom,
            height: dotSize! * zoom,
            child: InkWell(
              onTap: () => onPageSelected!(index),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List<Widget>.generate(itemCount!, _buildDot),
    );
  }
}

class WidgetCarousel extends StatefulWidget {
  //All the pages on this Carousel.
  final List pages;

  //The transition animation timing curve. Default is [Curves.ease]
  final Curve animationCurve;

  //The transition animation duration. Default is 300ms.
  final Duration animationDuration;

  // The base size of the dots. Default is 8.0
  final double dotSize;

  // The increase in the size of the selected dot. Default is 2.0
  final double dotIncreaseSize;

  // The distance between the center of each dot. Default is 25.0
  final double dotSpacing;

  // The Color of each dot. Default is Colors.white
  final Color dotColor;

  // The background Color of the dots. Default is [Colors.grey[800].withOpacity(0.5)]
  final Color? dotBgColor;

  // Enable or Disable the indicator (dots). Default is true
  final bool showIndicator;

  //Padding Size of the background Indicator. Default is 20.0
  final double indicatorBgPadding;

  //How to show the images in the box. Default is cover
  final BoxFit boxFit;

  //Enable/Disable radius Border for the images. Default is false
  final bool borderRadius;

  //Border Radius of the images. Default is [Radius.circular(8.0)]
  final Radius? radius;

  //Move the Indicator From the Bottom
  final double moveIndicatorFromBottom;

  //Remove the radius bottom from the indicator background. Default false
  final bool noRadiusForIndicator;

  //Enable/Disable Image Overlay Shadow. Default false
  final bool overlayShadow;

  //Choose the color of the overlay Shadow color. Default Colors.grey[800]
  final Color? overlayShadowColors;

  //Choose the size of the Overlay Shadow, from 0.0 to 1.0. Default 0.5
  final double overlayShadowSize;

  //Enable/Disable the auto play of the slider. Default true
  final bool autoplay;

  //Duration of the Auto play slider by seconds. Default 3 seconds
  final Duration autoplayDuration;

  const WidgetCarousel(
      {Key? key,
      required this.pages,
      this.animationCurve = Curves.ease,
      this.animationDuration = const Duration(milliseconds: 300),
      this.dotSize = 8.0,
      this.dotSpacing = 25.0,
      this.dotIncreaseSize = 2.0,
      this.dotColor = Colors.white,
      this.dotBgColor,
      this.showIndicator = true,
      this.indicatorBgPadding = 20.0,
      this.boxFit = BoxFit.cover,
      this.borderRadius = false,
      this.radius,
      this.moveIndicatorFromBottom = 0.0,
      this.noRadiusForIndicator = false,
      this.overlayShadow = false,
      this.overlayShadowColors,
      this.overlayShadowSize = 0.5,
      this.autoplay = true,
      this.autoplayDuration = const Duration(seconds: 3)})
      : super(key: key);

  @override
  State createState() => WidgetCarouselState();
}

class WidgetCarouselState extends State<WidgetCarousel> {
  final _controller = PageController();

  @override
  void initState() {
    super.initState();

    if (widget.autoplay) {
      Timer.periodic(widget.autoplayDuration, (_) {
        if (_controller.page == widget.pages.length - 1) {
          _controller.animateToPage(
            0,
            duration: widget.animationDuration,
            curve: widget.animationCurve,
          );
        } else {
          _controller.nextPage(
              duration: widget.animationDuration, curve: widget.animationCurve);
        }
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> listPages = widget.pages
        .map((widget) => Container(
              child: widget,
            ))
        .toList();

    return Stack(
      children: <Widget>[
        PageView(
          physics: const AlwaysScrollableScrollPhysics(),
          controller: _controller,
          children: listPages,
        ),
        widget.showIndicator
            ? Positioned(
                bottom: widget.moveIndicatorFromBottom,
                left: 0.0,
                right: 0.0,
                child: Container(
                  decoration: BoxDecoration(
                    color:
                        widget.dotBgColor ?? Colors.grey[800]!.withOpacity(0.5),
                    borderRadius: widget.borderRadius
                        ? (widget.noRadiusForIndicator
                            ? null
                            : BorderRadius.only(
                                bottomLeft:
                                    widget.radius ?? const Radius.circular(8.0),
                                bottomRight:
                                    widget.radius ?? const Radius.circular(8.0)))
                        : null,
                  ),
                  padding: EdgeInsets.all(widget.indicatorBgPadding),
                  child: Center(
                    child: DotsIndicator(
                      controller: _controller,
                      itemCount: listPages.length,
                      color: widget.dotColor,
                      dotSize: widget.dotSize,
                      dotSpacing: widget.dotSpacing,
                      dotIncreaseSize: widget.dotIncreaseSize,
                      onPageSelected: (int page) {
                        _controller.animateToPage(
                          page,
                          duration: widget.animationDuration,
                          curve: widget.animationCurve,
                        );
                      },
                    ),
                  ),
                ),
              )
            : Container(),
      ],
    );
  }
}

这里有一个文件,我保存了所有的常量,在这段代码中引用了它。以下是相关的部分。

const borderDouble = 8.0;
BorderRadius standardBorderRadius = BorderRadius.circular(borderDouble);

享受

相关问题