当前位置:   article > 正文

Flutter使用stack来实现悬浮UI

Flutter使用stack来实现悬浮UI

在这里插入图片描述

文章目录

stack特性

Flutter中,你可以使用Stack和Positioned来创建悬浮 UI。Stack允许你将多个小部件叠放在一起,而Positioned则用于定位小部件在Stack中的位置。

示例

以下是一个简单的示例,演示如何创建一个悬浮按钮:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Floating UI Example'),
        ),
        body: MyFloatingUI(),
      ),
    );
  }
}

class MyFloatingUI extends StatefulWidget {
  
  _MyFloatingUIState createState() => _MyFloatingUIState();
}

class _MyFloatingUIState extends State<MyFloatingUI> {
  bool isFloatingUIVisible = false;

  
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // Your main content goes here
        Center(
          child: Text(
            'Main Content',
            style: TextStyle(fontSize: 20),
          ),
        ),
        
        // Floating UI
        Visibility(
          visible: isFloatingUIVisible,
          child: Positioned(
            bottom: 16,
            right: 16,
            child: FloatingActionButton(
              onPressed: () {
                // Handle floating button tap
                print('Floating Button Tapped');
              },
              child: Icon(Icons.add),
            ),
          ),
        ),
      ],
    );
  }

  // Show/hide the floating UI based on some condition
  void toggleFloatingUI() {
    setState(() {
      isFloatingUIVisible = !isFloatingUIVisible;
    });
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

在这个例子中,MyFloatingUI是一个StatefulWidget,它包含一个Stack,其中包括了一个主要的内容(Text)和一个悬浮的按钮(FloatingActionButton)。通过Visibility小部件,可以根据条件来控制悬浮按钮的可见性。在这个例子中,isFloatingUIVisible为true时悬浮按钮可见,为false时不可见。


结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/47143
推荐阅读
相关标签
  

闽ICP备14008679号