The article directories

    • Output Hello World
    • 2. Text, container
    • 3, remote pictures, local pictures, circular pictures, rounded pictures
    • 4. Basic list component, Horizontal list component, icon component
    • 5. Lists, dynamic lists
    • 6. Grid layout
    • 7. Bottom navigation
    • 8. Page jump, jump value transmission (common route, common route value transmission)
    • 9. Page jump, jump value (named route, named route value)
    • 10. Replace the route and return to the root route
    • Define the top Tab switch, the bottom Tab combined with the top Tab to achieve similar to the headline page layout
    • 12. TabController defines the top TAB switch and introduces the lifecycle functions
    • 13, Drawer sidebar, and layout of sidebar content
    • RaisedButton, FlatButton, OutlineButton, IconButton, ButtonBar and custom button components
    • 15. Similar to the raised navigation button on the bottom of the Idler App
    • 16. Single line text box, multiple checkboxes
    • 17, multi-line text box, switch button, multi-checkbox, Radio button, RadioListTile, Radio, form
    • Call native time picker, date picker, timestamp, Future async
    • 19, call third party time picker, date picker, timestamp
    • 20. Rotation diagram flutter_swiper
    • General dialog box, list dialog box, radio dialog box, Toast prompt

Output Hello World

1.1. Renderings

Output Hello World

import 'package:flutter/material.dart';

void main(a)=>runApp(MyApp());
// Equivalent to:
/*
void main(){
	runApp(MyApp());
}
*/

class MyApp extends StatelessWidget{		// Pull out the entire page
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(						/ / the top widget
      home:Scaffold(						//Material Design The basic implementation of the layout structure
        appBar: AppBar(						// Display an AppBar at the top of the interface.
          title: Text('Flutter Demo'),		/ / title
        ),
        body: HomeContent(),				// The main content displayed in the current interface is the Widget.
      ),
          theme: ThemeData(					/ / theme
        primarySwatch: Colors.yellow		// Change the theme color)); }}class HomeContent extends StatelessWidget{	// Pull away from the main screen
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(						/ / in the middle
      child: Text("Hello Flutter".// The Text component is used to display the string content into the page
      textDirection:TextDirection.ltr,	// Indicates how the text will be displayed
        style: TextStyle(				/ / style
          fontSize: 40.0./ / size
          color: Colors.yellow,			/ / color),),); }}Copy the code

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

Home/title/color/theme/routes home/title/color/theme/routes

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

Scaffold has the following main attributes: appBar – an appBar displayed at the top of the interface. Body – a Widget that displays the main content of the current interface. Drawer – Drawer menu control.

1.4, notes

1.All components are classes2.Dart allows classes to be instantiated without keywordsnew, such as:var p = newPersion(); It can be written as:var p = Persion();

3.In The Flutter, we put the Center in runApp which is obviously not reasonable! Because: when our component needs a lot of functionality, we will have a lot of code, so we put runApp, the code will become very messy and redundant so: we can separate it into a component, equivalent to Java encapsulation, reduce the burden of the program, saving code quality4.Question: Why instantiate runApp(MyApp()); The time,Widget build(BuildContext context) {
    // TODO: implement build
    return Center(                    / / in the middle
        child: Text('Hello Flutter',
          textDirection: TextDirection.ltr, // Indicates how the text will be displayed)); } Is the abstract method automatically executed? A: Build is used to create widgets. Build is called every time the interface is refreshed5.Does child: Text mean instantiating Text? A: No, let's look at the following code to see why!class MyApp extends StatelessWidget{
  @override
  // Build is used to create widgets. Build is called every time the interface is refreshed
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo'),
        ),
        body: HomeContent(),
      ),
          theme: ThemeData(
            primarySwatch: Colors.yellow    // Change the theme color)); }}class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(                    / / in the middle
        child: Text('Hello Flutter',
          textDirection: TextDirection.ltr, // Indicates how the text will be displayed
          style: TextStyle(       // Font style
            fontSize: 40.0.// There are two ways to set the color
/ / way
            color: Colors.yellow,
// Mode 2:
            // The meanings of the parameters are: red, green, blue, transparency, color take the first three mixed values, transparency take the fourth parameter
// Color: color. FromRGBO (244, 233, 321, 0.5)))); }} body: HomeContent();newHomeContent(), so the meaning is obvious, which components are instantiated when the functionality is implemented!Copy the code

2. Text, container

2.1, effect diagram

2.2. Code + comments

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text('Fullter Demo'), ), body: HomeContent(), ) ); }}class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: Container(     // is a container, equivalent to the front div, used for layout
        child: Text('I am a text I am a text I am a text I am a text I am a text I am a text',
                    textAlign: TextAlign.center,   // Display in the center
                    overflow: TextOverflow.ellipsis,  // Use... Instead of
                    maxLines: 1.// Display a maximum of one line
                    textScaleFactor: 1.8.// Double the font size
                    style: TextStyle(
                    fontSize: 16.0 ,     // Set the font size
                    color: Colors.red ,  // Font color
                    fontWeight:FontWeight.w800, // Make the font bold
                    fontStyle: FontStyle.italic,  // Font tilt
                    decoration: TextDecoration.lineThrough , // The line through the text
                    decorationColor: Colors.white,   // The color of the cross line
                    decorationStyle: TextDecorationStyle.dashed,   / / dotted line
                    letterSpacing: 5.0    // Font spacing
                    ),
        ),
        height: 300.0.// Set the container height
        width: 300.0.// Set the container width
        decoration: BoxDecoration(
          color: Colors.yellow,   // The background color
          border: Border.all(
            color: Colors.blue,   // Border color
            width: 2.0              // Frame width
          ),
            borderRadius: BorderRadius.all(
              Radius.circular(20),    // Set the rounded border
// Radius. Circular (150), // Set circular border)),// padding: edgeinset.all (20), // indicates a margin of 20 with the top, bottom, left, and left sides
          padding: EdgeInsets.fromLTRB(10.30.5.0), // Set the upper left and lower right margins

        margin: EdgeInsets.fromLTRB(10.30.5.0),  // Set the upper left and lower right margins

/ / the transform: Matrix4 translationValues (100, 0, 0) / / 100 X axis displacement
Transform: matrix4.rotationz (0.3); // Transform: matrix4.rotationz (0.3); // Transform: matrix4.rotationz (0.3)
// Transform: matrix4.diagonal3values (1.2, 1, 1), // Scale
          alignment: Alignment.bottomLeft,    // Set the elements in the border to the bottom left)); }}Copy the code

2.3 Knowledge Points

Text component

[1TextDirection (LTR from left to right, LTR from left to right) RTL From right to left) Overflow text processing (Clip, fade, ellipsis) textScaleFactor maxLines Maximum number of lines to display text style Font style2Here is the TextStyle parameter: Name Function Decoration (none, lineThrough, overline, Underline the underline) decorationColor words decorationStyle decorative thread color words decorative thread style (dashed and dotted line,doubleTwo lines, solid, wavy. Spacing (if it's negative, it makes the words more compact) Normal) fontSize fontSize color font color fontWeight fontSize (bold, normal)//docs.flutter.io/flutter/painting/TextStyle-class.html
Copy the code

3, remote pictures, local pictures, circular pictures, rounded pictures

3.1. Effect drawing

[1] Quoting remote images



[2] Reference local images



[3] To achieve circular images (Method 1), rounded images (affected by radians)



[4] Realize circular picture (Method 2)

[1] Reference remote images

import 'package:flutter/material.dart';
void main(a)=> runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FlutterDemo'), ), body: HomeCentent(), ), ); }}class HomeCentent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
        child: Container(
          child: Image.network(                   // Import a remote image
            "https://www.itying.com/images/flutter/2.png".// Remote image link
            alignment: Alignment.topLeft,     // Set the orientation of the image to the upper left corner
// Color: color. yellow, // set the color of this image
ColorBlendMode: blendmode. luminosity, // set the colorBlendMode

            fit:BoxFit.cover,       // Set the image display mode, cover -- full screen display, most commonly used!
// repeat: imagerepeat.repeatx, // repeat: imagerepeat.repeatx, // repeat: ImageRepeat
// repeat: imagerepeat. repeat, //
          ),
          width: 300,
          height: 300,
          decoration: BoxDecoration(
              color: Colors.yellow          // Set the background color of the box))); }}Copy the code

[2] Reference local images

Prepare first :(three steps)

1. Create the Images folder in the project root directory, as shown below:

2. Create 2.0x, 3.0x, 4.0x and put images in each folder, and then put another image outside, as shown in the figure below:



3. In the pubspec.yaml file, add the following configuration:



Click Packages get in the upper right corner and press Ctrl+ S to save

Then you can start typing code:

import 'package:flutter/material.dart';
void main(a)=> runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FlutterDemo'), ), body: HomeCentent(), ), ); }}class HomeCentent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: Container(
        child: Image.asset('images/aa.png'.// Import the local image
          fit: BoxFit.cover,
        ),
        height: 300,
        width: 300)); }}Copy the code

[3] Achieve round pictures (Method 1), rounded pictures (according to the radian change)

    return Center(
        child: Container(

          width: 300,
          height: 300,
          decoration: BoxDecoration(
            color: Colors.yellow ,         // Set the background color of the box
// borderRadius: BorderRadius.all(
// Radius. Circular (150); // Circular (150)
/ /),
            borderRadius: BorderRadius.circular(150),       // The first way to implement circular images is a bit cumbersome
            image: DecorationImage(
                image: NetworkImage("https://www.itying.com/images/flutter/2.png"),
                fit: BoxFit.cover     // Cover the full screen),),));Copy the code

[4] To achieve circular pictures (Method 2) :

    return Center(
        child: Container(
          child: ClipOval(    // Implement circular image method 2, the simplest way
            child: Image.network('https://www.itying.com/images/flutter/2.png',
              height: 100,
              width: 100,
              fit: BoxFit.cover,
            ),
          ),
        )
    );
Copy the code

3.3 Knowledge Points

The Image component is a component that displays images. The Image component has many constructors. Here we will only talk about two images. asset, local Image Image.network remote Image

Common properties of the Image component:

Align Image alignment Color and colorBlendMode Indicates the background color of the image. This mode is usually used together with colorBlendMode to combine the image color and background color. The above image is a color blend, with a green background and a red image fit BoxFit the fit property is used to control the stretching and extrusion of the image, depending on the parent container. Boxfit. fill: The full image is displayed, the image is stretched and fills the parent container. BoxFit. Contain: Full image, show the original scale, there may be some space. Boxfit. cover: Shows that it may stretch, it may crop, it may fill (the picture should fill the container without distorting). Boxfit. fitWidth: Width full (landscape full), showing possible stretch, possible cropped. BoxFit. FitHeight: Height full (vertical full), display may stretch, may cut. Boxfit.scaledown: This property is similar to the contain attribute, but does not allow the display to be larger than the source image. Repeat Tile ImageRepeat. Repeat: Repeat both horizontally and vertically until the entire canvas is covered. ImageRepeat. RepeatX: repeat horizontally, not vertically. ImageRepeat. RepeatY: repeat vertically, not horizontally. Width = "width"; height = "height"; width = "width"; height = "height";//api.flutter.dev/flutter/widgets/Image-class.html
Copy the code

4. Basic list component, Horizontal list component, icon component

4.1. Renderings

[1] Basic list



[2] Basic list + icon component

[3] Basic list + reference remote image

[4] Vertical list



[5] Level list

4.2 code + comments

[1] Basic list

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text('Hello Flutter'), ), body: HomeContent(), ) ); }}class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView(        / / list
      children: <Widget>[   // configures its child elements
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on',
            style: TextStyle(
              fontSize: 18),),/ / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content)],); }}Copy the code

