1. Start of flutter

1. Know folders

Folder name role
android Android platform related code
ios Ios platform related code
lib Flutter code, the main code to be written into the folder
test Used to store test code
pubspec.yaml Configuration files, project-related information, generally stored third-party library dependencies

2. Entry file/entry method

Dart entry file: The main. Dart entry file of a Flutter project is found in its lib directory

The entry method: in the main.dart file

void main() {
  runApp(MyApp());
}
// You can also abbreviate it
void main()=>runApp(MyApp());
Copy the code

The main method is the dart entry method. The runApp method is the entry method of a flutter. MyApp is a custom component.

2, flutter basic

Start with the basics.

1, the Helloworld

import 'package:flutter/material.dart';

void main() {
  runApp( Center(
    child: Text(
      'CDX',
      textDirection: TextDirection.ltr,
    )
  ));
}
Copy the code

Effect:

2. Custom components

Custom components in the flutter is actually a class, the class needs to inherit StatelessWidget/StatefulWidget.

StatelessWidget: a stateless component whose state is immutable.

StatefulWidget: A stateful component that holds a state that may change during the widget’s life cycle.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Text(
      'CDX111',
      textDirection: TextDirection.ltr,
      style: TextStyle(
        fontSize: 40.0, color: Colors.yellow, ), )); }}Copy the code

Effect:

3. Component: MaterialApp/Scaffold

1. The MaterialApp component is a convenient Widget that encapsulates some of the widgets your application needs to implement Material Design. Typically used as a top-level widget.

2. The Scaffold component is the basic implementation of the Material Design layout structure. This class provides apis for displaying drawers, snackbars, and bottom sheets.

Block of code:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: HomeContent(), ), ); }}Copy the code
class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Text(
      'CDX111',
      textDirection: TextDirection.ltr,
      style: TextStyle(
        fontSize: 40.0, color: Colors.yellow, ), )); }}Copy the code

Complete code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: HomeContent(), ), ); }}class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Text(
      'CDX111',
      textDirection: TextDirection.ltr,
      style: TextStyle(
        fontSize: 40.0, color: Colors.yellow, ), )); }}Copy the code

Effect:

4. Component: Container/Text

1. Container components

This component can be thought of as a div before us, but it is actually an object. Let’s look at its constructor.

Container Component property description

The property name type instructions
key Key Container identifier used to find updates
alignment AlignmentGeometry Controls the alignment of the child. This property takes effect if the Container or its parent is larger than the child’s size. There are many ways to align the child
padding EdgelnsetsGeometry The empty area inside the Decoration, if there is a child, which is inside the padding
color Color Contain background color, if set to foregroundDecoration, may cover the color effect
decoration Decoration If “Decoration” is set behind child, the color attribute cannot be set. Otherwise, an error will be reported. In this case, the color should be set in “Decoration”
foregroundDecoration Decoration Decoration painted in front of child
width double The width of the Container is set to double. Infinity forces the Container to be full. If it is not set, the Container will be arranged according to both the child and the parent
height double The Container height is set to double. Infinity forces the Container to be full in height
constraints BoxConstraints Add additional constraints to child
margin EdgelnsetsGeometry The blank area surrounding Decoration and child does not belong to the content area
transform Matrix4 Set the transformation matrix of Container to Matrix4
child Widget Content widgets in containers

2. Text component

Text Component property description

The property name type The default value instructions
data String Data is the text to be displayed
maxLines int 0 The maximum number of lines of text to display
style TextStyle null Text style, can define text font size, color, thickness, etc
textAlign TextAlign TextAlign.center Horizontal text alignment. The value can be center, end, justify, left, right, start, or values
textDirection TextDirection TextDirection.ltr Direction of text writing. LTR from left to right, RTL from right to left
textScaleFactor double 1.0 Font scaling factor
textSpan TextSpan null Text block

3, sample

// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: HomeContent(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Text(
          'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
          textAlign: TextAlign.center,
          overflow: TextOverflow.fade,
          style: TextStyle(
              fontSize: 16.0,
              color: Colors.red,
              fontWeight: FontWeight.w700,
              fontStyle: FontStyle.italic,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.white,
              decorationStyle: TextDecorationStyle.dashed),
        ),
        height: 300.0,
        width: 300.0,
        decoration: BoxDecoration(
            color: Colors.green,
            border: Border.all(color: Colors.blue, width: 2.0),
            borderRadius: BorderRadius.all(Radius.circular(150))
            ),
            transform: Matrix4.rotationZ(0.3),),); }}Copy the code

Effect:

5. Picture component

Basic code block :(code base part of this section, the rest of the effect display code are in HomeContent)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: HomeContent(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1, the introduction

1. New Image: Get the Image from ImageProvideer

2, new image. asset: load the Image of the resource

3. New image. file: load the local Image file

4, New Image.netWork: load network image

New Image. Memory: Load Uint8List resource Image.

Image Component property description

The property name type instructions
image ImageProvider Abstract class, need to achieve their own image data operations
width/hei ght double Image Sets the width and height of the display area
fit Boxfit Image fill mode
color Color The picture color
colorBlendMode BlendMode When you manually manipulate an image, you may use image blending to change the color of the image. This property mixes colors.
alignment Alignment Control the placement of pictures
repeat ImageRepeat Set image repetition mode
centerSlice Rect Use when the image needs to be stretched
matchTextDirection booI This property is used with Directionlity
gaplessPlayback bool Whether the display of the original image remains during the reloading process after the ImageProvide changes

BoxFit Value description

The values describe
Boxfit.fill Full view display, display may stretch, full
Boxfit.contain Full picture display, display the original scale, do not need to fill
Boxfit. cover Display may stretch, may crop, fill
BoxFit.fitWidth Display may stretch, may crop, width full
BoxFit.fitHeight Display may stretch, may crop, highly filled
Boxfit.none Original size
BoxFit.scaleDown Contain is similar to boxfit. contain, but does not allow it to contain more than the size of the source image

2. Remote picture examples

mage.network(src)

A simple example:

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Image.network(
          "Https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1675144683, & FM = 26 & gp = 0. 641372710 JPG",
        colorBlendMode: BlendMode.screen,
        fit: BoxFit.cover,),
        width: 300,
        height: 300, decoration: BoxDecoration( color: Colors.green, ), ), ); }}Copy the code

Effect:

3. Realize rounded corners and round pictures

1. Implement with borderRadius and BoxFit.cover

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
      width: 300,
      height: 300,
      decoration: BoxDecoration(
        color: Colors.green,
        borderRadius: BorderRadius.circular(150),/ / * * * * * * * * *
        image: DecorationImage(
          image: NetworkImage(      "Https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1675144683, & FM = 26 & gp = 0. 641372710 JPG",
          ),
          fit: BoxFit.cover,/ / * * * * * * * * * * * *),),)); }}Copy the code

Effect:

2, use ClipOval implementation

1, first look at the effect of clipOval processing

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
          child: ClipOval(
            child: Image.network("Https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1675144683, & FM = 26 & gp = 0. 641372710 JPG",),))); }}Copy the code

Effect:

2. Continue to get rounded

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
          child: ClipOval(
            child: Image.network("Https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1675144683, & FM = 26 & gp = 0. 641372710 JPG",
            height: 300,
            width: 300, fit: BoxFit.cover,), ), )); }}Copy the code

Effect:

2. Local images

1. Create related folders and modify configuration files

2, sample

1, code,

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
          child: Image.asset("images/1.jpg"))); }}Copy the code

Effect of 2,

6. List components

