更新於 2022/04/24閱讀時間約 6 分鐘

Flutter Web image hover zoom(實現圖片懸浮縮放)

Implement Picture zoom when hover the image.
鼠標懸浮縮放
鼠標懸浮縮放
How to implement it?
Using AnimatedContainer to do animation and using InkWell to detect hover.
In InkWell:
InkWell(
       onTap: () {
         print('Tap');
       },
       // Detect hover here
       onHover: (val) {
         setState(() {
           isHover = val;
           print(val);
         });
       },
       child: //Child
)
In AnimatedContainer:
AnimatedContainer(
           transform: isHover ? hoverdTransform : unhoverdTransform,
           // duraction time
           duration: const Duration(seconds: 10),
           curve: Curves.ease,
           child: Image.network(
             imageUrl,
             fit: BoxFit.cover,
             height: 200,
           ),
         ),
Full Code:
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

void main() {
 runApp(
   MaterialApp(
     home: Home(),
   ),
 );
}

class Home extends StatefulWidget {
 @override
 _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: ZoomAnimate(),
   );
 }
}

class ZoomAnimate extends StatefulWidget {
 const ZoomAnimate({Key? key}) : super(key: key);

 @override
 State<ZoomAnimate> createState() => _ZoomAnimateState();
}

class _ZoomAnimateState extends State<ZoomAnimate> {
 bool isHover = false;
 String imageUrl =
     "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";

 @override
 Widget build(BuildContext context) {
   final hoverdTransform = Matrix4.identity()..scale(1.2);
   final unhoverdTransform = Matrix4.identity()..scale(1);
   return Padding(
     padding: const EdgeInsets.all(8.0),
     child: InkWell(
       onTap: () {
         print('Tap');
       },
       onHover: (val) {
         setState(() {
           isHover = val;
           print(val);
         });
       },
       child: ClipRRect(
         borderRadius: BorderRadius.circular(8.0),
         child: AnimatedContainer(
           transform: isHover ? hoverdTransform : unhoverdTransform,
           duration: const Duration(seconds: 10),
           curve: Curves.ease,
           child: Image.network(
             imageUrl,
             fit: BoxFit.cover,
             height: 200,
           ),
         ),
       ),
     ),
   );
 }
}

歡迎大家來我的Blog看:
1.Blog: 文章連結
2.Medium: 文章連結
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.