Flutter 360度图片查看插件 imageview360_nullsafe 的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter 360度图片查看插件 imageview360_nullsafe 的使用

imageview360

The Real Author is harpreetseera

pub.dev pub github github 我只是将代码转换为null安全版本。

这是一个提供带旋转和手势自定义的360度图片查看的Flutter包。

支持的Dart版本

Dart SDK 版本 >= 2.12.0

示例GIF

安装

添加依赖包:

dependencies:
  imageview360_nullsafe: ^2.0.0

如何使用

在dart文件中导入包:

import 'package:imageview360_nullsafe/imageview360_nullsafe.dart';
基本用法
ImageView360(
    key: UniqueKey(),
    imageList: imageList,
),

注意:为了让ImageView360在热重载时即时显示更改,你需要提供UniqueKey()以便每次重建该部件。

可定制的用法
ImageView360(
    key: UniqueKey(),                                           
    imageList: imageList,                                       
    autoRotate: true,                                           //可选
    rotationCount: 2,                                           //可选
    rotationDirection: RotationDirection.anticlockwise,         //可选
    frameChangeDuration: Duration(milliseconds: 50),            //可选
    swipeSensitivity: 2,                                        //可选
    allowSwipeToRotate: true,                                   //可选
    onImageIndexChanged: (currentImageIndex) {                  //可选
                          print("currentImageIndex: $currentImageIndex");
                        },
)

注意:为了获得更好的体验,在提供图片给部件之前,最好先缓存图片。例如:

从资源加载并预缓存图片的示例
List<ImageProvider> imageList = List<ImageProvider>();
for (int i = 1; i <= 52; i++) {
  imageList.add(AssetImage('assets/sample/$i.png'));
  // 预缓存图片以加快加载速度。
  await precacheImage(AssetImage('assets/sample/$i.png'), context);
}

必须字段

属性 类型 用途
imageList 列表 要显示的图片列表

可配置字段

属性 类型 默认值
autoRotate 布尔值 false
rotationCount 整数 1
rotationDirection RotationDirection RotationDirection.clockwise
frameChangeDuration 时长 Duration(milliseconds: 80)
swipeSensitivity 整数 1 (注意:允许范围为1-5,小于1被视为1,大于5被视为5)
allowSwipeToRotate 布尔值 true
onImageIndexChanged 函数(int) (currentImageIndex){}

博客文章

要更好地理解这个包的工作原理,请参阅我的博客文章:360度图像展示在Flutter中的实现

创建与维护者

许可证

Copyright 2020 Harpreet Singh & Damanpreet Singh

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

示例代码

以下是从示例项目中提取的代码:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ImageView360 Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DemoPage(title: 'ImageView360 Demo'),
    );
  }
}

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

  final String title;

  [@override](/user/override)
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  List<ImageProvider> imageList = [];
  bool autoRotate = true;
  int rotationCount = 2;
  int swipeSensitivity = 2;
  bool allowSwipeToRotate = true;
  RotationDirection rotationDirection = RotationDirection.anticlockwise;
  Duration frameChangeDuration = Duration(milliseconds: 50);
  bool imagePrecached = false;

  [@override](/user/override)
  void initState() {
    // 在第一次帧构建后加载图片。
    WidgetsBinding.instance?.addPostFrameCallback((_) => updateImageList(context));
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.only(top: 72.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                (imagePrecached == true)
                    ? ImageView360(
                        key: UniqueKey(),
                        imageList: imageList,
                        autoRotate: autoRotate,
                        rotationCount: rotationCount,
                        rotationDirection: RotationDirection.anticlockwise,
                        frameChangeDuration: Duration(milliseconds: 30),
                        swipeSensitivity: swipeSensitivity,
                        allowSwipeToRotate: allowSwipeToRotate,
                        onImageIndexChanged: (currentImageIndex) {
                          print("currentImageIndex: $currentImageIndex");
                        },
                      )
                    : Text("Pre-Caching images..."),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "Optional features:",
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.green,
                        fontSize: 24),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text("Auto rotate: $autoRotate"),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text("Rotation count: $rotationCount"),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text("Rotation direction: $rotationDirection"),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text(
                      "Frame change duration: ${frameChangeDuration.inMilliseconds} milliseconds"),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child:
                      Text("Allow swipe to rotate image: $allowSwipeToRotate"),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text("Swipe sensitivity: $swipeSensitivity"),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void updateImageList(BuildContext context) async {
    for (int i = 1; i <= 52; i++) {
      imageList.add(AssetImage('assets/sample/$i.png'));
      // 预缓存图片以加快加载速度。
      await precacheImage(AssetImage('assets/sample/$i.png'), context);
    }
    setState(() {
      imagePrecached = true;
    });
  }
}

更多关于Flutter 360度图片查看插件 imageview360_nullsafe 的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter 360度图片查看插件 imageview360_nullsafe 的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用imageview360_nullsafe插件来实现360度图片查看功能的示例代码。imageview360_nullsafe是一个提供360度全景图查看功能的Flutter插件,支持空安全。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加imageview360_nullsafe依赖:

dependencies:
  flutter:
    sdk: flutter
  imageview360_nullsafe: ^最新版本号  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 导入包

在你的Dart文件中导入imageview360_nullsafe包:

import 'package:imageview360_nullsafe/imageview360_nullsafe.dart';

3. 使用ImageView360组件

下面是一个完整的示例,展示如何在Flutter应用中使用ImageView360组件来显示360度图片:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '360度图片查看示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('360度图片查看示例'),
        ),
        body: Center(
          child: ImageView360(
            imageUrls: [
              'https://example.com/your-360-image-1.jpg',
              'https://example.com/your-360-image-2.jpg',
              // ... 添加更多的图片URL,通常一个360度图片会分成多个片段
            ],
            width: double.infinity, // 宽度
            height: double.infinity, // 高度,通常设置为屏幕高度的一部分或特定值
            autoPlay: true, // 是否自动播放
            autoPlayInterval: 3000, // 自动播放间隔时间(毫秒)
            imageScale: 1.0, // 图片缩放比例
            isLooping: true, // 是否循环播放
          ),
        ),
      ),
    );
  }
}

4. 配置说明

  • imageUrls: 一个包含360度图片片段URL的列表。通常,一个完整的360度图片会被分割成多个水平片段。
  • widthheight: 设置组件的宽度和高度。这里使用double.infinity来使其尽可能大,但你可以根据需要调整。
  • autoPlay: 一个布尔值,用于控制是否自动播放。
  • autoPlayInterval: 自动播放的时间间隔(毫秒)。
  • imageScale: 图片的缩放比例。
  • isLooping: 一个布尔值,用于控制是否循环播放。

5. 运行应用

保存所有文件后,使用flutter run命令运行你的Flutter应用。你应该能够在应用中看到一个360度图片查看器,支持拖动和自动播放功能。

请注意,以上代码中的图片URL需要替换为你自己的360度图片片段的URL。这些图片应该是按顺序排列的,每个片段覆盖360度中的一部分。

回到顶部