[2] Basic list + icon component

. . .return ListView(        / / list
      children: <Widget>[   // configures its child elements
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Icon(Icons.settings,color: Colors.yellow),    // Put an icon on the left and change the icon color
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Icon(Icons.home,size: 30),    // Place an icon on the left
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
          trailing: Icon(Icons.settings),     // Place an icon on the right
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Icon(Icons.settings),    // Place an icon on the left
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Icon(Icons.home),    // Place an icon on the left
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content)],);Copy the code

[3] Basic list + reference remote image

. . .return ListView(        / / list
      children: <Widget>[   // configures its child elements
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Image.network("https://www.itying.com/images/flutter/1.png"),
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Image.network("https://www.itying.com/images/flutter/2.png"),
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
          trailing: Image.network("https://www.itying.com/images/flutter/5.png")
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Image.network("https://www.itying.com/images/flutter/3.png"),
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content
        ),
        ListTile(     // Each item is written in a ListTile. That's the specification
          leading: Image.network("https://www.itying.com/images/flutter/4.png"),
          title: Text('Bed before the moonlight, according to the database everyone burner on time to consider the start of the pull on'),  / / title
          subtitle: Text('Astrazeneca great god answer control Ascoli everyone cool all four cool drawing machine database how long ah how long ah class classy classic'), / / content)],);Copy the code

[4] Vertical list

. .return ListView(
      scrollDirection: Axis.vertical,     // Vertical list
      padding: EdgeInsets.all(10),
      children: <Widget>[
        Image.network('https://www.itying.com/images/flutter/1.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/2.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/3.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/4.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/5.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/6.png'),
        Container(
          child: Text('I am a title',
            textAlign: TextAlign.center,  / / in the middle
            style: TextStyle(
              fontSize: 28,
            ),
          ),
          height: 60,
          padding: EdgeInsets.fromLTRB(0.10.0.10),
        ),
        Image.network('https://www.itying.com/images/flutter/2.png'),
        Image.network('https://www.itying.com/images/flutter/3.png'),
        Image.network('https://www.itying.com/images/flutter/4.png'),
        Image.network('https://www.itying.com/images/flutter/1.png'),
        Image.network('https://www.itying.com/images/flutter/2.png'),
        Image.network('https://www.itying.com/images/flutter/3.png'),
        Image.network('https://www.itying.com/images/flutter/1.png'),
        Image.network('https://www.itying.com/images/flutter/2.png'),
        Image.network('https://www.itying.com/images/flutter/3.png'),]);Copy the code

[5] Level list

. . .return Container(
      height: 180,
        child: ListView(
// scrollDirection: Axis. Vertical, // Vertical list
          scrollDirection: Axis.horizontal,        // Level list,
          children: <Widget>[
            Container(
              width: 180.0,
              height: 180.0,
              color: Colors.yellow,
            ),
            Container(
              width: 180.0,
              height: 180.0,
              color: Colors.blue,
              child: ListView(
                children: <Widget>[
                  Image.network("https://www.itying.com/images/flutter/2.png"),
                  Text('I am a text')
                ],
              ),
            ),
            Container(
              width: 180.0,
              height: 180.0,
              color: Colors.red,
            ),
            Container(
              width: 180.0,
              height: 180.0,
              color: Colors.green,
            )
          ],
        ),
    );
Copy the code

4.3 Knowledge points

  • The list layout is one of the most common layouts we use in project development. With Flutter we can define list items via ListView, which supports vertical and horizontal display. You can control the display direction of the list with a single property. The list has the following categories: 1, vertical list 2, vertical graphic list 3, horizontal list 4, dynamic list 5, matrix list
  • Flutter list parameters
Horizontal Horizontal list Axis. Vertical Vertical list PADDING EdgeInsetsGeometry Margin Resolve Bool Indicates the reverse sorting of components Children List<Widget> List elementsCopy the code

4.4, notes

  • You can place any component in the ListView children:
  • After we write each ListTile (android item), it automatically generates the Widget array, which acts as an array behind the Adapter management data

5. Lists, dynamic lists

5.1 Renderings

5.2. Code + comments to achieve dynamic list: [1] Method 1: Pull out components

import 'package:flutter/material.dart';

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

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

	// Method 1: create a list by creating a list of listtiles
  List<Widget> _getData(a){
    return [
      ListTile(
        title: Text("I am a list"),
      ),
      ListTile(
        title: Text("I am a list"),
      ),
      ListTile(
        title: Text("I am a list"),
      ),
      ListTile(
        title: Text("I am a list"),
      )
    ];
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView(
      children: this._getData(), ); }}Copy the code

[2] Method 2: Dynamically generate ListTile data through List collection

. .class HomeContent extends StatelessWidget{

	// Method 2: Dynamically generate ListTile data from List collection
  List<Widget> _getData(a){
    List<Widget> list = new List();
    for(var i=0; i<20; i++){ list.add(ListTile( title: Text("I am the $I list"))); }return list;
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView(
      children: this._getData( ), ); }}Copy the code

[3] Method 3: Dynamically generate ListTile data through the Map set

Now create the data externally: let’s say I’m currently in lib/res/ listdata.dart