Basic code block :(code base part of this section, the rest of the effect display code are in HomeContent)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: HomeContent(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1, the introduction

There are roughly the following categories of lists

1. Horizontal lists

2. Vertical lists

3. A very large list of data

Matrix list

Basic properties of the ListView component

The property name type The default value instructions
scrollDirection Axis Axis.vertical Axis. Vertical is the default value for the vertical method and Axis. Horizontal is the horizontal method
padding EdgelnsetsGeometry The empty area inside the list, if there is a child, inside the padding
reverse bool false Components in reverse order
children List List elements, notice that List elements are all widgets

2. Vertical lists

Code:

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        ListTile(
          leading: Image.asset("images/1.jpg"),
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),
        ),
        ListTile(
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),
          trailing: Icon(Icons.search),
        ),
        ListTile(
          leading: Icon(Icons.padding),
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),
        ),
        ListTile(
          leading: Icon(Icons.games),
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),
        ),
        ListTile(
          leading: Icon(Icons.ac_unit_sharp),
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),
        ),
        ListTile(
          leading: Icon(Icons.tab),
          title: Text("xxxxxxxxxxxxxxxxxxxxx"),
          subtitle: Text("ccccccccccccccccccc"),),,); }}Copy the code

Effect:

3. Horizontal lists

Code:

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child:ListView(
      scrollDirection: Axis.horizontal,
      children: <Widget>[
        Container(
          width: 100,
          height: 100,
          color: Colors.green,
        ),
        Container(
          width: 100,
          height: 100,
          color: Colors.blue,
        ),
        Container(
          width: 100,
          height: 100,
          color: Colors.red,
        ),
        Container(
          width: 100,
          height: 100,
          color: Colors.grey,
        ),
        Container(
          width: 100,
          height: 100, color: Colors.deepOrange, ), ], ) ); }}Copy the code

Effect:

4. Dynamic lists

Code:

class HomeContent extends StatelessWidget {
  List<Widget> getData() {
    List<Widget> list = new List(a);for (var i = 1; i <= 7; i++) {
      list.add(ListTile(
        title: Text("xxxxxx$iA"))); }return list;
  }
  @override
  Widget build(BuildContext context) {
    return Container(child: ListView(children: this.getData())); }}Copy the code

ListView.builder

class HomeContent extends StatelessWidget {
  List list = new List(a); HomeContent() {for (var i = 1; i <= 7; i++) {
      list.add("xxxxxx$iA"); }}@override
  Widget build(BuildContext context) {
    return Container(child: ListView.builder(
      itemCount: this.list.length,
      itemBuilder: (context,index){
        return ListTile(
          title: Text(this.list[index]), ); })); }}Copy the code

Effect:

7. GridView component

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

GridView component properties and description

The property name type The default value instructions
scrollDirection Axis Axis.vertical The scrolling direction can be vertical or horizontal. The default scrolling direction is vertical
reverse bool false The default scroll is up or left down or right. This property controls whether the scroll is reversed. The default is false, which means no reverse scrolling
controller ScrollController Controls the position of the child when scrolling
primary bool Is the primary scroll view associated with the parent’s PrimaryScrollcontroller
physics ScrollPhysics How does a scrolling view respond to user input
shrinkWrap bool false Whether the scrolling view content of the scrolling direction should be determined by what is being viewed
padding EdgeinsetsGeometry The blank area around
gridDelegate SliverGridDelegate Delegate to control the GridView neutron node layout
cacheExtent double Cache region

1. Grid layout via GridView.count

Code:

class Demo extends StatelessWidget {
  List<Widget> getData() {
    List<Widget> list = new List(a);for (var i = 0; i < 20; i++) {
      list.add(Container(
        alignment: Alignment.center,
        child: Text(
          'xxxxx $i xxxx',
          style: TextStyle(color: Colors.white,fontSize: 20),
        ),
        color: Colors.blue,
      ));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisSpacing: 10.0.// Level the distance between the child widgets
      mainAxisSpacing: 10.0.// Vertical distance between widgets
      padding: EdgeInsets.all(10),
      crossAxisCount: 3.// Controls how many widgets are in a row
      childAspectRatio: 0.7.// Ratio of width to height
      children: this.getData(), ); }}Copy the code

Effect:

2, through GridView. Builder to achieve grid layout

Code:

class Demo extends StatelessWidget {
  Widget getData(context, index) {
    return Container(
      child: Column(
        children: <Widget>[
          Image.asset("images/1.jpg"),
          SizedBox(height: 12),
          Text(
            "xxxxxxxx",
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 20),
          )
        ],
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.blue, width: 1),),); }@override
  Widget build(BuildContext context) {
    return GridView.builder(
      // padding: EdgeInsets.all(10),
      // crossAxisCount: 3, // Controls how many widgets are in a row
      // childAspectRatio: 0.7,// Ratio of width to height
      // children: this.getData(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisSpacing: 10.0.// Level the distance between the child widgets
        mainAxisSpacing: 10.0.// Vertical distance between widgets
        crossAxisCount: 3.// Controls how many widgets are in a row
      ),
      itemCount: 10,
      itemBuilder: this.getData, ); }}Copy the code

Effect:

8, page layout Padding/Row/Column/Expanded

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

GridView component properties and description

1. Padding component

Common layout tags in HTML have the padding property, but many widgets in Fliuuter don’t. We can use the Padding component to handle the spacing between the container and the child elements

attribute instructions
padding Padding, EdgeInsetss set the padding value
child Child components

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GridView.count(
      padding: EdgeInsets.fromLTRB(0.0.10.0),
      crossAxisCount: 3.// Controls how many widgets are in a row
      childAspectRatio: 1.7.// Ratio of width to height
      children: <Widget>[
        Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,),
        ),
         Padding(
          padding: EdgeInsets.fromLTRB(10.10.0.0),
          child: Image.asset("images/1.jpg",fit: BoxFit.cover,), ), ], ); }}Copy the code

Effect:

2. Row layout components horizontally

Properties:

attribute instructions
mainAxisAlignment The way the principal axis is sorted
crossAxisAlignment The way the subaxis is sorted
children Component child element

Column vertical layout components

Implement an icon component: Implement incoming ICONS (color and size dynamics)

Code:

class IconDemo extends StatelessWidget {
  double size = 32.0;
  Color color = Colors.red;
  IconData icon;
  IconDemo(this.icon, {this.color, this.size});
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100.0,
      width: 100.0,
      color: this.color,
      child: Center(
        child: Icon(
          Icons.home,
          size: 32, color: Colors.white, ), ), ); }}Copy the code

Test the Row ordering with the above components

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 600.0,
      width: 600.0, child:Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ IconDemo( Icons.home, color: Colors.green, ), IconDemo( Icons.search, color: Colors.red, ), IconDemo( Icons.fit_screen, color: Colors.green, ), ], ) ); }}class IconDemo extends StatelessWidget {
  double size = 32.0;
  Color color = Colors.red;
  IconData icon;
  IconDemo(this.icon, {this.color, this.size});
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100.0,
      width: 100.0,
      color: this.color,
      child: Center(
        child: Icon(
          Icons.home,
          size: 32, color: Colors.white, ), ), ); }}Copy the code

Effect:

Expanded Components

Expanded components in Flutter are similar to Flex layouts in the Web

Expanded can be used in Row and Column layouts

attribute instructions
flex The ratio of the element to the entire parent Row/Column
child Child elements

Code :(does not contain the code for the IconDemo component above)

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded(
          flex: 1,
          child: IconDemo(
            Icons.home,
            color: Colors.green,
          ),
        ),
        Expanded(
          flex: 2, child: IconDemo( Icons.search, color: Colors.red, ), ), ], ); }}Copy the code

Effect:

5. Related cases

