Simple use of ImageView, ListView and GridView in Flutter


Learn a little record of Flutter, mainly because I am afraid that I will forget~

Basic Shortcuts

In Android studio

  1. First enter the command in Terminal to run the project

    flutter run
    
  2. To show the grid press the P key

  3. Switch ios display by pressing the O key

  4. Hot update button is command+\

VScode

  1. flutter runRun the project with

  2. p displays the grid, o is to switch between Android and ios systems

  3. Press the r key to hot update.

  4. Delete a line: command+shift+k

  5. Copy a line: shift+option+⬆️ or ⬇️

  6. Hold option and click: select multiple cursors

  7. To create a new project, you need to use the command under Terminal
    flutter create 项目名称,

Flutter control-ImageView

  • Look at the basic code
void main() => runApp(WudanImageViewPage());

class WudanImageViewPage extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      title: 'Class Name',
      home: Scaffold(
        appBar: AppBar(title: Text('UIImageView')),
        body: Center(
          child: Image.network(//加载的是网络的图片
            "url",
            fit: BoxFit.cover,//fit 填充方式很多种
          ),
        ),
      ),
    );
  }
}
  • loading method

    1. Image.asset: Load resource images, that is, to load images in the project resource directory. Adding images will increase the volume of the package, using relative paths.
    2. Image.network: network resource image
    3. Image.file: Loading a local image means loading an image from a local file. This is an absolute path and has nothing to do with the package body.
    4. Image.memory: load Uint8List resource image
  • fit property

    The fit property can control the stretching and squeezing of the picture, which are all based on the parent container of the picture. Look at a few commonly used

    BoxFit.fill:Full image display, the image will be stretched to fill the parent container.

    BoxFit.contain: Full image display, showing the original scale, there may be gaps.
    BoxFit.cover: The display may be stretched, cropped, and filled (the picture must fill the entire container without deformation).

    BoxFit.fitWidth: Full width (full horizontally), the display may be stretched or cropped.

    BoxFit.fitHeight: Full height (full vertically), the display may be stretched or cropped.

    BoxFit.scaleDown: The effect is similar to contain, but this attribute does not allow the display to exceed the size of the source image, which can be small or large.

  • image blending mode

    The image blending mode (colorBlendMode) and the color attribute are used together to change the color of the image. There are many modes in it, and the effects produced are also very rich.

    child: Image.network(
      'url,
        color: Colors.greenAccent,
        colorBlendMode: BlendMode.darken,
    ),
    