List listData=[
  {
    "title":'Candy Shop'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/1.png'}, {"title":'Childhood in a picture'."author":'Google'."imageUrl":'https://www.itying.com/images/flutter/2.png'}, {"title":'Alibaba Shop'."author":'Alibaba'."imageUrl":'https://www.itying.com/images/flutter/3.png'}, {"title":'Candy Shop'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/4.png'}, {"title":'Tornado'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/5.png',}];Copy the code

Remember to import: import ‘res/ listdata.dart’;

class HomeContent extends StatelessWidget{

	// Method 3: Dynamically generate ListTile data from the Map set
  List<Widget> _getData(a){

      var tempList = listData.map((value){      Var (map); var (map); var (map); var (map)
        return ListTile(                  // Return the tempList value for each change
          leading: Image.network(value["imageUrl"]),
          title: Text(value["title"]),
          subtitle: Text(value["author"])); });return tempList.toList();       // Finally return this value, but remember, it is not an array of collections, so we want it to be converted to the next type, via toList
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView(
      children: this._getData( ), ); }}Copy the code

[4] Method four: Through the Builder specification, let ListView automatically loop through the false data

. .class HomeContent extends StatelessWidget{

  / / note that there is at the time of instantiation constructor is executed, so is to create good data first, then four to traverse through the following ways to get the data
  List list = new List();
  HomeContent(){
    for(var i=0; i<20; i++){this.list.add('I am the $I clause'); }}@override
  Widget build(BuildContext context) {
    // TODO: implement build
    // Method 4: let the ListView automatically loop through the data through the Builder specification
    return ListView.builder(
      itemCount: this.list.length,      // You must specify the length of the List
      itemBuilder:(context,index){      // You need to pass two parameters, and then the Builder will automatically loop from 0 to the maximum length
        return ListTile(
          title: Text(this.list[index]),  // Return the data corresponding to the index retrieved each time); }); }}Copy the code

[5] Method five: Through builder specification, let ListView automatically loop through dynamic real data

class HomeContent extends StatelessWidget{

  // Custom methods
  Widget _getListData(context,index){
    return ListTile(
      title: Text(listData[index]["title"]),  // Return the data corresponding to the index retrieved each time
      leading: Image.network(listData[index]["imageUrl"]),
      subtitle: Text(listData[index]["author"])); }@override
  Widget build(BuildContext context) {
    // TODO: implement build
    // Method 4: let the ListView automatically loop through the data through the Builder specification
    return ListView.builder(
      itemCount: listData.length,      // You must specify the length of the List
      itemBuilder:this._getListData   }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
      // The purpose of assignment is to take the code out of the code and make it clear
    );
  }
Copy the code

The list layout is one of the most commonly used layouts in our project development. With Flutter we can define list items via ListView, which supports vertical and horizontal display. You can control the display direction of the list with a single property. The list has the following categories: 1, vertical list 2, vertical graphic list 3, horizontal list 4, dynamic list 5, matrix list

2. Flutter list parameters

Horizontal Horizontal list Axis. Vertical Vertical list PADDING EdgeInsetsGeometry Margin Resolve Bool Indicates the reverse sorting of components Children List<Widget> List elementsCopy the code

6. Grid layout

6.1 Renderings

[1] Simple grid layout

[2] Loop through false data to realize grid layout



[3] GridView.count Dynamically obtains data and realizes grid layout



[4] GridView. Builder dynamically obtains data and realizes grid layout

6.2 code + comments

[1] Simple grid layout

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo'), ), body: HomeContent(), ) ); }}class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GridView.count(    // Grid component

      crossAxisCount: 2.// Control the number of grid columns

      children: <Widget>[     // Control the grid elements
        Text('This is a text.'), // The child element
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.'),
        Text('This is a text.')],); }}Copy the code

[2] Loop through false data to realize grid layout

. .class HomeContent extends StatelessWidget{

  List<Widget> _getlistData(a){
    List<Widget> list = new List();

    for(var i=0; i<20; i++){ list.add(Container( alignment: Alignment.center, child: Text('This is the $I item.',
                style: TextStyle(color: Colors.white,fontSize: 20),
          ),
        color: Colors.blue,
// Height: 400, // set height to no response,
      ));
    }
    return list;
  }



  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GridView.count(    // Grid component

      crossAxisSpacing: 20.0.// The spacing between horizontal sub-widgets

        mainAxisSpacing: 20.0.// Vertical spacing between sub-widgets
        
        padding: EdgeInsets.all(10),  // Set an interval of 10 with the View

      crossAxisCount: 2.// Control the number of grid columns

        childAspectRatio: 0.7.// The ratio of width to height

      children: this._getlistData() // The Widget is returned); }}Copy the code

[3] GridView.count Dynamically obtains data and realizes grid layout

Remember to import the DART file for external data at the beginning, as follows:

List listData=[
  {
    "title":'Candy Shop'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/1.png'}, {"title":'Childhood in a picture'."author":'Google'."imageUrl":'https://www.itying.com/images/flutter/2.png'}, {"title":'Alibaba Shop'."author":'Alibaba'."imageUrl":'https://www.itying.com/images/flutter/3.png'}, {"title":'Candy Shop'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/4.png'}, {"title":'Tornado'."author":'Mohamed Chahin'."imageUrl":'https://www.itying.com/images/flutter/5.png',}];Copy the code

main.dart

import 'package:flutter/material.dart';

import 'res/listData.dart'; . .class HomeContent extends StatelessWidget{

  List<Widget> _getlistData(a){

    var tempList = listData.map((value){
      return Container(
        child: Column(            // Note that you can also use the ListView to retrieve data, but the downside of the ListView is that it ADAPTS to the width, i.e. tils the entire width
          children: <Widget>[     // However, Column does not. It only displays the size of the element and is automatically arranged vertically
            Image.network(value['imageUrl']),
            SizedBox(height: 10,),    // Set the spacing between Text and Image to 10
            Text(value['title'],
            textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 15
              ),
            )
          ],
        ),
        decoration: BoxDecoration(    / / frame class
          border: Border.all(         // Set the border style
            color: Color.fromRGBO(233.233.233.0.9),  / / color
            width: 1    // Frame width))); });return tempList.toList();
  }



  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GridView.count(    // Grid Components - list layout

      crossAxisSpacing: 20.0.// The spacing between horizontal sub-widgets

        mainAxisSpacing: 20.0.// Vertical spacing between sub-widgets
        
        padding: EdgeInsets.all(10),  // Set an interval of 10 with the View

      crossAxisCount: 2.// Control the number of grid columns

// childAspectRatio: 0.7, // Ratio of width to height

      children: this._getlistData() // The Widget is returned); }}Copy the code

[4] GridView. Builder dynamically obtains data and realizes grid layout

import 'package:flutter/material.dart';

import 'res/listData.dart'; . .class HomeContent extends StatelessWidget{

  Widget _getlistData(context,index){
      return Container(
        child: Column(            // Note that you can also use the ListView to retrieve data, but the downside of the ListView is that it ADAPTS to the width, i.e. tils the entire width
          children: <Widget>[     // However, Column does not. It only displays the size of the element and is automatically arranged vertically
            Image.network(listData[index]['imageUrl']),
            SizedBox(height: 10,),    // Set the spacing between Text and Image to 10
            Text(listData[index]['title'],
            textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 15
              ),
            )
          ],
        ),
        decoration: BoxDecoration(    / / frame class
          border: Border.all(         // Set the border style
            color: Color.fromRGBO(233.233.233.0.9),  / / color
            width: 1    // Frame width))); }@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GridView.builder(    // Grid Components - list layout
      /** * this method is used because when we use the GridView.builder, we can no longer put the element style outside. Instead, we should use the following class to fill in the style, otherwise we will report an error */
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisSpacing: 20.0.// The spacing between horizontal sub-widgets
                mainAxisSpacing: 20.0.// Vertical spacing between sub-widgets
                crossAxisCount: 2.// Control the number of grid columns
        ),
          itemCount: listData.length,		// Data length
          itemBuilder: this._getlistData ); }}Copy the code

6.3 Knowledge points

The common parameters of the GridView component are arranged in a matrix format for large amounts of data. At this point we can implement the layout using the grid list component GridView. The GridView creates a grid list in several ways, and we’ll focus on two. 1. Grid layout can be realized by gridView. count

Common attributes:

ScrollDirection Axis Scrolling method padding EdgeInsetsGeometry Edge spacing Resolve bool Reverse component sorting crossAxisSpacingdoubleSpacing between horizontal sub-widgets mainAxisSpacingdoubleSpacing between vertical child widgets crossAxisCountintNumber of widgets in a row childAspectRatiodoubleChild widgets wide high proportion of children < widgets > [] gridDelegate SliverGridDelegateWithFixedCrossAxisCount SliverGridDelegateWithMax (common) CrossAxisExtent control layout is mainly used in gridView. builderCopy the code

6.4, notes

1. Container is not a layout.

2. Grid components, also known as list layouts

7. Bottom navigation

Effect:

Home.dart

Category.dart

Setting.dart



main.dart:

import 'package:flutter/material.dart';
import 'pages/Tabs.dart';
void main(a) => runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Tabs()      // Pull out all the code as a Tabs component); }}Copy the code

In the lib root directory, create pages, and then create the Tabs. Dart file Tabs

import 'package:flutter/material.dart';
import 'tabs/Category.dart';
import 'tabs/Home.dart';
import 'tabs/Setting.dart';

class Tabs extends StatefulWidget {

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

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

  List _pageList = [    // First put all pages in the List collection
    HomePage(),
    CategoryPage(),
    SettingPage()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FlutterDemo'),
      ),
      body: this._pageList[this._currentIndex],   // Then get the corresponding page Settings according to the subscript and put them in the body
      bottomNavigationBar: BottomNavigationBar(     // Customize the bottom navigation bar

          currentIndex: this._currentIndex,   // Configure the corresponding index value selected
          onTap: (int index){
            setState(() {     // Change the state
              this._currentIndex=index;      // Change the selected Tab coordinate
            });
          },
          iconSize: 45.0.// The size of the Icon is about 20 by default
          fixedColor: Colors.red, // The selected color, which is blue by default
          type: BottomNavigationBarType.fixed,    // The bottom tabs can have multiple buttons. By default, the bottom tabs can have no more than three buttons
          items:[
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.home),
                title: Text('home')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.category),
                title: Text('classification')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.settings),
                title: Text('set'() () () ( }}Copy the code

Dart, Home. Dart, and setting.dart

Category.dart

import 'package:flutter/material.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState(a) => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Text('classification'); }}Copy the code

Home.dart

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState(a) => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Text('I am the home page component'); }}Copy the code

Setting.dart

import 'package:flutter/material.dart';

class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState(a) => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        ListTile(
          title: Text('I am a text'),
        ),
        ListTile(
          title: Text('I am a text'),
        ),
        ListTile(
          title: Text('I am a text'),
        ),
        ListTile(
          title: Text('I am a text'),
        ),
        ListTile(
          title: Text('I am a text'), a)],); }}Copy the code

8. Page jump, jump value transmission (common route, common route value transmission)

Effect:

Home.dart



Search.dart



Category.dart



Form.dart



Bottom navigation basic frame in:The flutter implements bottom navigation

All right, let’s do the prep work, let’s get on track, let’s get on the page jump

Home.dart

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState(a) => _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: (){    / / listeners
              // Route jump
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context)=>SearchPage()
                )
              );
            },
            color: Theme.of(context).accentColor,
            textTheme: ButtonTextTheme.primary,
          ),
          SizedBox(height: 20,)]); }}Copy the code

Category.dart

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

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState(a) => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start, // The secondary axis is left
      mainAxisAlignment: MainAxisAlignment.center,  // The main axis is centered
      children: <Widget>[
        RaisedButton(
          child: Text('Jump to the Form page'),
          onPressed: () {   / / listeners
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context)=>FormPage(title: 'I'm a jump value'.)/** * Equivalent: Builder (context){* return FormPage(); *} * /)); }, color: Theme.of(context).accentColor, textTheme: ButtonTextTheme.primary, ) ], ); }}Copy the code

Create two new files in lib→pages directory:

Search.dart

import 'package:flutter/material.dart';


class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState(a) => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Search page'),
      ),
      body: Text('Search page Content area')); }}Copy the code

Form.dart

import 'package:flutter/material.dart';

class FormPage extends StatelessWidget {

  String title;
  FormPage({this.title='form'});    // The parameter is an optional parameter. The default value is the form. When a value is received, the form value is overwritten

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(     // Hover button
        child: Text('return'),
        onPressed: (){        / / listeners
          Navigator.of(context).pop();  // Exit the current heap and return to the upper page
        },
      ),
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
            title: Text('I'm the form page'),
          ),
          ListTile(
            title: Text('I'm the form page'),
          ),
          ListTile(
            title: Text('I'm the form page'),
          ),
          ListTile(
            title: Text('I'm the form page'"" "" "" "" "" }}Copy the code

9. Page jump, jump value (named route, named route value)

Effect:

Home.dart



Product.dart



ProductInfo.dart



Bottom navigation basic frame reference:The flutter implements bottom navigation

Other button interfaces refer to the previous section: Flutter implements page jump, jump value (common route, common route value)

First, I will show you the screenshots of all relevant folders and file page locations for your understanding. For other repetitive code, you can refer to the above two chapters to learn, and you will be ready. Come on, everyone!









Then I’ll post the code for the named route:

The main dart to modify

import 'package:flutter/material.dart';

import 'routes/Routes.dart';

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

class MyApp extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      initialRoute: '/'.// The route is loaded during initialization
// home: Tabs(), // pull all the code out as a TAB, then pull out as an initialRoute component, initialRoute: '/',
        // Configure the named route
        onGenerateRoute: oonGenerateRoute // Assign the exported routing specification to the left, not to the execution, remember!); }}Copy the code

Home.dart

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState(a) => _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: (){    / / listeners
              // Named route jump
              Navigator.pushNamed(context, '/search',arguments: { // Arguments must be used to carry the id key in order to fetch the value
                "id":123
              });
            },
            color: Theme.of(context).accentColor,
            textTheme: ButtonTextTheme.primary,
          ),
          SizedBox(height: 20,),
          RaisedButton(
            child: Text('Jump to product page'),
            onPressed: (){    / / listeners
              // Named route jump
              Navigator.pushNamed(context, '/product'); }, color: Theme.of(context).accentColor, textTheme: ButtonTextTheme.primary, ), ], ); }}Copy the code



Routes.dart

import '.. /pages/Form.dart';
import '.. /pages/Search.dart';
import '.. /pages/Tabs.dart';
import '.. /pages/Product.dart';
import '.. /pages/ProductInfo.dart';

import 'package:flutter/material.dart';