Implement a layout similar to the following figure

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Container(
                height: 200,
                color: Colors.blue,
                child: Text("xxxxxxxxxx"),
              ),
            )
          ],
        ),
        SizedBox(height: 10),
        Row(children: <Widget>[
          Expanded(
              flex: 2,
              child: Container(
                  height: 180,
                  child: Image.asset(
                    "images/1.jpg",
                    fit: BoxFit.cover,
                  ))),
          Expanded(
              flex: 1,
              child: Container(
                  height: 180,
                  child: ListView(children: <Widget>[
                    Container(
                        height: 85,
                        child: Image.asset(
                          "images/1.jpg",
                          fit: BoxFit.cover,
                        )),
                    SizedBox(height: 10),
                    Container(
                        height: 85,
                        child: Image.asset(
                          "images/1.jpg", fit: BoxFit.cover, )) ]))), ]), ], ); }}Copy the code

Effect:

Stack with Aligin/Stack with Aligin

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1. Stack components

attribute instructions
alignment Configure the display position of all child elements
children Child components

Stack effects: A bit like element overlap, text and container effects are shown below

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          height: 400,
          width: 300,
          color: Colors.red,
        ),
        Text("xxxxxxxxxxx")],); }}Copy the code

Effect:

The position is moved using the alignment attribute

It could be coordinates

alignment: Alignment(0.0),

Copy the code

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      // alignment: Alignment.center,
      / / alignment, alignment (0, 0),
      alignment: Alignment.center,
      children: <Widget>[
        Container(
          height: 400,
          width: 300,
          color: Colors.red,
        ),
        Text("xxxxxxxxxxx")],); }}Copy the code

Effect:

2, the align/positiond

If there are two texts in the stack above, the two texts will overlap as follows:

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      // alignment: Alignment.center,
      / / alignment, alignment (0, 0),
      alignment: Alignment.center,
      children: <Widget>[
        Container(
          height: 400,
          width: 300,
          color: Colors.red,
        ),
        Text("xxxxxxxxxxx"),
        Text("ddddddddddd"),]); }}Copy the code

Effect:

Use the align

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 400,
        width: 400,
        color: Colors.blue,
        child: Stack(children: <Widget>[
          Align(
            alignment: Alignment.topLeft,
            child:  Icon(Icons.help, size: 40, color: Colors.white),
          ),
          Align(
            alignment: Alignment.center,
            child: Icon(Icons.search, size: 40, color: Colors.white),
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: Icon(Icons.home_filled, size: 40, color: Colors.white), ), ]), ), ); }}Copy the code

Effect:

Using positiond
attribute instructions
top Distance of the child element from the top
bottom Distance of child element from bottom
left Distance of child element from left
right The distance to the right of the child element
child Child components

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 400,
        width: 400,
        color: Colors.blue,
        child: Stack(children: <Widget>[
          Positioned(
            left: 10,
            child:  Icon(Icons.help, size: 40, color: Colors.white),
          ),
          Positioned(
            bottom: 0,
            child: Icon(Icons.search, size: 40, color: Colors.white),
          ),
          Positioned(
            right: 0,
            child: Icon(Icons.home_filled, size: 40, color: Colors.white), ), ]), ), ); }}Copy the code

Effect:

AspectRatio /Card components

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1, AspectRatio

AspectRatio adjusts the AspectRatio of the child element according to the Settings.

AspectRatio will first expand as much as layout restrictions allow. The width of a widget is determined by its width and ratio, similar to a BoxFit folder, which uses a fixed ratio to contain as much space as possible.

If a viable size cannot be found after all the constraints have been met, AspectRatio will eventually preferentially accommodate the layout constraints, ignoring the ratio set

attribute instructions
aspectRatio The width to height ratio may not be laid out according to this value. It depends on comprehensive factors and whether the outer layer is allowed to be laid out in accordance with this ratio. This is only a reference value
child Child components