Flutter control-ListView

  • Basic operation - vertical list display

    import 'package:flutter/material.dart';
    void main() => runApp(MyApp());
    class MyApp extends StatelessWidget {
          
          
      
      Widget build(BuildContext context) {
          
          
        return MaterialApp(
            title: 'text widget',
            home: Scaffold(
              appBar: AppBar(title: Text('flutter hot')),
              body: new ListView(
                children: <Widget>[//数组,里面是单个的条目
                  new ListTile(
                    leading: new Icon(Icons.access_alarm),
                    title: new Text("这是一个闹钟")
                  ), new ListTile(
                    leading: new Icon(Icons.perm_camera_mic),
                    title: new Text("perm_camera_mic")
                  ), new ListTile(
                    leading: new Icon(Icons.call_end_rounded),
                    title: new Text("call_end_rounded")
                  ),
                ],
              )
            ));
      }
    }
    
  • Basic operation - horizontal list display

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
          
          
      
      Widget build(BuildContext context) {
          
          
        return MaterialApp(
            title: 'text widget',
            home: Scaffold(
              appBar: AppBar(title: Text('ListView')),
              body: Center(
                child: Container(//指定一个外层的容器
                height: 200.0,
                child: new ListView(
                  scrollDirection: Axis.horizontal,//指定横向
                  children:<Widget> [//子条目是一个个容器
                    new Container(
                      width: 180.0,
                      color: Colors.greenAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.blueAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.yellowAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.redAccent,
                    ),
                  ],
                ),
                ),
              )
            ));
      }
    }
    

    Axis is an enumerated type

    enum Axis {
          
          
      /// Left and right.
      ///
      /// See also:
      ///
      ///  * [TextDirection], which disambiguates between left-to-right horizontal
      ///    content and right-to-left horizontal content.
      horizontal,
    
      /// Up and down.
      vertical,
    }
    
  • Basic operation - dynamic list display

    1. Use of List type

      List is one of Dart's collection types. In fact, you can simply understand it as an array (I think so anyway), and other languages ​​​​also have this type. It can be declared in several ways:

      • var myList = List(): A statement of variable length.
      • var myList = List(2): A statement of fixed length.
      • var myList= List<String>(): The declaration method of the fixed type.
      • var myList = [1,2,3]: Direct assignment to List.

      What we use here is a List transfer, and then directly use the methods in the List generateto produce the elements in the List. The final result is to produce a List variable with a value. code show as below:

      void main () => runApp(MyApp(
        items: new List<String>.generate(1000, (i)=> "Item $i")//generate是对list赋值
      ));
      

      generate method

      The first specifies the length, the second parameter is the method

      List.generate(int length, String Function(int) generator, {
              
              bool growable = true})
      
    2. Reception of parameters

      • code show as below:
      final List<String> items;//声明一个成员变量
       MyApp({
              
              Key key,  this.items}):super(key:key);
      

      This is a constructor. In addition to Key, we added a parameter that must be passed, which @requiredmeans that it must be passed. :superIf the parent class does not have a default constructor with no name and no parameters, the subclass must manually call a parent class constructor.

      In this way, we can receive a passed parameter, of course we have to declare it in advance.

      • report error

        The parameter 'key' can't have a value of 'null' because of its type 'Key', but the implicit default value is 'null'.
        Try adding either an explicit non-'null' default value or the 'required' modifier.
          MyApp{
                  
                  Key key, this.title}) : super(key: key);
          
        

        This is because the flutter version upgrade adds a null judgment to the relevant calling class construction method .

        We can use the official recommended modification method to modify the key? key to indicate that it can be empty, and because title is a final modifier, the final modified constant must be initialized in the declaration or initialized in the constructor, and its value can be dynamically calculated. So you can add the required modifier to require that it must be filled in as a parameter.

        after modification

         MyApp({
                  
                  Key? key, this.items}):super(key: key);
        
      1. The complete code is as follows

        import 'package:flutter/material.dart';
        
        void main() => runApp(MyApp(
          items: new List<String>.generate(1000, (i) => 'item is ${
                    
                    i}'),
        ));
        
        class MyApp extends StatelessWidget {
                  
                  
        
          final List<String>? items;
          
          //构造 传递参数Key 是默认参数
          MyApp({
                  
                  Key? key, this.items}):super(key: key);
          
          
          Widget build(BuildContext context) {
                  
                  
            return MaterialApp(
                title: 'text widget',
                home: Scaffold(
                  appBar: AppBar(title: Text('ListView')),
                  body: new ListView.builder(//利用builder 来创建列表
                    itemCount: items!.length,
                    itemBuilder: (context,index){
                  
                  
                      return new ListTile(
                        title: new Text('${
                    
                    items![index]}'),
                      );
                    },
                  )
                ));
          }
        } 
        
  • Extract defined components

    The defined ListView can be encapsulated to make the code structure concise, for example:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
          
          
      
      Widget build(BuildContext context) {
          
          
        return MaterialApp(
            title: 'text widget',
            home: Scaffold(
              appBar: AppBar(title: Text('ListView')),
              body: Center(
                child: Container(//指定一个外层的容器
                height: 200.0,
                child:new MyListView() ,//将上边的例子封装一个widget
                ),
              )
            ));
      }
    }
    
    class MyListView extends StatelessWidget{
          
          
      
      Widget build(BuildContext context) {
          
          
       
        return new ListView(
                  scrollDirection: Axis.horizontal,//指定横向
                  children:<Widget> [//子条目是一个个容器
                    new Container(
                      width: 180.0,
                      color: Colors.greenAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.blueAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.yellowAccent,
                    ),  new Container(
                      width: 180.0,
                      color: Colors.redAccent,
                    ),
                  ],
                );
      }
    }
    

Flutter control-GridView

  1. basic use

    code show as below

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
          
          
      
      Widget build(BuildContext context) {
          
          
        return MaterialApp(
            title: 'text widget',
            home: Scaffold(
                appBar: AppBar(title: Text('ListView')),
                body: GridView.count(
                  crossAxisCount: 3, //横向是三列
                  padding: const EdgeInsets.all(10.0),//内边距设置
                  crossAxisSpacing: 5, //网格间的横向边距
                  children: const [
                    Text("这是第一个元素"),
                    Text("这是第二个元素"),
                    Text("这是第三个元素"),
                    Text("这是第四个元素"),
                    Text("这是第五个元素"),
                  ], //填充数据
                )));
      }
    }
    
  2. The way to use GridView construction directly

    • SliverGridDelegateWithFixedCrossAxisCountYou can directly specify how many items are displayed in each row (column),

      Two of these properties:

      main axis

      • mainAxisSpacing: 2.0,//The interval size of the main axis
      • mainAxisExtent: 100,//The length of the main axis
    • SliverGridDelegateWithMaxCrossAxisExtentIt will automatically calculate how many items are displayed in each row according to the width of the GridView and the width of each one you set

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
          
          
      
      Widget build(BuildContext context) {
          
          
        return MaterialApp(
            title: 'text widget',
            home: Scaffold(
                appBar: AppBar(title: Text('GridView')),
                body: GridView(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing: 2.0,//主轴的间隔大小
                      mainAxisExtent: 100,//主轴的长度
                      crossAxisSpacing: 2.0,//横向的间隔
                      childAspectRatio: 0.7),//横竖比
                  children: [//子条目
                    Image.network(
                        'http://img5.mtime.cn/mt/2018/10/22/104316.77318635_180X260X4.jpg',
                        fit: BoxFit.cover),
                    Image.network(
                        'http://img5.mtime.cn/mt/2018/10/10/112514.30587089_180X260X4.jpg',
                        fit: BoxFit.cover),
                    Image.network(
                        'http://img5.mtime.cn/mt/2018/11/13/093605.61422332_180X260X4.jpg',
                        fit: BoxFit.cover),
                    Image.network(
                        'http://img5.mtime.cn/mt/2018/11/07/092515.55805319_180X260X4.jpg',
                        fit: BoxFit.cover),
                  ],
                )));
      }
    }
    

Guess you like

Origin blog.csdn.net/MrLizuo/article/details/124621037