// Configure routes
final  routes={                   // Configure the named route
  '/':(context)=>Tabs(),  // The named routing value is required
  '/form':(context)=>FormPage(),
  '/product':(context)=>ProductPage(),  // The named routing value is required
  '/productInfoPage':(context,{arguments})=>ProductInfoPage(arguments:arguments),  // The named routing value is required
  '/search':(context,{arguments})=>SearchPage(arguments:arguments)  // The named routing value is required
};

// Fixed writing
var oonGenerateRoute=(RouteSettings settings) {
  // Unified processing
  final String name = settings.name;    // Get the name of the named route, for example: '/form'
  final Function pageContentBuilder = routes[name];  // get the key of the named route to get the value, for example :(context)=>FormPage(),
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

Tabs. The dart is constant

Product.dart

import 'package:flutter/material.dart';

class ProductPage extends StatefulWidget {
  @override
  _ProductPageState createState(a) => _ProductPageState();
}

class _ProductPageState extends State<ProductPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Product Details'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            child: Text('Jump to product details'),
            onPressed: (){    / / listeners
              Navigator.pushNamed(context, '/productInfoPage',arguments: {
                'pid':456}); }, color: Theme.of(context).accentColor, textTheme: ButtonTextTheme.primary, ), ], ), ); }}Copy the code

ProductInfo.dart

import 'package:flutter/material.dart';

class ProductInfoPage extends StatefulWidget {
  final Map arguments;
  ProductInfoPage({Key key,this.arguments}) : super(key: key);

  @override
  _ProductInfoPageState createState(a) => _ProductInfoPageState(arguments:this.arguments);
}

class _ProductInfoPageState extends State<ProductInfoPage> {
  Map arguments;

  _ProductInfoPageState({this.arguments});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Product Details'),
      ),
      body:  Container(
        child: Text('pid=${arguments['pid']} '),),); }}Copy the code

10. Replace the route and return to the root route

Effect:

Setting.dart

RegisterFirst.dart



RegisterSecond.dart

RegisterThird.dart



There is no relevantPage code architecture please refer to:Flutter implements page jump and jump value (named route, named route value)

Major changes:

Here is responsible for Posting the main code:

Login.dart

import 'package:flutter/material.dart';

class LoginPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('login'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            SizedBox(height: 40,),
            Text('This is a login page. Clicking login will perform the login action.'),
            RaisedButton(
              child: Text('login'), onPressed: (){ }, ) ], ), ), ); }}Copy the code

RegisterFirst.dart

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

class RegisterFirstPage extends StatelessWidget {
  const RegisterFirstPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("Step one -- Enter your phone number.")
        ),
        body:Column(
          children: <Widget>[
            SizedBox(height: 40),
            Text("This is the first step to register, please enter your phone number and click next."),
            SizedBox(height: 40),
            RaisedButton(
              child: Text('Next step'),
              onPressed: (){
// Navigator.pushNamed(context, '/registerSecond');

                // Replace the route
                 // Click the button to jump to the second page, and is a replacement, simply can understand the meaning of destroyed
                Navigator.of(context).pushReplacementNamed('/registerSecond'); },)],)); }}Copy the code

RegisterSecond.dart

import 'package:flutter/material.dart';


class RegisterSecondPage extends StatelessWidget {
  const RegisterSecondPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("Step two - Captcha.")
        ),body:Column(
      children: <Widget>[
        SizedBox(height: 40),
        Text("Enter the verification code to complete registration."),
        SizedBox(height: 40),
        RaisedButton(
          child: Text('Next step'),
          onPressed: (){
             Navigator.pushNamed(context, '/registerThird');

            // Replace the route
// Navigator.of(context).pushReplacementNamed('/registerThird');},)],)); }}Copy the code

RegisterThird.dart

import 'package:flutter/material.dart';
import 'package:flutter_app15/pages/Tabs.dart';

class RegisterThirdPage extends StatelessWidget {
  const RegisterThirdPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Step 3 - Complete registration")
      ),body:Column(
        children: <Widget>[
          SizedBox(height: 40),
          Text("Enter your password to complete registration"),
          SizedBox(height: 40),
          RaisedButton(
            child: Text('sure'),
            onPressed: (){

              /** * return root pushAndRemoveUntil * New MaterialPageRoute(Builder: (context) => new Tabs()), */
              Navigator.of(context).pushAndRemoveUntil(
                  new MaterialPageRoute(builder: (context) => new Tabs(index:1)),
                  (route) => route == null); },)],)); }}Copy the code

Setting.dart

import 'package:flutter/material.dart';

class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState(a) => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
       Column(
         children: <Widget>[
           ListTile(
             title: Text('I am a text'),
           ),
           ListTile(
             title: Text('I am a text'),
           ),
           ListTile(
             title: Text('I am a text'),
           ),
           ListTile(
             title: Text('I am a text'),
           ),
           ListTile(
             title: Text('I am a text'),
           )
         ],
       ),
        RaisedButton(
          child: Text('Go to the login page'),
          onPressed: (){
            Navigator.pushNamed(context, '/login');
          },
        ),

        RaisedButton(
          child: Text('Go to the registration page'),
          onPressed: (){
            Navigator.pushNamed(context, '/registerFirst'); },)],); }}Copy the code



Routes.dart

import 'package:flutter_app15/pages/user/RegisterThird.dart';

import '.. /pages/Form.dart';
import '.. /pages/Search.dart';
import '.. /pages/Tabs.dart';
import '.. /pages/Product.dart';
import '.. /pages/ProductInfo.dart';

import '.. /pages/user/Login.dart';
import '.. /pages/user/RegisterFirst.dart';
import '.. /pages/user/RegisterSecond.dart';
import '.. /pages/user/RegisterThird.dart';

import 'package:flutter/material.dart';

// Configure routes
final  routes={                   // Configure the named route
  '/':(context)=>Tabs(),  // The named routing value is required
  '/form':(context)=>FormPage(),
  '/product':(context)=>ProductPage(),  // The named routing value is required
  '/productInfoPage':(context,{arguments})=>ProductInfoPage(arguments:arguments),  // The named routing value is required
  '/search':(context,{arguments})=>SearchPage(arguments:arguments),  // The named routing value is required
  '/login':(context)=>LoginPage(),
  '/registerFirst':(context)=>RegisterFirstPage(),
  '/registerSecond':(context)=>RegisterSecondPage(),
  '/registerThird':(context)=>RegisterThirdPage()
};

// Fixed writing
var oonGenerateRoute=(RouteSettings settings) {
  // Unified processing
  final String name = settings.name;    // Get the name of the named route, for example: '/form'
  final Function pageContentBuilder = routes[name];  // get the key of the named route to get the value, for example :(context)=>FormPage(),
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

Define the top Tab switch, the bottom Tab combined with the top Tab to achieve similar to the headline page layout

Effect:

Home.dart



AppBarDemo.dart



Categroy.dart

Bottom navigation Basic architecture Reference: The Flutter implements bottom navigation

main.dart

import 'package:flutter/material.dart';

import 'routes/Routes.dart';

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

class MyApp extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false.// Remove the debug icon

      initialRoute: '/'.// The route is loaded during initialization
// home: Tabs(), // pull all the code out as a TAB, then pull out as an initialRoute component, initialRoute: '/',
        // Configure the named route
        onGenerateRoute: oonGenerateRoute // Assign the exported routing specification to the left, not to the execution, remember!); }}Copy the code

Routes.dart

import '.. /pages/Tabs.dart';

import 'package:flutter/material.dart';

import '.. /pages/AppBarDemo.dart';

// Configure routes
final  routes={                   // Configure the named route
  '/':(context)=>Tabs(),  // The named routing value is required
  '/appBarDemo':(context)=>AppBarDemoPage()
};

// Fixed writing
var oonGenerateRoute=(RouteSettings settings) {
  // Unified processing
  final String name = settings.name;    // Get the name of the named route, for example: '/form'
  final Function pageContentBuilder = routes[name];  // get the key of the named route to get the value, for example :(context)=>FormPage(),
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

Tabs.dart

import 'package:flutter/material.dart';
import 'tabs/Category.dart';
import 'tabs/Home.dart';
import 'tabs/Setting.dart';

class Tabs extends StatefulWidget {
  final index;    // Use it to determine the coordinates of the bottom navigation items to display when returning the root route

Tabs({Key key,this.index=0}) : super(key: key);   // This parameter is optional. The default value is 0

  @override
  _TabsState createState(a) => _TabsState(this.index); // Pass the current coordinate to the _TabsState class via the _TabsState constructor
}

class _TabsState extends State<Tabs> {
  int _currentIndex;
  _TabsState(index){    // When the Tabs class is called, the parameter is passed to _currentIndex
    this._currentIndex=index;
  }

  List _pageList = [    // First put all pages in the List collection
    HomePage(),
    CategoryPage(),
    SettingPage()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FlutterDemo'),
      ),
      body: this._pageList[this._currentIndex],   // Then get the corresponding page Settings according to the subscript and put them in the body
      bottomNavigationBar: BottomNavigationBar(     // Customize the bottom navigation bar

          currentIndex: this._currentIndex,   // Configure the corresponding index value selected
          onTap: (int index){
            setState(() {     // Change the state
              this._currentIndex=index;      // Change the selected Tab coordinate
            });
          },
//Icon size: 45.0, //Icon size, default is about 20
          fixedColor: Colors.red, // The selected color, which is blue by default
          items:[
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.home),
                title: Text('home')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.category),
                title: Text('classification')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.settings),
                title: Text('set'] [] [] [] [ }}Copy the code

AppBarDemo.dart

import 'package:flutter/material.dart';

class AppBarDemoPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(      // Top navigation toggle
      length: 2.// Must configure: the total number of top ICONS

      child: Scaffold(
        appBar: AppBar(
          title: Text('AppBarDemoPage'),
          backgroundColor: Colors.red,    // Set the background color on the navigation
          centerTitle: true.// Settings: On both Android and ios, the title is displayed in the center
// leading: Icon(icon.menu), // add an Icon to the left of the navigation, default is to return the Icon, cannot listen
// leading: IconButton(
// icon: icon (icon.menu), // add an icon to the left of the navigation
// onPressed: (){
// print('menu');
/ /},
/ /),
// Actions: 
      
       [// Add the icon button on the right
      
// IconButton(
// icon: Icon(Icons.search),
// onPressed: (){
// print('search');
/ /},
/ /),
// add a second IconButton on the right
// icon: Icon(Icons.settings),
// onPressed: (){
// print('settings');
/ /},
/ /)
/ /,
        bottom: TabBar(
          tabs: <Widget>[         // Configure the "Tabs" menu. The system will display the elements according to the order configured here and the order of the elements in the following body:TabBarView
            Tab(text: 'hot',),
            Tab(text: 'recommendations',)
          ],
        ),
        ),
        body: TabBarView(
          children: <Widget>[
           ListView(
             children: <Widget>[
               ListTile(
                 title: Text('First TAB'),
               ),
               ListTile(
                 title: Text('First TAB'),
               ),
               ListTile(
                 title: Text('First TAB'),
               )
             ],
           ),
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('Second TAB'),
                ),
                ListTile(
                  title: Text('Second TAB'),
                ),
                ListTile(
                  title: Text('Second TAB'() () () () () ( }}Copy the code

Home.dart

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState(a) => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            child: Text('Jump to appBar'),
            onPressed: (){
              // Route jump
              Navigator.pushNamed(context, '/appBarDemo'); },)],),); }}Copy the code

