Home > database >  create button that pops up on hover
create button that pops up on hover

Time:09-19

I've spent a lot of time trying to implement one thing, which is a button that pops up in the center of a picture when the user's mouse enters the picture block, and when the mouse exits, button should disappear.

I've tried using many different widgets, such as InkWell and MouseArea but sadly didn't get expected behavior

Please share your thoughts if you know how to implement such behavior in flutter

Any help appreciated!

CodePudding user response:

Instead of using AnimatedContainer, you could use AnimatedSwitcher which switches between a Button and a non-visible SizedBox whenever the onEnter or onExit event is called.

Just change the container to the picture you want to show.

Code example with DartPad:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  
  bool showButton = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material App Bar'),
        ),
        body: Center(
          child: MouseRegion(
            onEnter: (_) => setState(() {
              showButton = true;
            }),
            onExit: (_) => setState(() {
              showButton = false;
            }),
            child: Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  color: Colors.red[200],
                  width: 300,
                  height: 300,
                ),
                AnimatedSwitcher(
                  duration: const Duration(milliseconds: 250),
                  child: showButton ? ElevatedButton(
                    onPressed: () => print("Hi!"),
                    child: const Text("Hello")
                  ) : const SizedBox.shrink(),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
  • Related