Code :(example of length being twice as tall)

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200,
      child: AspectRatio(
        aspectRatio: 2.0/1.0.// The outer container is 200 long and 100 highchild: Container( color: Colors.red, ), ), ); }}Copy the code

2, Card

A Card is a Card component block whose content can be made up of most types of widgets. The Card has rounded corners and shadows to make it look three-dimensional.

attribute instructions
margin From the outside
child Child components
Shape Card shadow effect, the default shadow effect is rounded rectangle edge.

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Card(
          margin:EdgeInsets.all(10),
          child: Column(
            children: <Widget>[
              ListTile(
                title:Text('chidaoxian'),
                subtitle: Text('Front-end Development Engineer'),
              ),
               ListTile(
                title:Text('Tel: 12323432141234123'),
               
              ),
               ListTile(
                title:Text('Address: XXXXXX'),
                
              ),
            ],
          ),
        ),
        Card(
          margin:EdgeInsets.all(10),
          child: Column(
            children: <Widget>[
              ListTile(
                title:Text('chidaoxian'),
                subtitle: Text('Front-end Development Engineer'),
              ),
               ListTile(
                title:Text('Tel: 12323432141234123'),
               
              ),
               ListTile(
                title:Text('Address: XXXXXX'() [[() [[() [[() [[() }}Copy the code

Effect:

11. Wrap component

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1, the introduction

The wrap component provides a stream layout, where a single-row wrap behaves almost identically to a Column, and a single-column wrap behaves almost identically to a Row. But Row and Column are single-row and single-column, and Wrap breaks this limitation by extending the display to crossAxis when mainAxis runs out of space.

attribute instructions
direction Spindle method, default level
alignment Alignment of spindle
spacing Spacing along the principal axis
textDirection The text direction
verticalDirection Defines the order in which children are placed. The default is down, as shown in flex properties
runAlignment Alignment of run. Run can be interpreted as a new row or column, or as a new row if the layout is horizontal
runSpacing The run of the spacing

2. Wrap instance

Code:

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing:10.// runSpacing:5,
      children: <Widget>[
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),
      MyButton('xxx'),]); }}class MyButton extends StatelessWidget {
  final String text;
  const MyButton(this.text, {Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text(this.text), textColor: Theme.of(context).accentColor, onPressed: () {}, ); }}Copy the code

Effect:

StatefulWidget has stateful components, binding data on the page, and changing page data

Basic code block :(code base part of this section, the rest of the effect display codes are in the Demo)

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'), ), body: Demo(), ), theme: ThemeData( primarySwatch: Colors.green, ), ); }}Copy the code

1, the introduction

Statefulwidgets are stateful components that hold states that can change during the Widget’s life cycle. In layman’s terms: If you want to change the data in a page, you need the StatefulWidget.

Stateful component/data binding

Code:

class Demo extends StatefulWidget {
  Demo({Key key}) : super(key: key);

  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  int countNum = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 20,),
        Chip(label: Text('The ${this.countNum}')),
        SizedBox(height: 20,),
        RaisedButton(
          child: Text('button'),
          onPressed: (){
            setState(() {
              this.countNum++; }); },)],); }}Copy the code

Effect:

The ButtonNavigationBar component

1, the introduction

The ButtonNavigationBar is the bottom navigation bar that allows us to define the bottom Tab toggle. The ButtonNavigationBar is the Scaffold component parameter.

The property name type instructions
currentlndex int Current index, used to toggle button control
fixedColor Color Select the color of the button. If no value is specified, the system theme color is used
iconSize double Button icon size
items List Bottom navigation call button set. Each item is a BottomNavigationBarItem with icon icon and title text attributes
onTap ValueChanged Press one of these buttons to call back the event. You need to set the current index based on the returned index

2, the instance,

1. Effect:

Bottom navigation switch page effect:

Code introduction:

Code:

1. The code for main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app01/pages/tabs/Home.dart';
import 'pages/tabs/Tabs.dart';
import 'pages/tabs/ddd.dart';
import 'pages/tabs/Setting.dart';

void main() {
  runApp(MyApp());
}

// Custom components
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    returnMaterialApp( home: Tabs(), theme: ThemeData( primarySwatch: Colors.green, ), ); }}class Tabs extends StatefulWidget {
  Tabs({Key key}) : super(key: key);

  @override
  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  int currentIndex = 0;

  List pageList = [
    HomePage(),
    SettingPage(),
    DDDPage(),
  ];
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'),
        ),
        body: this.pageList[this.currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: this.currentIndex,
          onTap: (int index) {
            setState(() {
              this.currentIndex = index;
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.my_library_books),
              label: 'I',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.settings_applications),
              label: 'set',),),),); }}Copy the code