Categroy.dart

import 'package:flutter/material.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState(a) => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(      // That Scaffold is nested within that Scaffold
        appBar: AppBar(
          backgroundColor: Colors.black26,

          /** * Placing the top navigation bar in the title is to prevent two top bugs that occur when that Scaffold is nested within that Scaffold. To fix this bug * we can place the top navigation bar in the title */
        title: Row(
            children: <Widget>[
              Expanded(
                child: TabBar(
                  indicatorColor: Colors.blue,   // Set the color of the indicator
                  labelColor: Colors.blue,   // Settings: Select the color
                  unselectedLabelColor: Colors.white, // Settings: color is not selected
                  indicatorSize: TabBarIndicatorSize.label,   // When selected, the bottom bar is as long as the text. The default is TAB

                  tabs: <Widget>[
                    Tab(text: 'hot'),
                    Tab(text: 'recommendations',),
                    Tab(text: '三',),
                    Tab(text: 'four',)
                  ],
                ),
              )
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('First TAB'),
                ),
                ListTile(
                  title: Text('First TAB'),
                ),
                ListTile(
                  title: Text('First TAB'),
                )
              ],
            ),
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('Second TAB'),
                ),
                ListTile(
                  title: Text('Second TAB'),
                ),
                ListTile(
                  title: Text('Second TAB'),
                )
              ],
            ),
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('Third TAB'),
                ),
                ListTile(
                  title: Text('Third TAB'),
                ),
                ListTile(
                  title: Text('Third TAB'),
                )
              ],
            ),
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('Fourth TAB'),
                ),
                ListTile(
                  title: Text('Fourth TAB'),
                ),
                ListTile(
                  title: Text('Fourth TAB'() () () () () ( }}Copy the code

Demo directory structure:







12. TabController defines the top TAB switch and introduces the lifecycle functions

Effect:

Home.dart



TabBarController.dart



Home.dart

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState(a) => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            child: Text('Jump to appBar'),
            onPressed: (){
              // Route jump
              Navigator.pushNamed(context, '/appBarDemo');
            },
          ),
          SizedBox(width: 10,),
          RaisedButton(
            child: Text('TabController defines top TAB switchover '),
            onPressed: (){
              // Route jump
              Navigator.pushNamed(context, '/tabBarController'); },)],),); }}Copy the code

TabBarController.dart

import 'package:flutter/material.dart';

class TabBarControllerPage extends StatefulWidget {
  @override
  _TabBarControllerPageState createState(a) => _TabBarControllerPageState();
}

class _TabBarControllerPageState extends State<TabBarControllerPage> with SingleTickerProviderStateMixin {
  TabController _tabController;   // The second way to configure the top navigation,

  @override
  void dispose(a) {    // Declare periodic functions to be called upon destruction
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose(); // Destroy the _tabController as well
  }

  @override
  void initState(a) {    // Life cycle function, automatically called when initialization
    // TODO: implement initState
    super.initState();
    _tabController=new TabController(length: 2, vsync: this);   // When the constructor is called to initialize, it is instantiated, with parameter 1 being length and parameter 2 being fixed

    _tabController.addListener((){
      print(_tabController.index);  // Listen for subscripts that change
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TabBarControllerpage'),
        bottom: TabBar(
          controller: this._tabController, // Note that the difference here is to set controller= _tabController above
          tabs: <Widget>[
            Tab(text:"Hot"),
            Tab(text:"Recommended"),
          ],
        ),
      ),
      body: TabBarView(
        controller: this._tabController, // Note that this also needs to be configured
        children: <Widget>[
          Center(child: Text('hot'),),
          Center(child: Text('recommendations'),),),); }}Copy the code

Also remember to configure named routes:

Routes.dart

import '.. /pages/Tabs.dart';

import 'package:flutter/material.dart';

import '.. /pages/AppBarDemo.dart';

import '.. /pages/TabBarController.dart';



// Configure routes
final  routes={                   // Configure the named route
  '/':(context)=>Tabs(),  // The named routing value is required
  '/appBarDemo':(context)=>AppBarDemoPage(),
  '/tabBarController':(context)=>TabBarControllerPage()
};

// Fixed writing
var oonGenerateRoute=(RouteSettings settings) {
  // Unified processing
  final String name = settings.name;    // Get the name of the named route, for example: '/form'
  final Function pageContentBuilder = routes[name];  // get the key of the named route to get the value, for example :(context)=>FormPage(),
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

13, Drawer sidebar, and layout of sidebar content

Effect:

Tabs.dart



User.dart



Tabs.dart

Project Structure:









main.dart

import 'package:flutter/material.dart';

import 'routes/Routes.dart';

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

class MyApp extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false.// Remove the debug icon

      initialRoute: '/'.// The route is loaded during initialization
// home: Tabs(), // pull all the code out as a TAB, then pull out as an initialRoute component, initialRoute: '/',
        // Configure the named route
        onGenerateRoute: oonGenerateRoute // Assign the exported routing specification to the left, not to the execution, remember!); }}Copy the code

Routes.dart

import '.. /pages/Tabs.dart';

import 'package:flutter/material.dart';

import '.. /pages/User.dart';

// Configure routes
final  routes={                   // Configure the named route
  '/':(context)=>Tabs(),  // The named routing value is required
  '/user':(context)=>UserPage()
};

// Fixed writing
var oonGenerateRoute=(RouteSettings settings) {
  // Unified processing
  final String name = settings.name;    // Get the name of the named route, for example: '/form'
  final Function pageContentBuilder = routes[name];  // get the key of the named route to get the value, for example :(context)=>FormPage(),
  if(pageContentBuilder ! =null) {
    if(settings.arguments ! =null) {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      final Route route = MaterialPageRoute(
          builder: (context) => pageContentBuilder(context));
      returnroute; }}};Copy the code

User.dart Jumps to the user-center code

import 'package:flutter/material.dart';

class UserPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('User Center'),),); }}Copy the code

Tabs. Dart Sidebar main code

import 'package:flutter/material.dart';
import 'tabs/Category.dart';
import 'tabs/Home.dart';
import 'tabs/Setting.dart';

class Tabs extends StatefulWidget {
  final index;    // Use it to determine the coordinates of the bottom navigation items to display when returning the root route

Tabs({Key key,this.index=0}) : super(key: key);   // This parameter is optional. The default value is 0

  @override
  _TabsState createState(a) => _TabsState(this.index); // Pass the current coordinate to the _TabsState class via the _TabsState constructor
}

class _TabsState extends State<Tabs> {
  int _currentIndex;
  _TabsState(index){    // When the Tabs class is called, the parameter is passed to _currentIndex
    this._currentIndex=index;
  }

  List _pageList = [    // First put all pages in the List collection
    HomePage(),
    CategoryPage(),
    SettingPage()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FlutterDemo'),
      ),
      body: this._pageList[this._currentIndex],   // Then get the corresponding page Settings according to the subscript and put them in the body
      bottomNavigationBar: BottomNavigationBar(     // Customize the bottom navigation bar

          currentIndex: this._currentIndex,   // Configure the corresponding index value selected
          onTap: (int index){
            setState(() {     // Change the state
              this._currentIndex=index;      // Change the selected Tab coordinate
            });
          },
//Icon size: 45.0, //Icon size, default is about 20
          fixedColor: Colors.red, // The selected color, which is blue by default
          items:[
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.home),
                title: Text('home')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.category),
                title: Text('classification')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.settings),
                title: Text('set')
            )
          ]
      ),
      drawer: Drawer(               // Left sidebar
        child: Column(
          children: <Widget>[
            Row(                        // Row and Expanded are used together so that the bottom lines horizontally cover the screen
              children: <Widget>[
                Expanded(
                  child:   UserAccountsDrawerHeader(
                    accountName: Text('Smart boy'),    / / user name
                    accountEmail: Text('[email protected]'), / / email
                    currentAccountPicture: CircleAvatar(    // Set the circular head
                      backgroundImage: NetworkImage('https://www.itying.com/images/flutter/3.png'),
                    ),
                    decoration: BoxDecoration(        // Set the background image
                      image: DecorationImage(
                        image: NetworkImage('https://www.itying.com/images/flutter/2.png'),
                        fit: BoxFit.cover
                      )
                    ),
                    otherAccountsPictures: <Widget>[    // Display the image to the right of the head
                      Image.network('https://www.itying.com/images/flutter/4.png'),
                      Image.network('https://www.itying.com/images/flutter/5.png'),
                    ],
                  )
                )
              ],
            ),
            ListTile(
              leading: CircleAvatar(
                child: Icon(Icons.home),
              ),
              title: Text('My Space'),
            ),
            Divider(),
            ListTile(
              leading: CircleAvatar(
                child: Icon(Icons.people),
              ),
              title: Text('User Center'),
              onTap: (){                  // Sidebar listener
                Navigator.of(context).pop();  // Hide the sidebar
                Navigator.pushNamed(context, '/user');
              },
            ),
            Divider(),
            ListTile(
              leading: CircleAvatar(
                child: Icon(Icons.settings),
              ),
              title: Text('Setting center'),
            ),
            Divider(),
          ],
        ),
      ),
      endDrawer: Drawer(            // Right sidebar
        child: Text('Right sidebar'),),); }}Copy the code

Dart, Home. Dart, Setting. Dart is not related to this chapter. The Flutter implements a TabController that defines the top TAB switch and introduces the lifecycle functions

RaisedButton, FlatButton, OutlineButton, IconButton, ButtonBar and custom button components

Effect:

import 'package:flutter/material.dart';

class ButtonDemoPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Button Demo page'),

        actions: <Widget>[
          IconButton(           // Button
            icon: Icon(Icons.settings),
            onPressed: (){

            },
          )
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,    // Vertical center
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,  // The level is centered
            children: <Widget>[
              RaisedButton(
                child: Text('Normal button'),
                onPressed: (){
                  print('Normal button');
                },
              ),
              SizedBox(width: 10,),
              RaisedButton(
                child: Text('Color button'),
                color: Colors.blue, // The background color
                textColor: Colors.white,  // The font is white
                onPressed: (){
                  print('Color button');
                },
              ),
              SizedBox(width: 10,),
              RaisedButton(
                child: Text('Shadow button'),
                color: Colors.blue, // The background color
                textColor: Colors.white,  // The font is white
                elevation: 10.// Set the shadow effect. The larger the value, the better the shadow effect
                onPressed: (){
                  print('Shadow button');
                },
              ),
            ],
          ),
          RaisedButton.icon(
// onPressed: null,
              icon: Icon(Icons.search),
              label: Text('Icon button'),
            color: Colors.blue,
              textColor: Colors.white,
            onPressed: (){
                print('Icon button');
            },
          ),
          SizedBox(height: 5,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(      // Use the container to set the width and height of the button
                height: 50,
                width: 300,
                child: RaisedButton(
                  child: Text('Width height'),
                  color: Colors.blue,
                  textColor: Colors.white,
                  elevation: 20,
                  onPressed: (){
                    print('Width height');
                  },
                ),
              )
            ],
          ),
          SizedBox(height: 5,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
             Expanded(            // Spread the width of the screen
               child: Container(    // Use the container to set the height
                 height: 80,
                 margin: EdgeInsets.all(10),    // Set: left-right spacing 10
                 child:  RaisedButton(
                   child: Text('Adaptive button'),
                   color: Colors.blue,
                   textColor: Colors.white,
                   elevation: 20,
                   onPressed: (){
                     print('Adaptive button');
                   },
                 ),
               )
             )
            ],
          ),
          SizedBox(height: 10,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text('Rounded Corner Button'),
                color: Colors.blue,
                textColor: Colors.white,
                elevation: 20,
                shape: RoundedRectangleBorder(      // Rounded button
                  borderRadius: BorderRadius.circular(10)     // Fillet radian
                ),
                onPressed: (){
                  print('Rounded Corner Button');
                }),
              SizedBox(width: 10,),
             Container(
               height: 80.// Set: height, also known as diameter
               child:  RaisedButton(
                   child: Text('Round button'),
                   color: Colors.blue,
                   textColor: Colors.white,
                   elevation: 20,
                   splashColor: Colors.red,  // Set water ripple color when long press button
                   shape: CircleBorder(      // Rounded button
                       side: BorderSide(
                           color: Colors.white
                       )
                   ),
                   onPressed: (){
                     print('Round button');
                   }),
             ),
              FlatButton(               // The flat button has no shadow by default and has no background color by default
                child: Text('Flat button'),
                color: Colors.blue,
                textColor: Colors.yellow,
                onPressed: (){
                  print('Flat button');
                },
              )
            ],
          ),
          SizedBox(height: 10,),
          OutlineButton(        // Button with border
            child: Text('Border button'),
// Color: color. red, no effect. This is the feature of the border button
// textColor: color. yellow, // has effect
            onPressed: (){
              print('Border button');
            },
          ),
          SizedBox(height: 5,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(                   // Adaptive horizontal tiling
                child: Container(
                  margin: EdgeInsets.all(20),   // Spacing up, down, left, and right 20
                  height: 50,
                  child: OutlineButton(
                    child: Text('registered'),
                    onPressed: (){

                    },
                  ),
                ),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ButtonBar(
                children: <Widget>[
                  RaisedButton(
                    child: Text('login'),
                    color: Colors.blue,
                    textColor: Colors.white,
                    elevation: 20,
                    onPressed: (){
                      print('login');
                    },
                  ),
                  RaisedButton(
                    child: Text('registered'),
                    color: Colors.blue,
                    textColor: Colors.white,
                    elevation: 20,
                    onPressed: (){
                      print('registered');
                    },
                  ),
                  MyButton(text:'Custom button',height: 60.0,width: 100,pressed: (){
                    print('Custom button'); })],)],)],),); }}// Customize the button component

class MyButton extends StatelessWidget {
  final text;
  final pressed;
  final double width;
  final double height;
  const MyButton({this.text="".this.pressed=null.this.width=80.0.this.height=30.0});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: this.height,
      width: this.width,
      child: RaisedButton(
        child: Text(this.text),
        onPressed: this.pressed, ), ); }}Copy the code

15. Similar to the raised navigation button on the bottom of the Idler App

Effect:

The basic architecture of the bottom navigation bar is referenced here: Flutter implements bottom navigation

How can I change the icon in the middle into a raised button like the bottom navigation button of the Idler App

Tabs.dart

import 'package:flutter/material.dart';
import 'tabs/Category.dart';
import 'tabs/Home.dart';
import 'tabs/Setting.dart';

class Tabs extends StatefulWidget {
  final index;    // Use it to determine the coordinates of the bottom navigation items to display when returning the root route

Tabs({Key key,this.index=0}) : super(key: key);   // This parameter is optional. The default value is 0

  @override
  _TabsState createState(a) => _TabsState(this.index); // Pass the current coordinate to the _TabsState class via the _TabsState constructor
}

class _TabsState extends State<Tabs> {
  int _currentIndex;
  _TabsState(index){    // When the Tabs class is called, the parameter is passed to _currentIndex
    this._currentIndex=index;
  }

  List _pageList = [    // First put all pages in the List collection
    HomePage(),
    CategoryPage(),
    SettingPage()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FlutterDemo'),
      ),
      floatingActionButton: Container(
        height: 70,
        width: 70,
        padding: EdgeInsets.all(8), // Set: padding 8
        margin: EdgeInsets.only(top: 2), // Set: margin 2, so that the float button is down close to the classified Tab text
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(40),
          color: Colors.white
        ),
        child: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: (){
            setState(() {   // We can rerender the page, because _currentIndex is changed to 1, so the page will jump to the category page
              this._currentIndex=1;   // Click the float button to switch to the category page
            });
          },
          backgroundColor: this._currentIndex==1? Colors.red:Colors.yellow// Use the ternary operator to change the background color of the float button when selected
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,  // The float button is centered at the bottom of the screen
      body: this._pageList[this._currentIndex],   // Then get the corresponding page Settings according to the subscript and put them in the body
      bottomNavigationBar: BottomNavigationBar(     // Customize the bottom navigation bar

          currentIndex: this._currentIndex,   // Configure the corresponding index value selected
          onTap: (int index){
            setState(() {     // Change the state
              this._currentIndex=index;      // Change the selected Tab coordinate
            });
          },
//Icon size: 45.0, //Icon size, default is about 20
          fixedColor: Colors.red, // The selected color, which is blue by default
          items:[
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.home),
                title: Text('home')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.category),
                title: Text('classification')
            ),
            BottomNavigationBarItem(      // Set navigation items
                icon:Icon(Icons.settings),
                title: Text('set'] [] [] [] [ }}Copy the code

16. Single line text box, multiple checkboxes

Effect:

TextField.dart



CheckBox.dart

TextField.dart

import 'package:flutter/material.dart';

class TextFieldDemoPage extends StatefulWidget {
  @override
  _TextFieldDemoPageState createState(a) => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
  var _username = new TextEditingController();    // Assign a value to the form during initialization
  var _password;    // Initialize without assigning a value

  @override
  void initState(a) {
    // TODO: implement initState
    super.initState();
    _username.text='Initial value';       // Call text assignment
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Presentation Page'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
// child: TextDemo(),
      child: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              hintText: 'Please enter a user name'
            ),
            controller: _username,    // The object is uniquely identified and is assigned a value during initialization
            onChanged: (value){       // The event that is triggered when the text box changes. If the text box changes, the system automatically assigns the value of the input box to value
              setState(() {
                _username.text = value;
              });
            },
          ),
          SizedBox(height: 20,),
          TextField(
            obscureText: true.// Enable the password mode
            decoration: InputDecoration(
                hintText: 'Please enter your password'
            ),
            onChanged: (value){       // The event that is triggered when the text box changes. If the text box changes, the system automatically assigns the value of the input box to value
              setState(() {
                this._password = value;    // Note that the.text is not written here, so when we get the value, we don't need to write.text, we just write the variable name
              });
            },
          ),
          SizedBox(height: 40,),
          Container(
            width: double.infinity,   // Indicates that the width of the Container becomes adaptive
            height: 40,
            child: RaisedButton(
              child: Text('login'),
              onPressed: (){
                print(this._username.text);   // Print the user name
                print(this._password);   // Print the password}, color: Colors.blue, textColor: Colors.white, ), ) ], ), ), ); }}// Special effect examples, but not called here, to see the effect directly in the body: TextDemo
class TextDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          TextField(), // Input field form
          SizedBox(height: 20,),
          TextField(
            decoration: InputDecoration(
                hintText: 'Please enter search content'.// Hint text, which is the Android equivalent of hint
                border: OutlineInputBorder()    // Add borders around the form
            ),
          ),
          SizedBox(height: 20,),
          TextField(
            maxLines: 4.// Set the maximum number of rows
            decoration: InputDecoration(
                hintText: 'Multi-line text box'.// Multiline text box
                border: OutlineInputBorder()    // Add borders around the form
            ),
          ),
          SizedBox(height: 20,),
          TextField(
            obscureText: true.// Enable the password mode
            decoration: InputDecoration(
                hintText: 'Password box'.// Multiline text box
                border: OutlineInputBorder()    // Add borders around the form
            ),
          ),
          SizedBox(height: 20,),
          TextField(                            // Special effect, when entering information, the user name dynamically run to the border session prompt
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Username'
            ),
          ),
          SizedBox(height: 20,),
          TextField(                            // Special effect, when entering information, the user name dynamically run to the border session prompt
            obscureText: true,
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'password'
            ),
          ),
          SizedBox(height: 20,),
          TextField(                            // Add an icon in front of the text box
            decoration: InputDecoration(
                icon: Icon(Icons.people),
                hintText: 'Please enter a user name')))))))); }}// Enumerate the style and pattern of the textbox. To use it, just call the TextDemo component in the body
Copy the code

CheckBox.dart

import 'package:flutter/material.dart';

class CheckBoxPage extends StatefulWidget {

  @override
  _CheckBoxPageState createState(a) => _CheckBoxPageState();
}

