只能用于Row、Column和Flex布局中,可利用剩余空间进行占位,使用flex属性可以给多个Spacer按比例分配空间。

相关组件

Flex

Spacer基本使用

一个Spacer会占据可延伸区域
image.png

  1. import 'package:flutter/material.dart';
  2. class OneSpacer extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return
  6. Container(
  7. color: Colors.grey.withAlpha(33),
  8. child: Row(children: <Widget>[
  9. Container(
  10. alignment: Alignment.center,
  11. width: 100,
  12. height: 50,
  13. color: Colors.red,
  14. ),
  15. Spacer(),
  16. Container(
  17. alignment: Alignment.center,
  18. width: 60,
  19. height: 50,
  20. color: Colors.blue,
  21. ),
  22. ],),
  23. );
  24. }
  25. }

多个Spacer空间分配

【flex】 : 剩余空间分配占比 【int】
44.gif

import 'package:flutter/material.dart';
class ManySpacer extends StatefulWidget {
  @override
  _ManySpacerState createState() => _ManySpacerState();
}

class _ManySpacerState extends State<ManySpacer> {
  int _flexA=1;
  int _flexB=1;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _buildSliders(),
        Container(
          color: Colors.grey.withAlpha(33),
          child: Row(children: <Widget>[
            Spacer(flex: _flexA),
            Container(
              alignment: Alignment.center,
              width: 100,
              height: 50,
              color: Colors.red,
            ),
            Spacer(flex: _flexB),
            Container(
              alignment: Alignment.center,
              width: 60,
              height: 50,
              color: Colors.blue,
            ),
          ],),
        )
      ],
    );
  }

  Widget _buildSliders() {
    return Column(
      children: <Widget>[
        Slider(
            divisions: 20,
            min: 1,
            max: 10,
            label: "左边flex: $_flexA",
            value: _flexA.toDouble(),
            onChanged: (v) => setState(() => _flexA = v.round())
        ),
        Slider(
            divisions: 20,
            label: "右边flex: $_flexB",
            min: 1,
            max: 10,
            value: _flexB.toDouble(),
            onChanged: (v) => setState(() => _flexB = v.round())
        ),
      ],
    );
  }
}