Dart code

import 'package:flutter/material.dart';

class Tabs extends StatefulWidget {
  Tabs({Key key}) : super(key: key);

  @override
  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  int currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('flutter cdx'),
        ),
        body: Text('xxx'),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: this.currentIndex,
          onTap: (int index) {
            setState(() {
              this.currentIndex = index;
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.my_library_books),
              label: 'I',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.settings_applications),
              label: 'set',),),),); }}Copy the code

3, The code for home.dart (home.dart/setting.dart is similar)

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Text('HomePage')); }}Copy the code

14. Basic routes in Flutter

The route of a flutter is colloquially referred to as a page jump. Manage route navigation in FLUTTER through the Navigator component. It also provides methods to manage the stack. Examples are navigator.push and navigator.pop

Flutter provides two ways to configure route hops: 1. Basic route 2. Named route

1. Simple route jump

Code:

import 'package:flutter/material.dart';
import '.. /Search.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        RaisedButton(
          child: Text('Jump to search page'), onPressed: (){ Navigator.of(context).push( MaterialPageRoute( builder: (context)=> SearchPage() ) ); },),,); }}Copy the code

2. Jump to a value

Code:

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  SearchPage({Key key}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String title ;
  _SearchPageState({this.title = 'cdx'});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("The ${this.title}Page"),
      ),
      body: Text("Content area")); }}Copy the code

3, return

Code:

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  SearchPage({Key key}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String title ;
  _SearchPageState({this.title = 'cdx'});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Text('return'),
        onPressed: (){
          Navigator.of(context).pop();
        },
      ),
      appBar: AppBar(
        title: Text("The ${this.title}Page"),
      ),
      body: Text("Content area")); }}Copy the code

Effect:

15, Flutter named route

1. No parameters

Dart file configuration: **

Route hop mode:

2. Carry parameters

Routes. The dart files

import 'package:flutter/material.dart';
import 'package:flutter_app01/pages/tabs/Tabs.dart';
import 'package:flutter_app01/pages/tabs/ddd.dart';
import 'package:flutter_app01/pages/tabs/Setting.dart';
import 'package:flutter_app01/pages/Search.dart';
import 'package:flutter_app01/pages/tabs/Home.dart';

final routes = {
  '/': (context, {arguments}) => Tabs(),
  '/home': (context, {arguments}) => HomePage(),
  '/ddd': (context, {arguments}) => DDDPage(),
  '/setting': (context, {arguments}) => SettingPage(),
  '/search': (context, {arguments}) => SearchPage(arguments: arguments),
};