class _CheckBoxPageState extends State<CheckBoxPage> {
  var flag = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('checkbox'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(children: <Widget>[
            Checkbox(               // Multi-checkbox components
              value: this.flag,
              onChanged: (v){   // Trigger when multiple checkbox values change
                setState(() {
                  this.flag=v;
                });
              },
              activeColor: Colors.red,    // Settings: the color when selected
            ),
          ],),
          Row(
            children: <Widget>[
              Text(this.flag?'selected':'Not selected')    // Display the value of checkBox
            ],
          ),
          SizedBox(height: 40,),
          CheckboxListTile(       // Multi-checkbox components
            value: this.flag,
            onChanged: (v){   // Trigger when multiple checkbox values change
              setState(() {
                this.flag=v;
              });
            },
            title: Text('title'),
            subtitle: Text('This is a secondary title.'),
          ),
          Divider(),
          CheckboxListTile(       // Multi-checkbox components
            value: this.flag,
            onChanged: (v){   // Trigger when multiple checkbox values change
              setState(() {
                this.flag=v;
              });
            },
            title: Text('title'),
            subtitle: Text('This is a secondary title.'), secondary: Icon(Icons.help), ) ], ), ); }}Copy the code

17, multi-line text box, switch button, multi-checkbox, Radio button, RadioListTile, Radio, form

Effect:

Radio.dart



FormDemo.dart

Radio.dart

import 'package:flutter/material.dart';

class RadioPage extends StatefulWidget {
  @override
  _RadioPageState createState(a) => _RadioPageState();
}

class _RadioPageState extends State<RadioPage> {
  int sex=1;
  bool flag = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Radio'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
// Row(
// children: 
      
       [
      
// Text(' male: '),
// Radio(// similar to the Radio button group
// value: 1,
// onChanged: (v){//Radio changes when the event is triggered
// setState(() {// re-render the interface
// this.sex=v;
/ /});
/ /},
// groupValue: this.sex, // If the values are the same, it means they belong to the same radio button group
/ /),
// SizedBox(width: 20,),
// Text(' female: '),
// Radio(// similar to the Radio button group
// value: 2,
// onChanged: (v){//Radio changes when the event is triggered
// setState(() {// re-render the interface
// this.sex=v;
/ /});
/ /},
// groupValue: this.sex, // If the values are the same, it means they belong to the same radio button group
/ /)
/ /,
/ /),
// Row(
// children: 
      
       [
      
${this.sex}'), // print the subscript
// Text(this.sex==1? 'male ':' female ') // Prints the value using the ternary operator
/ /,
/ /),
          SizedBox(height: 40,),
            RadioListTile(
              value: 1,
              onChanged: (v){         // When Radio changes, an event is triggered
                setState(() {   // Re-render the interface
                  this.sex=v;
                });
              },
              groupValue: this.sex,   // If the values are the same, they all belong to the same radio button group
              title: Text('title'),
              subtitle: Text('This is a secondary title.'),
              secondary: Icon(Icons.help),    // Settings: icon
              selected: this.sex==1.// When selected, the text shines
            ),
            RadioListTile(
              value: 2,
              onChanged: (v){         // When Radio changes, an event is triggered
                setState(() {   // Re-render the interface
                  this.sex=v;
                });
              },
              groupValue: this.sex,   // If the values are the same, they all belong to the same radio button group
              title: Text('title'),
              subtitle: Text('This is a secondary title.'),
              secondary: Image.network('https://www.itying.com/images/flutter/1.png'), // Load the remote image
              selected: this.sex==2.// When selected, the text shines
            ),
            SizedBox(height: 40,),
            Switch(               //Android switch button
              value: this.flag,
              onChanged: (v){
                setState(() {
                  print((v));
                  this.flag=v; }); },)],),); }}Copy the code

FormDemo.dart

import 'package:flutter/material.dart';

class FormDemoPage extends StatefulWidget {
  @override
  _FormDemoPageState createState(a) => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
  String username;
  int sex=1;  // Default 1 is male
  String info = ' ';

  List hobby=[
    {
      'checked':true.'title':'eat'
    },
    {
      'checked':false.'title':'sleep'
    },
    {
      'checked':true.'title':'Write code'},];List<Widget> _getHobby(a){   // Return multiple checkboxes

    List<Widget> tempList=[];

    for(var i=0; i<this.hobby.length; i++){//
      tempList.add(Text(this.hobby[i]['title'] +":"));
      tempList.add(
        Checkbox(
          value: this.hobby[i]['checked'],
          onChanged: (value){
            setState(() {
              this.hobby[i]['checked']=value; }); }));//
// tempList.add(
// Row(
// children: 
      
       [
      
// Text(this.hobby[i]['title']+":"),
// Checkbox(
// value: this.hobby[i]['checked'],
// onChanged: (value){
// setState(() {
// this.hobby[i]['checked']=value;
/ /});
/ /},
/ /)
/ /,
/ /)
/ /);
    }
    return tempList;
  }

  void _sexChanged(value){    // Pull out the listener of the radio group button
    setState(() {
      this.sex=value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Student Information Registration System),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                hintText: 'Enter user information'
              ),
              onChanged: (value){
                setState(() {
                  this.username=value;
                });
              },
            ),
              SizedBox(height: 10,),
              Row(
                children: <Widget>[
                  Text('male'),
                  Radio(
                    value: 1,
                    onChanged: this._sexChanged,
                    groupValue: this.sex,
                  ),
                  SizedBox(width: 20,),
                  Text('woman'),
                  Radio(
                    value: 2,
                    onChanged: this._sexChanged,
                    groupValue: this.sex,
                  )
                ],
              ),

            / / love
            SizedBox(height: 40,),
            Wrap(
              children: this._getHobby(),
            ),
            SizedBox(height: 20,),
            TextField(
              maxLines: 4,
              decoration: InputDecoration(
                  hintText: 'Description',
                border: OutlineInputBorder()
              ),
              onChanged: (value){
                setState(() {
                  this.info=value;
                });
              },
            ),

            SizedBox(height: 40,),
            Container(
              width: double.infinity,   // Indicates that the width of the Container becomes adaptive
              height: 40,
              child: RaisedButton(
                child: Text('Submit information'),
                onPressed: (){
                  print(this.sex);   // Get the value of the radio button
                  print(this.username);   // Get the value of the textbox
                  print(this.hobby);    // Get the value of the multiple checkboxes
                  print(this.info);   // Obtain the description}, color: Colors.blue, textColor: Colors.white, ), ) ], ), ), ); }}Copy the code

Call native time picker, date picker, timestamp, Future async

Effect:

Refer to third-party libraries:Pub. Dev/packages/da…

In Pubspec.yaml, introduce the latest dependencies, which I have here

Introduce package names in related classes:

The import ‘package: date_format/date_format dart “;

Timestamp conversion demo: timestamp is the time stored in the server value, he with normal we see the value is not the same

// Convert date to timestamp:
var now = new DateTime.now();
print(now.millisecondsSinceEpoch);// The unit of milliseconds, 13 bit timestamp

// Convert timestamp to date:
var now = new DateTime.now();
var a=now.millisecondsSinceEpoch; / / timestamp
print(DateTime.fromMillisecondsSinceEpoch(a));
Copy the code

DatePicker.dart

import 'package:flutter/material.dart';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart' as prefix0;

class DatePickerPage extends StatefulWidget {
  @override
  _DatePickerPageState createState(a) => _DatePickerPageState();
}

class _DatePickerPageState extends State<DatePickerPage> {

  DateTime _nowDate = DateTime.now();

  var _nowTime = TimeOfDay(hour: 12,minute: 20);  // Initialization time value


  _showDatePicker() async{   // The date component of the Flutter gets asynchronous data


    // Obtain asynchronous data in mode 1: Obtain data through THEN
// showDatePicker(
// context:context,
// initialDate:_nowDate, // The current date
// firstDate:DateTime(1980), // start date
LastDate :DateTime(2100) // End date
// ).then((result){
// print(result);
/ /});

    * await means to wait for the asynchronous request and then assign the value to result * we can print the result to get the data */
    var result = await showDatePicker(context:context, initialDate:_nowDate, firstDate:DateTime)1980).// Start date
        lastDate:DateTime(2100).// End date
        locale: prefix0.Locale('zh') // Not required. If the operating system is Chinese, do not add it. If the operating system is not Chinese, do add it to make it Chinese
    );

// print(result);

    setState(() {
      this._nowDate = result; // Assign the value after the selected date to _nowDate
    });

  }

  _showTimePicker() async{    // The time component of the Flutter

  var result =  await showTimePicker( context:context, initialTime: _nowTime );

  setState(() {
    this._nowTime = result;
  });

  }

  @override
  void initState(a) {
    // TODO: implement initState
    super.initState();
    // var now = DateTime.now();

// print(now); / / the 12:23:06 2019-11-17. 811117
// print(now.millisecondsSinceEpoch); / / 1573964623294
/* print(DateTime.fromMicrosecondsSinceEpoch(1573964623294)); / / the 1970-01-19 13:12:44. 623294 * /

    print(formatDate(DateTime.now(), [yyyy, 'years', mm, 'month', dd]));

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DatePickerDemo'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(         // Make the component clickable
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
// Text('${_nowDate}'),
                    Text('${formatDate(_nowDate, [yyyy, 'years', mm, 'month', dd])}'), // Use a third-party library to display the data in the specified format
                    Icon(Icons.arrow_drop_down)
                  ],
                ),
                onTap: _showDatePicker,
              ),
              InkWell(         // Make the component clickable
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
// Text('${_nowDate}'),
// Text('${_nowTime}'), // display the value: TimeOfDay(07:26) is not what we want, so change to the following
                    Text('${_nowTime.format(context)}'), Icon(Icons.arrow_drop_down) ], ), onTap: _showTimePicker, ) ], ) ], ), ); }}Copy the code

In this case, the time is still in English. In this case, the solution is as follows:

The control flutter showDatePicker displays The Chinese date and the _Flutter time control displays the Chinese language. If you do not understand the tutorial, I have provided some screenshots of the code changes, so you can follow them:

pubspec.yaml

main.dart

Import ‘package:flutter_localizations/flutter_localizations. Dart’;



DatePicker.dart

  _showDatePicker() async{   // The date component of the Flutter gets asynchronous data


    // Obtain asynchronous data in mode 1: Obtain data through THEN
// showDatePicker(
// context:context,
// initialDate:_nowDate, // The current date
// firstDate:DateTime(1980), // start date
LastDate :DateTime(2100) // End date
// ).then((result){
// print(result);
/ /});

    * await means to wait for the asynchronous request and then assign the value to result * we can print the result to get the data */
    var result = await showDatePicker(context:context, initialDate:_nowDate, firstDate:DateTime)1980).// Start date
        lastDate:DateTime(2100).// End date
        locale: prefix0.Locale('zh') // Not required. If the operating system is Chinese, do not add it. If the operating system is not Chinese, do add it to make it Chinese
    );

