Flutter中Stack和Position简单例子

2022年8月7日 1081点热度 0人点赞 0条评论

效果图:
Flutter中Stack和Position简单例子插图

<code>Stack({
    Key? key,
    this.alignment = AlignmentDirectional.topStart,
    this.textDirection,
    this.fit = StackFit.loose,
    this.clipBehavior = Clip.hardEdge,
    List&lt;Widget&gt; children = const &lt;Widget&gt;[],
  })</code>

Stack:
alignment:作用于没有指定横轴或者纵轴位置的子元素。
fit:StackFit.loose--根据子元素大小显示;StackFit.expand会扩展到stack的大小。


<code>const Positioned({
    Key? key,
    this.left,
    this.top,
    this.right,
    this.bottom,
    this.width,
    this.height,
    required Widget child,
  })</code>

left、width、right只能设置其中两个,同样top、height、bottom也是只能设置其中两个。


<code>import &#039;package:flutter/material.dart&#039;;

main()=&gt;runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(&quot;Stack和Position&quot;),
          centerTitle: true,
        ),
        body: const MyHomePage()
      ),
    );
  }
}

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

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  DateTime? _dateTime;

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: const BoxConstraints.expand(),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            color: Colors.red,
            child: const Text(&quot;Hello world&quot;,style: TextStyle(color: Colors.white)),
          ),
          const Positioned(
              left: 18,
              child: Text(&quot;I am Jack&quot;)
          ),
          const Positioned(
            top: 18,
              child: Text(&quot;Your friend&quot;))
        ],
      ),
    );
  }
}</code>

Hello world:没有指定位置,根据stack的alignment来布局.
I am Jack:横轴设置了left,纵轴没有设置,则也是根据stack的alignment来布局,居中显示。
Your friend:设置了纵轴top,横轴则以stack的alignment来布局,居中显示。

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论