• Flutter学习笔记(二)


    *、assets

    当引用图片的时候,需要在pubspec.yaml的文件中的flutter下添加assets,类似于下面的样子:
    image.png

    这里需要注意的是文件里的assets只要一个缩进即和flutter里的内容保持对齐,否则,会出问题。我遇到的是,没办法选择运行设备。

    一、Layout原理

    Flutter布局Layout的核心就是Widget。在Flutter里,基本上任何东西都是Widget,甚至布局的模型。比如images、icon、text等你能在界面上看到的。你看不到的,如Row、Column等也是Widget。
    复杂的Widget都是有单个widget组成的。

    下面是几个常用Widget
    • Container:
      容器Widget,允许自己定制一些子widget。其初始化如下:
    Container({
        Key key,
        this.alignment,
        this.padding,
        Color color,
        Decoration decoration,
        this.foregroundDecoration,
        double width,
        double height,
        BoxConstraints constraints,
        this.margin,
        this.transform,
     })
    

    可以发现,该UI Widget可以控制其中的Widget的padding、margin以及当前widget的宽高、border背景色等等。

    • Row:

      定义一行中的所有Widget和这些Widget的展示方式,包括主轴方向和副轴方向,具体的定义如下,其中MainAxisAlignment表示主轴方向(水平方向),CrossAxisAlignment表示副轴方向(和主轴垂直,即垂直方向):
      row-diagram.png
    Row({
        Key key,
        MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
        MainAxisSize mainAxisSize: MainAxisSize.max,
        CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
        TextDirection textDirection,
        VerticalDirection verticalDirection: VerticalDirection.down,
        TextBaseline textBaseline,
        List<Widget> children: const <Widget>[],
      })
    
    • Column:

      定义一列中的所有Widget和这些Widget的展示方式,也有主轴和副轴两个方向,具体的和Row相同,其定义如下:
      column-diagram.png
    Column({
        Key key,
        MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
        MainAxisSize mainAxisSize: MainAxisSize.max,
        CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
        TextDirection textDirection,
        VerticalDirection verticalDirection: VerticalDirection.down,
        TextBaseline textBaseline,
        List<Widget> children: const <Widget>[],
      })
    
    ps:主轴和副轴对于熟悉RN的人应该比较好理解

    二、Layout Widget(Container、MaterialApp、Scaffold)

    这里通过一个HelloWorld app来展示如何创建一个Widget并展示出来,并区分Material和非Material环境。
    hello_word.dart里的代码如下:

    class HelloWorld {
      static Widget helloWorld() {
        return new MaterialApp(
          title: 'Hello World',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new Scaffold(
            appBar: new AppBar(title: new Text('Hello World')),
            body: new Center(
                child: new Text(
              "Hello World",
              style: new TextStyle(fontSize: 32.0),
            )),
          ),
        );
      }
    
      static Widget hellWorldWithoutMaterial() {
        return new Container(
          decoration: new BoxDecoration(color: Colors.white),
          child: new Center(
            child: new Text(
              'Hello World',
              textDirection: TextDirection.ltr, // 这一句必须有
              style: new TextStyle(color: Colors.black, fontSize: 40.0),
            ),
          ),
        );
      }
    }
    

    而在展示上,主要的区别在于非Material下,没有Appbar、背景色和标题等,所有的内容都需要自定义。

    注意⚠️:

    1、Scaffold必须放在MaterialApp里面,否则会报错,大致如下:

    ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
    The following assertion was thrown building Scaffold(dirty, state: ScaffoldState#6f74d):
    No MediaQuery widget found.
    Scaffold widgets require a MediaQuery widget ancestor.
    The specific widget that could not find a MediaQuery ancestor was:
    Scaffold
    The ownership chain for the affected widget is:
    Scaffold ← MyApp ← [root]
    Typically, the MediaQuery widget is introduced by the MaterialApp or WidgetsApp widget at the top of
    your application widget tree.
    

    2、非Material下Text的textDirection属性是必须的

    ??????到底什么是Material App?

    三、在水平和垂直方向上Layout(Row、Column)

    1、水平布局:

    class LayoutImagesH {
      static layoutImagesH() {
        MaterialApp material = new MaterialApp(
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text(
                "Images H Layout",
                style: new TextStyle(color: Colors.white, fontSize: 20.0),
              ),
            ),
            body: _getLayoutContainer(),
          ),
        );
        return material;
      }
    
      static _getLayoutContainer() {
        Row row = new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            _getRowsImage('images/pic1.jpg'),
            _getRowsImage('images/pic2.jpg'),
            _getRowsImage('images/pic3.jpg')
          ],
        );
        Container container = new Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.grey,
          child: row,
        );
        return container;
      }
    
      static _getRowsImage(imageStr) {
        return new Image.asset(
          imageStr,
           100.0,
        );
      }
    }
    

    2、垂直布局

    class LayoutImagesV {
      static layoutImagesVSpaceEvenly() {
        return new Container(
          color: Colors.green,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Image.asset('images/pic1.jpg'),
              new Image.asset('images/pic2.jpg'),
              new Image.asset('images/pic3.jpg'),
            ],
          ),
        );
      }
      static layoutImagesVSpaceAround() {
        return new Container(
          color: Colors.green,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Image.asset('images/pic1.jpg'),
              new Image.asset('images/pic2.jpg'),
              new Image.asset('images/pic3.jpg'),
            ],
          ),
        );
      }
      static layoutImagesVSpaceBetween() {
        return new Container(
          color: Colors.green,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Image.asset('images/pic1.jpg'),
              new Image.asset('images/pic2.jpg'),
              new Image.asset('images/pic3.jpg'),
            ],
          ),
        );
      }
    }
    

    主轴的枚举如下:

    enum MainAxisAlignment {
      start,
      end,
      center,
      /// 第一个和最后一个贴边,中间的平分
      spaceBetween,
      /// 第一个和最后一个距离边的距离是它与中间的距离的一半
      spaceAround,
      /// 完全平分
      spaceEvenly,
    }
    

    四、按比例布局(Expanded)

    使用Expanded Widget,它继承自Flexible,主要是通过其中flex属性来控制,默认整个Expanded里的flex都是1,即平分。我们可以通过控制flex来控制每个Widget所占的大小。

    先来看一个现象:
    image.png

     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    边上黄条是什么鬼,这里用的代码还是上面提到的水平方向的布局,代码里只是修改了图片,就变成了这个鬼样子。

    经过尝试,你会发现,只要总尺寸超过了容器的限制,就会出现这种问题。要解决这种问题,目前来看,一是控制图片的尺寸,一个就是使用Expanded 的Widget。

    代码如下:

    class ExpandedImages {
      static expandedImages() {
        return new Container(
          color: Colors.green,
    //      margin: const EdgeInsets.all(15.0),
          child: new Row(
            textDirection: TextDirection.ltr,
    //        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: _getRowChildren(),
          ),
        );
      }
      static expandImagesWithMaterial() {
          return new MaterialApp(
            home: new Scaffold(
              appBar: new AppBar(
                  title: new Text('Expanded')
              ),
              body: new Center(
                child: new Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: _getRowChildren(),
                ),
              )
            ),
          );
      }
      static _getRowChildren() {
        return [
    //      new Expanded(child: new Image.asset("images/pic1.jpg")),
    //      new Expanded(flex:2, child: new Image.asset("images/pic2.jpg")),
    //      new Expanded(child: new Image.asset("images/pic3.jpg"))
          new Expanded(child: new Image.asset("images/expand1.jpg")),
          new Expanded(flex:2, child: new Image.asset("images/expand2.jpg")),
          new Expanded(child: new Image.asset("images/expand3.jpg"))
        ];
      }
    }
    
    最后的效果如下图所示:
    image.png

    看到这里其实也明白了,上面的水平方向和垂直方向的布局是有问题的。

    五、压缩空间

    一般的Row和Column的布局都是尽可能大的利用Space,如果此时不想要这些space,那么可以使用相应的mainAxisSize的值来控制,它只有min和max两个值,默认是max,即我们看见的那种情况。如果设置了该值为min,那么mainAxisAlignment的后面的几个值对其不再起作用。
    下面是测试代码:

    class _MyHomePageState extends State<_MyHomePage> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return new Scaffold(
          appBar: new AppBar(title: new Text("Packing Widget")),
          body: new Center(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              mainAxisSize: MainAxisSize.min,
    //          crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                new Icon(Icons.star, color: Colors.green[500]),
                new Icon(Icons.star, color: Colors.green[500]),
                new Icon(Icons.star, color: Colors.green[500]),
                new Icon(Icons.star, color: Colors.grey),
                new Icon(Icons.star, color: Colors.grey),
              ],
            ),
          )
        );
      }
    }
    

    六、常用的Widget

    总体来说,所有的Widget可以分为两类:Standard Widget和Material Component。Standard Widget可以在Material App和非Material App中使用,但是Material Component只能在Material App中使用。

    1、Standard Widget

    常用的是下面四种:

    • Container
      为Widget添加内边距padding, 外边距margins, 边框borders, 背景色background color和其他的一些修饰信息。
    • GridView
      将其中的Widget按照Grid的形式展示,并且是可滑动的。(似乎和UICollectionView相似)。
    • ListView
      将其中的Widget按照List形式展示,并且是可滑动的。(似乎和UIScrollView、UITableView相似)。
    • Stack
      在Widget上覆盖一个Widget

    2、Material Component

    • Card
    • ListTitle
  • 相关阅读:
    python_day_5:20180720
    python_day_4:20180719
    2018悦读
    2018生活
    心理画
    js 策略模式
    js 单例模式
    js 模板方法模式
    C语言-数据类型
    js 观察者模式
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/10528928.html
Copyright © 2020-2023  润新知