// The main method
var onGenerateRoute = (RouteSettings settings) {
  final String name = settings.name;
  final Function pageContentBuilder = routes[name];
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route =   MaterialPageRoute(builder: (context) =>  pageContentBuilder(context, argumens: settings.arguments));
      return route;
    } else {
      final Route route =  MaterialPageRoute(builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

The main dart files

import 'package:flutter/material.dart';
import 'package:flutter_app01/routes/Routes.dart';

void main() {
  runApp(MyApp());
}

// Custom components
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      // home: Tabs(),
      initialRoute: '/'.// Route loaded during initializationonGenerateRoute: onGenerateRoute, ); }}Copy the code

16. Replace/return the root route

1. Replace routes

Replace the current page.

2. Return the following route

Table properties of the component to be imported

The Form component

The property name type instructions
key Key The key value of the component in the Widget tree
autovalidate bool Whether to submit the form automatically
child Widget The component child can have only one child
onChanged VoidCallback The callback function for FormFiled when the value changes

TextFromField components

The property name type instructions
autovalidate bool Automatic validation value
initialValue T Initial value of the form field
onSaved FormFieldSetter Callback function when the Form calls the Save method
validator FormFieldValidator Form Form validator

Material Design style components

Component name Chinese name Simple instructions
AppBar Application button component The tool button for the application
AlertDialog Dialog box component A dialog box with action buttons
BottomNavigationBar Bottom navigation bar component The bottom navigation bar makes it easy to switch between taps and browse top-level views
Card Card components Card components with border shadows
Drawer Drawer components Drawer components can be used to pull open and close drawers
FloatingActionButton Floating button assembly The main function of the application operation button
FlatButton Flat button assembly Flat style buttons
MaterialApp Material Application component Material App stands for apps that use paper and ink design styles
PopupMenuButton Popup menu component Popup menu button
Scaffold Scaffold assembly The basic Material Design layout is realized
SnackBar Lightweight prompt component A lightweight message prompt component that appears at the bottom of the screen
SimpleDialog Simple dialog box components Simple dialog box component, only prompts, no interaction
TabBar Horizontal TAB and view components A Material Design component that displays horizontal tabs
TextField Text box component A component that accepts applied input text

MaterialApp

The property name type instructions
title String Title of the application. The title appears in the following location: Android: Program snapshot on Task Manager IOS: Program Switch Manager
theme ThemeData Defines the theme color used by the application. You can specify the color of each control in a theme
color Color The primary color of the application
home Widget This is a Widget object that defines the interface to display when the current application is opened
routes Map<String,WidgetBuider> Define page jump rules in an application
initialRoute String Initializing a Route
onGenerateRoute RouteFactory Route callback function. When jumping to a route through navigator.of (context).pushnamed, this method is called when routes cannot be found
onLocaleChanged This callback is triggered when the system changes the language
navigatorObservers List Navigational observer
debugShowMaterialGrid bool Whether to display paper and ink design base layout grid, used to debug UI tools
showPerformanceOverlay bool Display performance labels

Scaffold

The property name type instructions
appBar AppBar An AppBar that appears at the top of the interface
body Widget The main content displayed on the current screen
floatingActionButton Widget A function button defined in Material Design
persistentFooterButtons List The button is fixed below the display
drawer Widget Sidebar components
bottomNavigationBar Widget Display the button bar at the bottom of the navigation bar
backgroundColor Color The background color
resizeToAvoidBottomPadding bool Controls whether the body of the interface content is rearranged so that the bottom is not covered, for example, when the keyboard is displayed, so that the content is not covered by the keyboard. The default value is true

AppBar and SliverAppBar components

The property name type The default value
leading Widget null
title Widget null
actions List null
bottom PreferredSize Widget null
elevation double 4
flexibleSpace Widget null
backgroundColor Color ThemeData.primaryColor
brightness Brightness ThemeData.primaryColorBrightness
iconTheme IconThemeData ThemeData.primaryIconTheme
textTheme TextTheme ThemeData.primaryTextTheme
centerTitle bool true

Introduction:

The property name instructions
leading A component that appears before the title, usually with the app’s logo on the front page; Normally displayed on other screens
title The main content of the Toolbar, usually displayed as the title text of the current interface
actions A list of widgets representing the menus displayed in the Toolbar, usually represented by IconButton for common menus, and PopupMenuButton for less common menus as a three-point display that pops up a secondary menu when clicked
bottom It’s usually TabBar. Use to display a Tab navigation bar under the Toolbar header
elevation The z-coordinate order of components in ink and paper design. For scrollable SliverAppBar, 0 when the SliverAppBar is at the same level as the content. Change the elevation when the content mutters into a ToolBar
flexibleSpace A component that appears below the AppBar and is the same height as the AppBar can achieve some special effects. This property is usually used in SliverAppBar
backgroundColor The background color
brightness AppBar brightness, white and black themes
iconTheme AppBar icon color, transparency and size information. The default value is themedata.primaryicon Theme
textTheme Text style on AppBar
centerTitle The default value varies with the operating system (OS)