Flutter Expanded组件实现自适应布局

发布于 1周前 作者 phonegap100 最后一次编辑是 5天前 来自 分享

Flutter Expanded类似Web中的Flex布局,可以简便、完整、响应式地实现各种页面布局。

属性 说明
flex 元素站整个父Row /Column的比例
child 子元素
比如我们想实现下面布局 左侧占2份 右侧占3份,这个时候就可以使用Flutter Expanded组件实现弹性布局

expand.jpg

import 'package:flutter/material.dart';

import 'res/listData.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FlutterDemo')),
        body: LayoutDemo(),
      ));
  }
}
class LayoutDemo extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {    
    return Padding(
      padding: EdgeInsets.all(10),
      child: Row(
        // crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(flex:2,child: IconContainer(Icons.home)),  
          SizedBox(width: 10),          
          Expanded(flex: 3,child: IconContainer(Icons.search)),   
          // SizedBox(width: 10),       
          // Expanded(child: IconContainer(Icons.send))         
        ],
      ),
    )
    
     
    ;
  }
}

class IconContainer extends StatelessWidget{

  double size;  
  IconData icon;
  IconContainer(this.icon,{this.size}){
    this.size=32.0;
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(      
      width: 100.0,
      height: 100.0,
      color: Colors.blue,
      child: Center(child: Icon(this.icon,color:Colors.white,size:this.size))    
    );
  }
  
}
使用Flutter Expanded组件实现如下图的自适应布局

expand2.jpg

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {   
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(title: Text('FlutterDemo')),
      body: LayoutDemo(),
    ));
  }
}

class LayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(         
        children: <Widget>[
          Expanded(
            flex: 1,
            child: IconContainer(Icons.home,color: Colors.orange),  
          ),
          IconContainer(Icons.search,color: Colors.blue)
               
        ],    
    );
  }
}


class IconContainer extends StatelessWidget{
  //定义属性的时候在类型后面加一个? 表示把当前属性定义成可空类型属性  
  Color? color=Colors.red;
  double? size=32.0;
  IconData icon;
  IconContainer(this.icon,{this.color,this.size});
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      height: 100.0,
      width: 100.0,
      color: this.color,
      child: Center(
        child: Icon(this.icon,size: this.size,color: Colors.white)
      ),
    );
  }
}
回到顶部