Flutter:堆组件Stack

xiaohai 2021-08-17 08:18:04 1983人围观 标签: Flutter 
简介堆组件Stack,其实该组件主要是用于每个子组件对其和定位。默认情况下Stack组件下的子组件都在左上角。

堆组件Stack,其实该组件主要是用于每个子组件对其和定位。默认情况下Stack组件下的子组件都在左上角。可以通过设置Stack的alignment属性来将所有的子组件的对其方式设置成top、right、left、bottom。

我们还可以通过Positioned组件来指定组件的位置,但是这个组件必须在Stack组件中使用。

本节我们还要学习另外一个组件就是IndexedStack组件,Index我们都知道表示索引,所以在一堆组件中,我们如果指定一个索引值,那么就会显示对应的那个组件,而其他组件将会影藏。

1、对其方式
import 'package:flutter/material.dart';

class DemoStack extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: <Widget>[
        Text(
          "Flutter",
          style: TextStyle(
            color: Colors.red,
          ),
        ),
        Container(
          width: 100.0,
          height: 100.0,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              border: Border.all(
            color: Colors.blue,
          )),
          child: Text("C"),
        ),
      ],
    );
  }
}

上面将Stack的对其方式设置成了topRight对其,所有上面的文本对其就在右上角。
图片alt

2、定位方式
import 'package:flutter/material.dart';

class DemoStack extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: <Widget>[
        Text(
          "Flutter",
          style: TextStyle(
            color: Colors.red,
          ),
        ),
        Container(
          width: 100.0,
          height: 100.0,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              border: Border.all(
            color: Colors.blue,
          )),
          child: Text("C"),
        ),
        Positioned(
          bottom: 0.0,
          right: 50.0,
          child: Text('XH'),
        ),
      ],
    );
  }
}

图片alt

3、IndexedStack组件使用
import 'package:flutter/material.dart';

class DemoStack extends StatefulWidget {
  @override
  _DemoStackState createState() => _DemoStackState();
}

class _DemoStackState extends State<DemoStack> {
  int index = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        IndexedStack(
          index: index,
          children: <Widget>[
            Text('Hello Flutter'),
            Text('Hello Dart'),
            Text('Hello Golang'),
            Text('Hello Python'),
          ],
        ),
        RaisedButton(
          child: Text('切换下一个'),
          onPressed: () {
            setState(() {
              index = index + 1;
              if (index >= 4) {
                index = 0;
              }
            });
          },
        )
      ],
    );
  }
}

图片alt