// print(result);

    setState(() {
      this._nowDate = result; // Assign the value after the selected date to _nowDate
    });

  }
Copy the code

19, call third party time picker, date picker, timestamp

Effect:

If you encounter problems in English, see: The Flutter implementation calls native time pickers, date pickers, timestamps, Future asynchrony

I’ve explained the solution in detail in this blog post

So let’s start with this chapter

Refer to third-party libraries:

Pub. Dev/packages/fl…

Configuration: pubspec yaml

Import ‘package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart’;

DatePickerPub.dart

import 'package:flutter/material.dart';

import 'package:date_format/date_format.dart';

import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';    // Third party time component library

class DatePickerPubPage extends StatefulWidget {
  @override
  _DatePickerPubPageState createState(a) => _DatePickerPubPageState();
}

class _DatePickerPubPageState extends State<DatePickerPubPage> {

  DateTime _dateTime = DateTime.now();  // Get the current date

  _showDatePicker(){
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('sure', style: TextStyle(color: Colors.red)),
        cancel: Text('cancel', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse("1980-05-12"),    // Start date
      maxDateTime: DateTime.parse('2100-05-12'),    // Termination date
      initialDateTime: DateTime.now(),  // Get the current time
      dateFormat: 'YYYY M M D EEE,H hour: M minute'.// Set: year - month - day format

      pickerMode: DateTimePickerMode.datetime,    // show TimePicker
      locale: DateTimePickerLocale.zh_cn, // Settings: Language - Chinese
      onClose: () => print("----- onClose -----"),    // Cancel the listener
// onCancel: () => print('onCancel'),
// onChange: (dateTime, List
      
        index)
      
// setState(() {
// _dateTime = dateTime;
/ /});
/ /},
      onConfirm: (dateTime, List<int> index) {      // Determine the listenersetState(() { _dateTime = dateTime; }); }); }@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DatePickerPubDemo'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                child: Row(
                  children: <Widget>[
                    Text('${formatDate(_dateTime, [yyyy, 'years', mm, 'month', dd," ",HH,":",nn])}'), Icon(Icons.arrow_drop_down) ], ), onTap: _showDatePicker ) ], ) ], ), ); }}Copy the code

20. Rotation diagram flutter_swiper

Effect:

Figure 1



Figure 2



Figure 3

Figure 4.



Figure 5

Third-party library reference: pub.dev/packages/fl…

Configuration pubspec yaml

In the class that requires a round cast, the package name is:

The import ‘package: flutter_swiper/flutter_swiper dart “;

Figure 1, Figure 2 Code:

import 'package:flutter/material.dart';

import 'package:flutter_swiper/flutter_swiper.dart';

class SwiperPage extends StatefulWidget {
  @override
  _SwiperPageState createState(a) => _SwiperPageState();
}

class _SwiperPageState extends State<SwiperPage> {

  List<Map> imgList = [     // Settings: The image material for the round diagram
    {
      "url":"https://www.itying.com/images/flutter/1.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/2.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/3.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/4.png"},];@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo of the Rotograph Component'),
      ),
      body: Column(
        children: <Widget>[

          /** * Container must be installed to use the rotation diagram, otherwise error */
          Container(
// height: 150,
            /** * AspectRatio is used to cover the rotograph component to ensure that the image is not deformed. The optimal effect is obtained by adaptive adaptation according to the AspectRatio of the mobile phone screen */
// width: double. Infinity
            child: AspectRatio(
              aspectRatio: 16/9,
              child:    Swiper(
                itemBuilder: (BuildContext context,int index){    // Assign I to index for each loop
                return new Image.network(
                imgList[index]['url'],
                  fit: BoxFit.fill,);
              },
                itemCount: imgList.length,
                pagination: new SwiperPagination(), // Set: pager.
                loop: true.// Infinite loop
                autoplay: true.// Automatic rotation of images
// control: new SwiperControl(), // Set: left and right arrows)))))))); }}Copy the code

Figure 3 code

import 'package:flutter/material.dart';

import 'package:flutter_swiper/flutter_swiper.dart';

class SwiperPage extends StatefulWidget {
  @override
  _SwiperPageState createState(a) => _SwiperPageState();
}

class _SwiperPageState extends State<SwiperPage> {

  List<Map> imgList = [     // Settings: The image material for the round diagram
    {
      "url":"https://www.itying.com/images/flutter/1.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/2.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/3.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/4.png"},];@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo of the Rotograph Component'),
      ),
      body: Column(
        children: <Widget>[

          /** * Container must be installed to use the rotation diagram, otherwise error */
          Container(
// height: 150,
            /** * AspectRatio is used to cover the rotograph component to ensure that the image is not deformed. The optimal effect is obtained by adaptive adaptation according to the AspectRatio of the mobile phone screen */
// width: double. Infinity
            child: AspectRatio(
              aspectRatio: 16/9,
              child:   new Swiper(
                  layout: SwiperLayout.CUSTOM,
                  customLayoutOption: new CustomLayoutOption(
                      startIndex: -1,
                      stateCount: 3
                  ).addRotate([
                    -45.0/180.0.0.45.0/180
                  ]).addTranslate([
                    new Offset(-370.0, -40.0),
                    new Offset(0.0.0.0),
                    new Offset(370.0, -40.0)
                  ]),
                  itemWidth: 300.0,
                  itemHeight: 200.0,
                  itemBuilder: (context, index) {
                    return new Container(
// Color: color. grey, set: the background of the round image
                      child: new Center(
                        child: Image.network(imgList[index]['url'],fit: BoxFit.contain,), ), ); }, itemCount: imgList.length) ), ) ], ) ); }}Copy the code

Figure 4, Figure 5 code

import 'package:flutter/material.dart';

import 'package:flutter_swiper/flutter_swiper.dart';

class SwiperPage extends StatefulWidget {
  @override
  _SwiperPageState createState(a) => _SwiperPageState();
}

class _SwiperPageState extends State<SwiperPage> {

  List<Map> imgList = [     // Settings: The image material for the round diagram
    {
      "url":"https://www.itying.com/images/flutter/1.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/2.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/3.png"
    },
    {
      "url":"https://www.itying.com/images/flutter/4.png"},];@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo of the Rotograph Component'),
      ),
      body: Swiper(
        itemBuilder: (BuildContext context,int index){    // Assign I to index for each loop
          return new Image.network(
            imgList[index]['url'],
            fit: BoxFit.fill,);
        },
        itemCount: imgList.length,
// pagination: new SwiperPagination(), set: paginator
// control: new SwiperControl(), set: left and right arrows)); }}Copy the code

General dialog box, list dialog box, radio dialog box, Toast prompt

Effect:

Dialog.dart

Here I have all the code in one class, but to implement Toast’s functionality we need to introduce a third party library, see pub.dev/packages/fl…

Configuration: pubspec yaml



Introduced a package name: import ‘package: fluttertoast/fluttertoast dart “;

Dialog.dart

import 'package:flutter/material.dart';

import 'package:fluttertoast/fluttertoast.dart';

class DialogPage extends StatefulWidget {
  @override
  _DialogPageState createState(a) => _DialogPageState();
}

class _DialogPageState extends State<DialogPage> {

  _alertDialog() async{
     var result = await showDialog(// Get value outside of context:context, Builder: (context){
           return AlertDialog(      // System built-in: common dialog box
             title: Text('Prompt message! '),
             content: Text('Are you sure you want to delete it? '),
             actions: <Widget>[     / / listeners
               FlatButton(              // Confirm listening
                 child: Text('cancel'),
                 onPressed: (){
                   print('cancel');
                   Navigator.pop(context,'Cancle');
                 },
               ),
               FlatButton(              // Cancel listening
                 child: Text('sure'),
                 onPressed: (){
                   print('sure');
                   Navigator.pop(context,'OK'); },)],); }); print(result);// Obtain the data externally and print it
  }

  _simpleDialog() async{
   var result = await showDialog( context: context, builder: (context){
          return SimpleDialog(
            title: Text('Select content'),
            children: <Widget>[
              SimpleDialogOption(
                child: Text('Option A'),
                onPressed: (){
                  print('Option A');
                  Navigator.pop(context,'A');
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text('Option B'),
                onPressed: (){
                  print('Option B');
                  Navigator.pop(context,'B');
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text('Option C'),
                onPressed: (){
                  print('Option C');
                  Navigator.pop(context,'C'); }, ), Divider(), ], ); }); print(result); } _modelBottomSheet() async{var result = await showModalBottomSheet( context: context, builder: (context){
          return Container(
            height: 250.// Configure the height of the pop-up box at the bottom
            child: Column(
              children: <Widget>[
                ListTile(
                  title: Text(Share A ' '),
                  onTap: (){
                    Navigator.pop(context,Share A ' ');
                  },
                ),
                Divider(),
                ListTile(
                  title: Text('share B'),
                  onTap: (){
                    Navigator.pop(context,'share B');
                  },
                ),
                Divider(),
                ListTile(
                  title: Text('share C'),
                  onTap: (){
                    Navigator.pop(context,'share C'); },),],); }); print(result); } _toast(){ Fluttertoast.showToast( msg:"Prompt Message",
        toastLength: Toast.LENGTH_SHORT,    // Same as Android, short time prompt
        gravity: ToastGravity.CENTER,       / / in the middle
        timeInSecForIos: 1.// timeInSecForIos int (only for ios)
        backgroundColor: Colors.red,      // The background color
        textColor: Colors.white,          // Font color
        fontSize: 16.0                    // Font size
    );

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DialogDemo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Alert popup -AlerDialog'),
              onPressed: _alertDialog,
            ),
            SizedBox(height: 20,),
            RaisedButton(
              child: Text('Select popup -SimpleDialog'),
              onPressed: _simpleDialog,
            ),
            SizedBox(height: 20,),
            RaisedButton(
              child: Text('Something pops up at the bottom of ActionSheet -showModalBottomSheet'),
              onPressed: _modelBottomSheet,
            ),
            SizedBox(height: 20,),
            RaisedButton(
              child: Text('Toasts - FlutterToast Third Party library'), onPressed: _toast, ) ], ), ), ); }}Copy the code