Basic Widgets

Important concepts

Everything is component. All elements of Flutter are made up of components. For example, a layout element, an animation, a decorative effect, etc.

Container, the Container

The Container component contains a child widget that has alignment, padding, and other properties to facilitate the placement of children during the layout.

attribute

The property name type instructions
key Key Control how one widget replaces another widget in the tree
alignment AlignmentGeometry Aligns the child with the Container. This property works if the size of the Container or the parent of the Container is larger than the size of the child. There are several alignments.
child Widget The children contained in the container
constraints BoxConstraints Additional constraints added to the child
decoration Decoration If the Decoration is drawn after the child, if the Decoration is set to Decoration, you cannot set the color property, otherwise you will report an error, and you should set the color in Decoration instead
foregroundDecoration Decoration Decoration drawn in front of the child
margin EdgeInsetsGeometry The white space around Decoration and Child is not part of the content area
padding EdgeInsetsGeometry The space inside the Decoration, if you have a child, the child is inside the padding.
transform Matrix4 Set the Container transformation matrix to Matrix4
  • The difference between padding and margin: padding is contained within Content, while margin is the outer boundary. If you set the click event, the padding area will respond, while the Margin area will not.

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: 'the container sample',
      home: HomePage(),
    ));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(10.0),
        color: const Color(0xFF00FF00),
        width: 200.0,
        height: 200.0,),); }}Copy the code

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: 'the container sample',
      home: HomePage(),
    ));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    returnContainer( constraints: BoxConstraints.expand( height: Theme of (context). TextTheme. Display1. FontSize * 1.1 + 200.0), the padding: const EdgeInsets. All (20.0), color: Colors.teal.shade700, alignment: Alignment.topRight, child: Text('Hello World', style: Theme.of(context).textTheme.display1.copyWith(color: Colors.white)),
      foregroundDecoration: BoxDecoration(
        image: DecorationImage(
          image: NetworkImage('https://www.example.com/images/frame.png'), centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),), Transform: Matrix4.rotationX(0.5),); }}Copy the code

Row, Row

List the child widgets horizontally

attribute type instructions
key Key Control how one widget replaces another widget in the tree
children List The widget below this widget in the tree
crossAxisAlignment CrossAxisAlignment How to align children
direction Axis Used as the direction of the main axis

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: HomePage(),
    ));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blue,
        body: Center(
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  '12121212',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white),
                ),
              ),
              Expanded(
                child: Text(
                  '555555',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white),
                ),
              ),
              Expanded(
                child: FittedBox(
                  fit: BoxFit.contain, // otherwise the logo will be tiny
                  child: constFlutterLogo( style: FlutterLogoStyle.horizontal, ), ), ), ], ), )); }}Copy the code

Column Column

List the child widgets vertically

attribute

attribute type instructions
key Key Control how one widget replaces another widget in the tree
children List The widget below this widget in the tree
crossAxisAlignment CrossAxisAlignment How to align children
direction Axis Used for direction
mainAxisAlignment MainAxisAlignment The alignment of the main axis will affect the position of the child, which defaults to start
mainAxisSize MainAxisSize The value that occupies space in the main axis. The default is Max
textDirection TextDirection Determine the order in which to place the child horizontally and how to interpret the start and end of the horizontal direction
verticalDirection VerticalDirection Determine the order in which to place the child vertically and how to interpret the beginning and end of the vertical direction

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: HomePage(),
    ));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blue,
        appBar: AppBar(
          title: Text('Row sample'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text('Deliver features faster',style: TextStyle(color: Colors.white,fontSize: 30.0),),
              Text('Craft beautiful UIs',style: TextStyle(color: Colors.white,fontSize: 30.0),),
              Expanded(
                child: FittedBox(
                  alignment: Alignment.bottomRight,
                  child: constFlutterLogo(), ), ), ], ), )); }}Copy the code

Image Image

A Widget that displays images

The constructor

The constructor instructions
Image() The general method, implemented using the ImageProvider, is essentially what the following method is
Image.asset(String name,{}) Load a resource image based on the resource name
Image. The file (the file file, {}) Given an image file, load a local file image
Image.memory(Uint8List bytes,{}) Get ImageStream from Uint8List and load an image in memory
Image.network(String src,{}) Given a URL, load a web image

attribute

attribute type instructions
key Key Control how one widget replaces another widget in the tree
alignment AlignmentGeometry How do I align images within the scope of images
centerSlice Rect When the image needs to be stretched for display, the rectangular area defined by centerSlice will be stretched, which can be interpreted as we define a point 9 file inside the image to be stretched
color Color If not null, then colorBlendMode is used to mix this Color with each image pixel
colorBlendMode BlendMode Use to combine Color with this image
excludeFromSemantics bool Whether to exclude this image from Semantics
filterQuality FilterQuality Used to set the filter quality of an image
fit BoxFit Control of image display
gaplessPlayback bool When the image provider changes, continue displaying the old image (true) or simply display anything (false)
height double
image ImageProvider The image to display
matchTextDirection bool Whether to draw the image in the direction of TextDirection
repeat ImageRepeat How do I draw any part of the layout boundary that is not covered by the image
semanticLable String
width double

A simple example

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:typed_data';

import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

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

//assets/images/tzd.jpg
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
// debugPaintSizeEnabled = true;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Image sample demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              // Load the network image
              Image.network(
                'https://www.baidu.com/img/bd_logo1.png?where=super',
                width: 100.0,
                height: 100.0,),/ / load Assets
              Image.asset(
                'assets/images/tzd.jpg',
                width: 200.0,
                height: 200.0,),//Memory
              MemoryImageWidget(),

              // Load the image from the fileFileImageWidget(), ], ), ), ), ); }}class FileImageWidget extends StatefulWidget {
  @override
  _FileImageWidgetState createState() => _FileImageWidgetState();
}

class _FileImageWidgetState extends State<FileImageWidget> {
  File _image;

  Future getImge() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Center(
          child: _image == null
              ? Text('Image not selected! ')
              : Image.file(
                  _image,
                  width: 200.0,
                  height: 200.0,
                ),
        ),
        FlatButton(
          onPressed: getImge,
          child: Text(
            'Select picture',
            style: TextStyle(
              color: Color(0xff0000ff"" "" "" "" "" " }}// STF StatefulWidget shortcut keys, STL StatelessWidget shortcut keys
class MemoryImageWidget extends StatefulWidget {
  @override
  _MemoryImageWidgetState createState() => _MemoryImageWidgetState();
}

class _MemoryImageWidgetState extends State<MemoryImageWidget> {
  Uint8List bytes;

  @override
  void initState() {
    super.initState();
    rootBundle.load('assets/images/tzd.jpg').then((data) {
      if(mounted) { setState(() { bytes = data.buffer.asUint8List(); }); }}); }@override
  Widget build(BuildContext context) {
    final _decoration = BoxDecoration(
      image: bytes == null ? null : DecorationImage(image: MemoryImage(bytes)),
    );
    return Container(
      width: 100.0,
      height: 100.0, decoration: _decoration, ); }}Copy the code

Text Widget Text

Single-format demo text

attribute

attribute type instructions
key Key Control how one widget replaces another widget in the tree
data String The text to be displayed
locale Locale Used to select a font when the same Unicode character can be rendered in different ways, depending on the locale
maxLines int The optional maximum number of lines to be crossed by text, wrapped if necessary. If the text exceeds the given number of lines, it is truncated based on overflow
overFlow TextoverFlow How to deal with visual overflow
semanticsLable String An alternative semantic tag for this text
softWrap bool Whether text should break at a soft newline
strutStyle StrutStyle Pillar style to use. The Strut style defines the Strut, which sets the minimum vertical layout metric
style TextStyle If it is not NULL, the style used for this text
textAlign TextAlign How should text be aligned horizontally
textScaleFactor double The number of font pixels per logical pixel.
textSpan TextSpan The text to display as TextSpan
textDirection TextDirection The directionality of text

A simple example

Text(
            'Hello, How are you111111111111111111111111111111111111111111111111111111111111111111111111111111? ',
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis, // Display the ellipsis
            style: TextStyle(fontWeight: FontWeight.bold),
          )
Copy the code

const Text.rich(
            TextSpan(
              text: 'Hello'.// default text style
              children: <TextSpan>[
                TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
                TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold,fontSize: 100.0)),],),)Copy the code

Icon in the Icon

A graphical icon Widget drawn using glyphs from the fonts described in IconData (such as pre-defined IconDatas for the materials in the icon)

attribute

attribute type instructions
color Color The Color used to draw the icon
icon IconData The icon to display. The Icons library has Icons available
semanticLable String Sign a
size double The size of the
textDirection TextDirection Draw direction, usually not used

Icon library

RaisedButton RaisedButton

Material Design button, a raised rectangular Material button that responds to a press event and has a touch effect when pressed.

attribute

The property name type The default value instructions
color Color null Components of the Color
disabledColor Color ThemeData.disabledColor The Color of the disabled state of the component, which defaults to the disabled Color in the theme, can also be set to any other Color
onPressed VoidCallback null This callback event is triggered when the button is pressed
child Widget The child of a button is usually a Text component that displays the Text of the button
enable bool true Whether the button is disabled
RaisedButton(
              onPressed: null.// onPressed: (){},
              child: const Text('Disabled Button'),),Copy the code

The Scaffold Scaffold

Basic implementation of Material Design layout structure. This class provides apis for displaying drawers, Snackbars, and bottom sheets

attribute

attribute type instructions
appBar PreferredSizeWidget An application bar, displayed at the top of the scaffold
backgroundColor Color The Color of the material widget that is the base of the entire scaffold
body Widget The main content of the bracket
bottomNavigationBar Widget The bottom navigation bar is displayed at the bottom of the scaffold
bottomSheet widget Persistence bottom worksheet to display
drawer widget A panel that appears on the side of the body, usually hidden on a mobile device. Slide in left to right (textdirection.ltr) or right to left (textdirection.rtl)
drawerDragStartBebavior DragStartBehavior Determines how to handle the drag start behavior
endDrawer Widget A panel that appears on the side of the body, usually hidden on a mobile device. Swipe from right to left (textdirection.ltr) or left to right (textdirection.rtl)
floatingActionButton Widget The button that appears above the body, in the lower right corner
floatingActionButtonAnimator FloatingActionButtonAnimator The Animator will floatingActionButton moved to the new floatingActionButtonLocation.
floatingActionButtonLocation FloatingActionButtonLocation Responsible for determining the whereabouts of the floatingActionButton
persistentFooterButtons List A set of buttons displayed at the bottom of the scaffold
primary bool Whether the scaffold is displayed at the top of the screen
resizeToAvoidBottomInset bool If the is true, the body and scaffold floating widgets should adjust the size, in order to avoid the height of the screen keyboard by the environmental MediaQuery MediaQueryData. At the bottom of the viewInsets property definitions
resizeToAvoidBottomPadding bool This flag is not recommended. Use resizeToAvoidBottomInset instead

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: HomePage(),
    ));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: null,
              child: const Text('Disabled Button'),
            ),
            RaisedButton(
              onPressed: null,
              child: const Text('Enabled Button'),
            ),
            RaisedButton(
              onPressed: () {},
              textColor: Colors.white,
              padding: const EdgeInsets.all(0.0),
              child: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: <Color>[Colors.red, Colors.green, Colors.blue],
                  ),
                ),
                padding: const EdgeInsets.all(10.0),
                child: Text('Gradient Button'"" "" "" "" "" "" }}Copy the code

Material Components Widgets → App structure and navigation

The Scaffold Scaffold

Scaffold implements a basic Material Design layout. Scaffold can be used to render any layout component element that is displayed on a single interface as defined in Material Design.

Reference base Widget → Scaffold

Apply the button component Appbar

The application button components are AppBar and SliverAppBar. They are the AppBar in Material Design, the ToolBar in Android. Both AppBar and SliverAppBar inherit from StatefulWidget. The difference between the two is that the AppBar is fixed at the top of the application. The SliverAppBar, on the other hand, can scroll along with the content.

Commonly used attributes

The property name type The default value instructions
actions List null The widget to be displayed after the title Widget
automaticallyImplyLeading bool false Controls whether the leading widget should be tried to imply null
backgroundColor Color ThemeData.primaryColor The Color used for the application bar material. Normally this should be set together with the brightness, iconTheme, and textTheme
bottom PreferredSizeWidget null This widget appears at the bottom of the application bar
bottomOpacity double Opacity at the bottom of the app bar
brightness Brightness ThemeData.primaryColorBrightness Brightness of the application bar material. Normally, this is set together with the backgroundColor, iconTheme, and textTheme.
centerTitle bool false Should the title be centered
elevation double 4 The Z coordinate that places this application bar relative to its parent
flexibleSpace Widget null This widget is stacked behind the toolbar and TAB bar. Its height is the same as the overall height of the app bar
iconTheme IcomThemData ThemeData.primaryIconTheme Color, opacity, and size for the app bar icon. Normally, this is set with the backgroundColor, brightness, and textTheme
leading Widget null The widget to be displayed before the title
preferredSize Size The height is the sum of the kToolbarHeight and the preferred height of the bottom widget
primary bool Whether the application bar is displayed at the top of the screen
textTheme TextTheme ThemeData.primaryTextTheme The typographical style used for text in the application bar. Normally, this is set along with the brightness, backgroundColor, iconTheme
title Widget null The main widget displayed in the AppBar
titleSpacing double The spacing around the header content on the horizontal axis. This interval is applied even if there is no leading content or action. If you want the title to take up all available space, set this value to 0.0
toolbarOpacity double How opaque the toolbar portion of the app bar is

A simple example

 AppBar(
        leading: Icon(Icons.arrow_back),
        title: Text('Simple App Example'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.playlist_play),
            tooltip: 'Air it',
            onPressed: (){},
          ),
          IconButton(
            icon: Icon(Icons.playlist_add),
            tooltip: 'Restitch it',
            onPressed: (){},
          ),
          IconButton(
            icon: Icon(Icons.playlist_add_check),
            tooltip: 'Repair it',
            onPressed: (){},
          ),
        ],
      ),
Copy the code

AppBar deepens study Sample 1

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

class AppBarBottomSample extends StatefulWidget {
  @override
  _AppBarBottomSampleState createState() => new _AppBarBottomSampleState();
}

class _AppBarBottomSampleState extends State<AppBarBottomSample> with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: choices.length);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void _nextPage(int delta) {
    final int newIndex = _tabController.index + delta;
    if (newIndex < 0 || newIndex >= _tabController.length)
      return;
    _tabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('AppBar Bottom Widget'),
          leading: new IconButton(
            tooltip: 'Previous choice',
            icon: const Icon(Icons.arrow_back),
            onPressed: () { _nextPage(- 1); },
          ),
          actions: <Widget>[
            new IconButton(
              icon: const Icon(Icons.arrow_forward),
              tooltip: 'Next choice',
              onPressed: () { _nextPage(1); },
            ),
          ],
          bottom: new PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: new Theme(
              data: Theme.of(context).copyWith(accentColor: Colors.white),
              child: new Container(
                height: 48.0,
                alignment: Alignment.center,
                child: new TabPageSelector(controller: _tabController),
              ),
            ),
          ),
        ),
        body: new TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return new Padding(
              padding: const EdgeInsets.all(16.0),
              child: newChoiceCard(choice: choice), ); }).toList(), ), ), ); }}class Choice {
  const Choice({ this.title, this.icon });
  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({ Key key, this.choice }) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return new Card(
      color: Colors.white,
      child: new Center(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Icon(choice.icon, size: 128.0, color: textStyle.color),
            newText(choice.title, style: textStyle), ], ), ), ); }}// Program entry
void main() {
  runApp(new AppBarBottomSample());
}
Copy the code

AppBar deepens study Sample 2

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

class TabbedAppBarSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new DefaultTabController(
        length: choices.length,
        child: new Scaffold(
          appBar: new AppBar(
            title: const Text('Tabbed AppBar'),
            bottom: new TabBar(
              isScrollable: true,
              tabs: choices.map((Choice choice) {
                return new Tab(
                  text: choice.title,
                  icon: new Icon(choice.icon),
                );
              }).toList(),
            ),
          ),
          body: new TabBarView(
            children: choices.map((Choice choice) {
              return new Padding(
                padding: const EdgeInsets.all(16.0),
                child: newChoiceCard(choice: choice), ); }).toList(), ), ), ), ); }}class Choice {
  const Choice({ this.title, this.icon });
  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({ Key key, this.choice }) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return new Card(
      color: Colors.white,
      child: new Center(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Icon(choice.icon, size: 128.0, color: textStyle.color),
            newText(choice.title, style: textStyle), ], ), ), ); }}void main() {
  runApp(new TabbedAppBarSample());
}
Copy the code

BottomNavigationBar is BottomNavigationBar

The bottom navigation bar makes it easy to switch between taps and navigate to the top view

Commonly used attributes

The property name type instructions
currentIndex int The current index
fixedColor Color Select the Color of the button. If not specified, the system theme Color is used
iconSize double Button Graphics size
items List<BottomNavigatorBarItem> Bottom navigation bar button set. Each entry is a BottomNavigatorBarItem containing the icon icon and title text
onTap ValueChanged<int> Callback event for pressing a button. You need to set the current index based on the index returned

import 'package:flutter/material.dart';
void main()=>runApp(MaterialApp(
  home: HomePage(),
));

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

class _HomePageState extends State<HomePage> {
  int _selectedIndex = 1;
  final _widgetOptions = [
    Text('Index 0: recent '),
    Text('Index 1: Address book '),
    Text('Index 2: discovery '),
    Text('Index 3: mine ')];@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(items: [
        BottomNavigationBarItem(icon: Icon(Icons.history),title:Text('recently'),backgroundColor:Colors.deepPurple),
        BottomNavigationBarItem(icon: Icon(Icons.contact_phone),title:Text('Address book'),backgroundColor:Colors.deepPurple),
        BottomNavigationBarItem(icon: Icon(Icons.find_in_page),title:Text('found'),backgroundColor:Colors.deepPurple),
        BottomNavigationBarItem(icon: Icon(Icons.my_location),title:Text('I'),backgroundColor:Colors.deepPurple), ], currentIndex: _selectedIndex, fixedColor: Colors.deepPurple, onTap: (index){ setState(() { _selectedIndex = index; }); },),); }}Copy the code

TAB TabBar

The TabBar is a Material Design component that displays horizontal tabs. It is usually used in conjunction with the Tab option component and the TabBarView page view component.

Commonly used attributes

The property name type instructions
controller TabController The widget’s selection and animation state
dragStartBehavior DragStartBehavior Determines how to handle the drag start behavior
indicatorPadding EdgeInsetsGeometry Displays the horizontal fill of the line below the selected TAB. For the isScrollable Tab bar, specifying kTabLabelPadding aligns the indicator with the Tab text of the Tab widget and all text except the shortest tab.text value
indicator Decoration Defines the appearance of the selected TAB indicator
indicatorColor Color Displays the Color of the line below the selected TAB. If this parameter is NULL, the value of the indicatorColor property of the Theme is used
indicatorSize TabBarIndicatorSize Defines how to calculate the size of a selected TAB indicator
indicatorWeight double Displays the line thickness below the selected TAB. The value of this parameter must be greater than zero
isScrollable bool Whether this TAB bar can scroll horizontally
labelColor Color Select the Color of Tab
labelPadding TextStyle Padding is added to each TAB TAB TAB
onTap ValueChanged Optional callback called when the TabBar is clicked
preferredSize Size The height depends on whether the label contains both icon and text size
tabs List Usually a list of two or more Tab widgets
unselectedLabelColor Color The Color of the tag is not selected
unselectedLableStyle TextStyle The text style of the tag is not selected

A TabBar can be used to navigate between pages displayed in a TabBarView. Although a TabBar is a common widget that can appear anywhere, it is usually included in an application’s AppBar.

Create a new project with AndroidStudio and try it out by replacing the contents of lib/main.dart with the following code.

A simple example

import 'package:flutter/material.dart';

void main() =>runApp(MaterialApp(home:  HomePage(),));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: choices.length,
        child: Scaffold(
          appBar: AppBar(
            title: Text('TabBar sample'),
            bottom: new TabBar(
              // TAB supports sliding
                isScrollable: true,
                tabs: choices.map((choice){ // This is equivalent to traversal
                  print("Traversal: →"+choice.title);
                  return Tab(
                    text: choice.title,
                    icon: new Icon(choice.icon),
                  );
                }).toList()
            ),
          ),
          body: TabBarView(children: choices.map((item){
            return newTab( text: item.title, icon: Icon(item.icon), ); }).toList()), ), ); }}class Choice {
  const Choice({ this.title, this.icon });
  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

Copy the code

TabBarView

Displays the page view corresponding to the currently selected TAB. Usually used with a TabBar

Commonly used attributes

The property name type instructions
children List Widgets for each tag
controller TabController Selection and animation state for this widget
dragStartBebavior DragStartBehavior Determines how to handle the drag start behavior
physics ScroolPhysics How should the page view respond to user input

Simple to use

import 'package:flutter/material.dart';
import 'package:flutter/src/scheduler/ticker.dart';

void main() =>runApp(MaterialApp(home:  HomePage(),));

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

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin{
  TabController _TabController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _TabController =  TabController(vsync: this,length: choices.length);
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _TabController.dispose();
  }

  void _nextPage(int delta){
   final int newIndex =  _TabController.index + delta;
   if (newIndex < 0 || newIndex >= _TabController.length)
     return;
   _TabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('TabBarView sample'),
            
            bottom:PreferredSize(child: Theme( data: Theme.of(context).copyWith(accentColor: Colors.white),
                child: Container(
                  height: 50.0,
                  alignment: Alignment.center,
                  child: TabPageSelector(controller: _TabController,),
                )), preferredSize: Size.fromHeight(50.0)) ,
        ),
        body: DefaultTabController(length: choices.length, child:  TabBarView(
            controller: _TabController,
            children: choices.map((item){
          return newTab( text: item.title, icon: Icon(item.icon), ); }).toList()),) ), ); }}class Choice {
  const Choice({ this.title, this.icon });
  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

Copy the code

MaterialApp

The MaterialApp represents an application that uses the Material Design style and contains the other required basic controls. The official example demo starts from the MaterialApp main component.

Commonly used attributes

The property name type instructions
title String The title of the application. The title appears in the following places: Android: Task Manager program snapshot; IOS: Program switch manager
theme ThemeData Define the theme Color to be used by the application. You can specify the Color of each control in the theme
color Color The primary Color of the application
home Widget Defines the interface to be displayed when the current application is opened
routes Map<String, WidgetBuilder> Define the page jump rule in the application
initialRoute String Initializing a Route
onGenerateRoute RouteFactory Route callback function. This method is called when routes cannot be found when a route is jumped through navigater.of (context).pushnamed
onLocaleChanged This callback is triggered when the system changes the language
navigatorObservers List<NavigatorObserver> Navigational observer
debugShowMaterialGrid bool Whether to display the layout grid, a tool used to debug the UI
showPerformanceOverlay bool Display performance labels

Set the home page

Use the home property to set the home page of your application and the main component of your entire application.

The routing process

The Routes object is a Map<String, WidgetBuilder>. When using Navigator. PushNamed to jump a route, look up the route name through routes, and then use the corresponding WidgetBuilder to construct a MaterialPageRoute with the page switch animation. If the application has only one interface, use home instead of setting the entire property.

Custom themes

The theme of the application, a variety of custom Color can be set, used for the program theme switch

WidgetsApp

A handy class that encapsulates some of the widgets that your application typically needs

Drawer assembly Drawe

A Drawer can be pulled in and out like a Drawer and is usually used in combination with a ListView.

Commonly used attributes

The property name type The default value instructions
child Widget The child of a Drawer can place any displayable component
elevation double 16 Shadow size

A Drawer can add a header effect:

  • DrawerHeader: Displays basic information
  • UserAccountsDrawerHeader: displays the user profile picture, user name, and Email address

DrawerHeader commonly used property

The property name type instructions
decoration Decoration Header area decoration, usually used to set the background Color or background image
curve Curve If the decoration changes, an animation is made using the change curve set by Curve and the animation time set by Duration
child Widget The content control displayed inside the Header
padding EdgeInsetsGeometry The padding value of the content control in the Header, which is invalid if the child is NULL
margin EdgeInsetsGeometry The gap around the Header

UserAccountsDrawerHeader Common property

The property name type instructions
margin EdgeInsetsGeometry The gap around the Header
decoration Decoration Header area decoration, usually used to set the background Color or background image
currentAccountPicture Widget Set the profile picture of the current user
otherAccountsPicture Widget This parameter is used to set the profile picture of other accounts of the current user
accountName Widget Name of the current user
accountEmail Widget Specifies the Email address of the current user
onDetailsPressed VoidCallback The callback function that is triggered when accountName or accountEmail is clicked can be used to display additional information

A simple demo

import 'package:flutter/material.dart';

void main ()=> runApp(MaterialApp(
  home: DrawerWidget(),
));

class DrawerWidget extends StatefulWidget {
  @override
  _DrawerWidgetState createState() => _DrawerWidgetState();
}

class _DrawerWidgetState extends State<DrawerWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('the drawer sample'), ), drawer: BuildDrawer(), ); }}class BuildDrawer extends StatefulWidget {
  @override
  _BuildDrawerState createState() => _BuildDrawerState();
}

class _BuildDrawerState extends State<BuildDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        children: <Widget>[
          UserAccountsDrawerHeader(
            currentAccountPicture: CircleAvatar(
              backgroundImage: NetworkImage(
                  'https://randomuser.me/api/portraits/women/17.jpg'),
            ),
            accountName: Text('Damon'),
            accountEmail: Text('[email protected]'),
            otherAccountsPictures: <Widget>[
              Icon(Icons.camera),
            ],
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/xinqiu.jpg'),
                fit: BoxFit.fill,
              ),
            ),
          ),
          ListTile(
            leading: Icon(Icons.payment),
            title: Text('Member Privileges'),
          ),
          ListTile(
            leading: Icon(Icons.payment),
            title: Text('Member Privileges'),
          ),
          ListTile(
            leading: Icon(Icons.payment),
            title: Text('Member Privileges'),
          ),
          AboutListTile(
            icon: Icon(Icons.error),
            child: Text('about'),
            applicationName: 'ha ha'
            ,applicationVersion: '1.0'[] [[] [ }}Copy the code

button

RaisedButton

Introduction to the

Botton in Meaterial Design, a raised rectangle button with material.

Commonly used attributes

The property name type instructions
animationDuration Duration Defines the duration of animation changes for shapes and elevations
child Widget Button label
clipBehavior Clip Depending on this option, the content will be clipped (or not clipped)
color Color The fill Color of the button, displayed by its material, is in the default (not pressed, enabled) state
colorBrightness Brightness Theme brightness for this button
disabledColor Color Button fill Color when the button is disabled
disabledTextColor Color The Color used for the button text when the button is disabled
elevation double The z coordinate to place this button relative to its parent
enabled bool Enables or disables the button
height double The vertical range of the button
highightColor Color The highlight Color of the InkWell button
highlightElevation double The elevation of the button’s material relative to its parent when the button is enabled and pressed
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
minWidth double Minimum horizontal range occupied by a button
onHighlightChanged ValueChanged By the underlying InkWell widget InkWell. OnHighlightChanged callback invocation.
onPressed VoidCallback Callback called when a button is clicked or otherwise activated
padding EdgeInsetsGeometry Button of the child’s inner fill
shape ShapeBorder The shape of the button material
splashColor Clor InkWell button flashing Color
textColor Color The Color used for the button text.
textTheme ButtonTextTheme Defines the Color of the button, as well as the default values for the button’s minimum size, internal fill, and shape

A simple example

// This sample shows how to render a disabled RaisedButton, an enabled RaisedButton
// and lastly a RaisedButton with gradient background.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Code Sample for material.RaisedButton', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyStatelessWidget(), ); }}class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: null,
              child: const Text('Disabled Button'),
            ),
            RaisedButton(
              onPressed: () {},
              child: const Text('Enabled Button'),
            ),
            RaisedButton(
              onPressed: () {},
              textColor: Colors.white,
              padding: const EdgeInsets.all(0.0),
              child: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: <Color>[Colors.red, Colors.green, Colors.blue],
                  ),
                ),
                padding: const EdgeInsets.all(10.0),
                child: Text('Gradient Button'"" "" "" "" "" "" }}Copy the code

FloationgActionButton

Introduction to the

A circular toon that hovers over the content to show the main actions in the application. FloatingActionButton is typically used for Scaffold. FloatingActionButton fields.

Commonly used attributes

The property name type instructions
backgroudColor Color The Color used to fill the button
child Widget The widget below this widget in the tree
clipBehavior Clip Depending on this option, the content will be clipped (or not clipped).
disableElevation double The z coordinate to place the button when it is disabled (onPressed is null)
elevation double The Z coordinate used to associate this button with its parent button
foregroudColor Color Default icon and text Color.
heroTag Object The tag of the Hero widget to apply to the button
highlightElevation double The z coordinate to place the button relative to its parent button when the user touches it
isExtended bool True if this is an “extend” float action button
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
mini bool Controls the size of this button
onPressed VoidCallback Callback called when a button is clicked or otherwise activated
shape ShapeBorder The shape of the button material
tooltip String Text that describes the action that will occur when the button is pressed

A simple example

      home: Scaffold(
        appBar: AppBar(
          title: Text('FloatingActionButton sample'),
        ),
        body: Center(child: Text('FloatingActionButton sample'),),
        floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: (){}),
        
      ),
Copy the code

FlatButton

Introduction to the

A flat Material button

Commonly used attributes

The property name type instructions
animationDuration Duration Defines the duration of animation changes for shapes and elevations
child Widget Button label
chlipBebavior Clip Depending on this option, the content will be clipped (or not clipped)
color Color The fill Color of the button, displayed by its material, is in the default (not pressed, enabled) state
colorBrightness Brightness Theme brightness for this button
disabledColor Color Button fill Color when the button is disabled
disableElevation double The height of the button’s material relative to its parent when the button is not enabled
disableTextColor Color Color The Color used for the button text when the button is disabled
elevation double The z coordinate to place this button relative to its parent.
enable bool Enables or disables the button
height double The vertical range of the button
highlightColor Color The highlight Color of the InkWell button
highlightElevation double The elevation of the button’s material relative to its parent when the button is enabled and pressed.
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
minWidth double Minimum horizontal range occupied by a button.
onHighlightChanged ValueChanged By the underlying InkWell widget InkWell. OnHighlightChanged callback invocation
onPressed VoidCallback Callback called when a button is clicked or otherwise activated
padding EdgeInsetsGeometry Callback called when a button is clicked or otherwise activated.
shape ShapeBorder The shape of the button material.
splashColor Color InkWell button flashing Color
textColor Color The Color used for the button text.
textTheme ButtonTextTheme Defines the Color of the button, as well as the default values for the button’s minimum size, internal fill, and shape

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FlatButton'),
        ),
        body: Center(
          child: Text('FlatButton'),
        ),
        floatingActionButton: FlatButton(
          onPressed: () {},
          child: Text(
            'FlatButton',
            style: TextStyle(color: Colors.white),
          ),
          color: Colors.deepPurple,
        ),
      ),
    ));

Copy the code

IconButton

Introduction to the

A Material icon button that will animate water waves when clicked.

Attribute is introduced

The property name type instructions
alignment AlignmentGeometry Defines how ICONS are positioned in an IconButton
color Color If icon is enabled, it is used for the Color of the icon inside the button. This is left to the icon widget by default
disableColor Color The Color of the icon inside the button if the icon is disabled. The default is themeData.disabledColor for the current theme.
highlightColor Color The secondary Color of the button when the button is in the down (down) state. The highlighted Color represents the solid Color overlaid on the button Color (if any). If the highlight Color is transparent, the button Color is displayed. The highlight quickly disappears when you hold the button down.
icon Widget The icon to be displayed inside the button
iconSize double The size of the icon inside the button.
onPressed VoidCallback Button callback
padding EdgeInsetsGeometry Fill around button ICONS. The entire fill icon will respond to the input gesture
splashColor Color The primary Color of the button when it is in the down state. The splash is represented by highlighting the circular overlay above the highlightColor overlay. The central point of the initial overlay layer matches the life point of the user touch event. If the touch lasts long enough, the splash overlay expands to fill the button area. If the initial Color is transparent, the highlight and button colors are displayed
tooltip String Text that describes the action that will occur when the button is pressed

A simple example

import 'package:flutter/material.dart';

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('IconButton sample'), actions: <Widget>[ IconButton(icon: Icon(Icons.home), onPressed: (){}), IconButton(icon: Icon(Icons.radio), onPressed: (){}), IconButton(icon: Icon(Icons.verified_user), onPressed: (){}), IconButton(icon: Icon(Icons.voice_chat), onPressed: (){}), IconButton(icon: Icon(Icons.video_call), onPressed: (){}), ], ), ), ); }}Copy the code

PopupMenuButton

Introduction to the

When the menu is hidden, click or call onSelected to display a pop-up menu list

Commonly used attributes

The property name type instructions
child Widget The widget for this button, if provided.
elevation double The z coordinate to place the menu when opened. This controls the size of the shadow below the menu
icon Icon Icon for this button, if supplied
initialValue T The value of the menu item, if any, should be highlighted when the menu is opened.
offset Offset The offset applied to the pop-up menu button
onCanceled PopupMenuCanceled Called when the user closes the pop-up menu without selecting the item
onSelected PopupMenuItemSelected Called when the user selects a value from the pop-up menu created by this button
padding EdgeInsetsGeometry By default, matches the IconButton’s 8 DPS fill. In some cases, especially if this button appears as a trailing element for a list item, it is useful to be able to set the padding to zero.
tooltip String Text that describes the action that will occur when the button is pressed
itemBuilder PopupMenuItemBuilder Call when the button is pressed to create the item to be displayed in the menu.

A simple example

import 'package:flutter/material.dart';

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('PopupMenuButton sample'),
          actions: <Widget>[
            IconButton(icon: Icon(Icons.home), onPressed: () {}),
            IconButton(icon: Icon(Icons.radio), onPressed: () {}),
            IconButton(icon: Icon(Icons.verified_user), onPressed: () {}),
            IconButton(icon: Icon(Icons.voice_chat), onPressed: () {}),
            IconButton(icon: Icon(Icons.video_call), onPressed: () {}),
            PopupMenuButton(
                itemBuilder: (context) => [
                      PopupMenuItem(child: Text('popupMenuItem ')),
                      PopupMenuItem(child: Text('popupMenuItem 1')),
                      PopupMenuItem(child: Text('popupMenuItem 2')),
                      PopupMenuItem(child: Text('popupMenuItem 3')),
                    ]
              ,
              onCanceled: (){
                  print('onCenten'); },),],),); }}Copy the code

ButtonBar

Introduction to the

A horizontal group of buttons

Commonly used attributes

The property name type instructions
alignment MainAxisAlignment How do I put my child on the horizontal axis
children List Horizontal arrangement of buttons
mainAxisSize MainAxisSize How much horizontal space is available. Please see the Row. MainAxisSize

A simple example

ButtonBar(
        children: <Widget>[
          Text('test'),
          Text('test 2'),
          Icon(Icons.video_call,color: Color(0xffff0000),),
          Icon(Icons.voice_chat,color: Color(0xffff0000),),
          Icon(Icons.wallpaper,color: Color(0xffff0000),),),Copy the code

Input boxes and selection boxes

TextField

Introduction to the

A text input field

Commonly used attributes

The property name type instructions
aotocorrect bool Whether to enable autocorrect
autofocus bool If nothing else has been focused, this text field should be focused
buildCounter InputCounterWidgetBuilder Generate a callback for the custom InputDecorator.counter widget
controller TextEditingController The Color used to draw the cursor.
cursorColor Color The Color used to draw the cursor
cursorRadius Radius The cursor Angle should be more circular
cursorWidth double Thickness of the cursor.
decoration InputDecoration Decoration displayed around a text field.
dragStartBehavior DragStartBehavior Determines how to handle the drag start behavior.
enable bool If false, the text field is “disabled” : it ignores the click and it is decorated with a grey Color.
enableInteractiveSelection bool If true, long-pressing this TextField will select text and display the Cut/Copy/Paste menu, and clicking will move the text caret.
focusNode FocusNode Defines the keyboard focus for this widget
inputFormatters List Optional input validation and formatting overrides.
keyboardAppearance Brightness The appearance of the keyboard
keyboardType TextInputType The type of keyboard used to edit text
maxLength int If true, this field is prevented from allowing more than maxLength characters
maxLines int Maximum number of lines of text to span, wrapped if necessary
obsureText bool Whether to hide the text being edited (for example, for a password).
onCanged ValueChanged Called when a user initiates a change to a TextField value: when they insert or delete text.
onEditingComplete VoidCallback Called when the user submits editable content (for example, when the user presses the “Done” button on the keyboard).
onSubmitted ValueChanged Called when a user indicates that they have finished editing text in a field
onTap GestureTapCallback Called when the user clicks on the text field
scrollPadding EdgeInsets When the Textfield is scrolled into the view, the configuration is filled to the edge around the Scrollable.
selectionEnabled bool If enabled interactive selection based on enableInteractiveSelection and obscureText value, it is True.
style TextStyle Style for the text being edited.
textAlign TextAlign How should text be aligned horizontally
textCapitalization TextCapitalization Configure platform Keyboard How to select an uppercase or lowercase keyboard.
textDirection TextDirection The directionality of text
textInputAction TextInputAction Type of action button used for the keyboard

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: TextFieldPage(),
    ));

class TextFieldPage extends StatelessWidget {
  Widget buildTextField(TextEditingController controller) {
    return TextField(
      controller: controller,
      maxLength: 30.// Maximum length. Setting this will make the bottom right corner of TextField have a statistical string for the number of inputs
      maxLines: 1.// Maximum number of rows
      autocorrect: true.// Whether to autocorrect
      autofocus: true.// Whether auto focus is enabled
      obscureText: true.// Whether it is a password
      textAlign: TextAlign.start,
      // Text alignment
      style: TextStyle(fontSize: 30.0, color: Colors.blue),
      // Enter the text style
// inputFormatters: [WhitelistingTextInputFormatter.digitsOnly,BlacklistingTextInputFormatter.singleLineFormatter],
      // Allowed input formats
      onChanged: (text) {
        // Callback for content change
        print('change $text');
      },
      onSubmitted: (text) {
        // Callback for content commit (press Enter)
        print('submit $text');
      },
      enabled: true.// Whether to disable
    );
  }

  @override
  Widget build(BuildContext context) {
    final controller = TextEditingController();
    controller.addListener(() {
      print('input ${controller.text}');
    });
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0), child: buildTextField(controller), ), ); }}Copy the code

Checkbox

Introduction to the

Check box that allows the user to select multiple options from a group.

Commonly used attributes

The property name type instructions
activeColor Color Color to use when this check box is selected
checkColor Color This check box is used to check the Color of the icon when selected
tristate bool If true, the value of the check box can be true, false, or null.
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
onChanged ValueChanged Called when the value of the check box should change
values bool Whether to select this check box

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: CheckboxPage()));

class CheckboxPage extends StatefulWidget {
  @override
  _CheckboxPageState createState() => _CheckboxPageState();
}

class _CheckboxPageState extends State<CheckboxPage> {

  bool _values = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkbox sample'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Checkbox(
              // The selected background color
              activeColor: Colors.red,
              // The color of the checkmark
              checkColor: Colors.white,
                materialTapTargetSize: MaterialTapTargetSize.padded,
                value: _values,
                onChanged: (isSelect) {
                setState(() {
                  _values = isSelect;
                });
                  print(isSelect); })],),)); }}Copy the code

Radio

Introduction to the

A radio box that allows the user to select an option from a group.

Commonly used attributes

The property name type instructions
activeColor Color The selected background color
groupValue T The currently selected value for this group of radio buttons
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target.
onCanged ValueChanged Called when the user selects this radio button
value T Value represented by this radio button

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: CheckboxPage()));

class CheckboxPage extends StatefulWidget {
  @override
  _CheckboxPageState createState() => _CheckboxPageState();
}

class _CheckboxPageState extends State<CheckboxPage> {

  var groupValue = 1;
  updateGroupValue(t){
    setState(() {
      groupValue = t;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Checkbox sample'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Radio(value: 0, groupValue: 0, onChanged: null),// If onChanged is null, the button is not available
              new Radio(
                  value: 1,
                  groupValue: groupValue,// select if the value is the same as the groupValueactiveColor: Colors.red, onChanged: (T){ updateGroupValue(T); }),new Radio(
                  value: 2, groupValue: groupValue, onChanged: (T){ updateGroupValue(T); }),new Radio(
                  value: 3, groupValue: groupValue, onChanged: (T){ updateGroupValue(T); }),new Radio(
                  value: 4, groupValue: groupValue, onChanged: (T){ updateGroupValue(T); }),new Radio(
                  value: 5, groupValue: groupValue, onChanged: (T){ updateGroupValue(T); }),new Radio(
                  value: 6, groupValue: groupValue, onChanged: (T){ updateGroupValue(T); }),],),); }}Copy the code

Switch

Introduction to the

On/OFF Is used to switch a single state

Commonly used attributes

The property name type instructions
activeColor Color This color represents the background color of the selection
groupValue T The currently selected value for this group of radio buttons
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
onChanged ValueChanged Called when the user selects this radio button
value T Value represented by this radio button

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: SwitchPage()));

class SwitchPage extends StatefulWidget {
  @override
  _SwitchPageState createState() => _SwitchPageState();
}

class _SwitchPageState extends State<SwitchPage> {
  var groupValue = 1;
  var _value = true;

  updateGroupValue(t) {
    setState(() {
      groupValue = t;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('the Switch sample'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Switch( activeColor: Colors.deepPurple, value: _value, onChanged: (select) { setState(() { _value = select; }); }), Switch( value: _value, onChanged: (select) { setState(() { _value = select; }); }), ], ), )); }}Copy the code

Slider

Introduction to the

A slider that allows the user to slide the slider to select from a range of values.

Commonly used attributes

The property name type instructions
activeColor Color Color for the moving part of the slider track
divisions int The number of discrete fractions
inactiveColor Color The color value that the slide track is not sliding
label String A label that appears above the slider when it is active
max double Maximum value that the user can select
min double For the minimum value that can be selected
onChanged ValueChanged The value of the slide listener
onChangeEnd ValueChanged End of the slide
onChangeStart ValueChanged The slide began
semanticFormatterCallback SemanticFormatterCallback Callbacks are used to create semantic values from the slider values
value double The currently selected value for this slider

A simple example

import 'package:flutter/material.dart';
import 'dart:math' as math;
void main()=> runApp(MaterialApp(home: SliderPage()));
class SliderPage extends StatefulWidget {
  @override
  _SliderPageState createState() => _SliderPageState();
}
Path _triangle(double size, Offset thumbCenter, {bool invert = false{})final Path thumbPath = Path();
  final double height = math.sqrt(3.0) / 2.0;
  final double halfSide = size / 2.0;
  final double centerHeight = size * height / 3.0;
  final double sign = invert ? 1.0 : 1.0;
  thumbPath.moveTo(thumbCenter.dx - halfSide, thumbCenter.dy + sign * centerHeight);
  thumbPath.lineTo(thumbCenter.dx, thumbCenter.dy - 2.0 * sign * centerHeight);
  thumbPath.lineTo(thumbCenter.dx + halfSide, thumbCenter.dy + sign * centerHeight);
  thumbPath.close();
  return thumbPath;
}
class _SliderPageState extends State<SliderPage> {
  double _value = 25.0;
  double _discreteValue = 20.0;

  _upDataValue(double){
    setState(() {
      _value = double;
    });
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SliderTheme(
            data: theme.sliderTheme.copyWith(
              activeTrackColor: Colors.deepPurple,
              inactiveTrackColor: Colors.black26,
              activeTickMarkColor: Colors.white70,
              inactiveTickMarkColor: Colors.black,
              overlayColor: Colors.black12,
              thumbColor: Colors.deepPurple,
              valueIndicatorColor: Colors.deepPurpleAccent,
              thumbShape: _CustomThumbShape(),
              valueIndicatorShape: _CustomValueIndicatorShape(),
              valueIndicatorTextStyle: theme.accentTextTheme.body2.copyWith(color: Colors.black87),
            ),
            child: Slider(
              value: _discreteValue,
              min: 0.0,
              max: 200.0,
              divisions: 5,
              semanticFormatterCallback: (double value) => value.round().toString(),
              label: '${_discreteValue.round()}',
              onChanged: (doublevalue) { setState(() { _discreteValue = value; }); },),),const Text('Discrete with Custom Theme'),,),); }}class _CustomThumbShape extends SliderComponentShape {
  static const double _thumbSize = 4.0;
  static const double _disabledThumbSize = 3.0;

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return isEnabled ? const Size.fromRadius(_thumbSize) : const Size.fromRadius(_disabledThumbSize);
  }

  static final Animatable<double> sizeTween = Tween<double>(
    begin: _disabledThumbSize,
    end: _thumbSize,
  );

  @override
  void paint(
      PaintingContext context,
      Offset thumbCenter, {
        Animation<double> activationAnimation,
        Animation<double> enableAnimation,
        bool isDiscrete,
        TextPainter labelPainter,
        RenderBox parentBox,
        SliderThemeData sliderTheme,
        TextDirection textDirection,
        double value,
      }) {
    final Canvas canvas = context.canvas;
    final ColorTween colorTween = ColorTween(
      begin: sliderTheme.disabledThumbColor,
      end: sliderTheme.thumbColor,
    );
    final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
    final Path thumbPath = _triangle(size, thumbCenter);
    canvas.drawPath(thumbPath, Paint()..color = colorTween.evaluate(enableAnimation));
  }
}

class _CustomValueIndicatorShape extends SliderComponentShape {
  static const double _indicatorSize = 4.0;
  static const double _disabledIndicatorSize = 3.0;
  static const double _slideUpHeight = 40.0;

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size.fromRadius(isEnabled ? _indicatorSize : _disabledIndicatorSize);
  }

  static final Animatable<double> sizeTween = Tween<double>(
    begin: _disabledIndicatorSize,
    end: _indicatorSize,
  );

  @override
  void paint(
      PaintingContext context,
      Offset thumbCenter, {
        Animation<double> activationAnimation,
        Animation<double> enableAnimation,
        bool isDiscrete,
        TextPainter labelPainter,
        RenderBox parentBox,
        SliderThemeData sliderTheme,
        TextDirection textDirection,
        double value,
      }) {
    final Canvas canvas = context.canvas;
    final ColorTween enableColor = ColorTween(
      begin: sliderTheme.disabledThumbColor,
      end: sliderTheme.valueIndicatorColor,
    );
    final Tween<double> slideUpTween = Tween<double>(
      begin: 0.0,
      end: _slideUpHeight,
    );
    final double size = _indicatorSize * sizeTween.evaluate(enableAnimation);
    final Offset slideUpOffset = Offset(0.0, -slideUpTween.evaluate(activationAnimation));
    final Path thumbPath = _triangle(
      size,
      thumbCenter + slideUpOffset,
      invert: true,);final Color paintColor = enableColor.evaluate(enableAnimation).withAlpha((255.0* activationAnimation.value).round()); canvas.drawPath( thumbPath, Paint().. color = paintColor, ); canvas.drawLine( thumbCenter, thumbCenter + slideUpOffset, Paint() .. color = paintColor .. style = PaintingStyle.stroke .. strokeWidth =2.0);
    labelPainter.paint(canvas, thumbCenter + slideUpOffset + Offset(-labelPainter.width / 2.0, -labelPainter.height - 4.0)); }}Copy the code

Date & Time Pickers

Introduction to the

Date & time selection

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
  color: Colors.white,
      home: DatePickerDemo(),
    ));

class DatePickerDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _DatePickerDemo();
}

class _DatePickerDemo extends State<DatePickerDemo> {
  _showDataPicker() async {
    Locale myLocale = Localizations.localeOf(context);
    var picker = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2016),
        lastDate: DateTime(2020),
        locale: myLocale);
    setState(() {
      _time = picker.toString();
    });
  }

  _showTimePicker() async {
    var picker =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    setState(() {
      _time = picker.toString();
    });
  }

  var _time;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text(_time == null ? 'Select date' : _time),
          onPressed: () => _showDataPicker(),
        ),
        RaisedButton(
          child: Text(_time == null ? 'Select time': _time), onPressed: () => _showTimePicker(), ), ], ); }}Copy the code

Dialog box, Alert, Panel

SimpleDialog

Introduction to the

Simple dialog boxes can display additional tips or actions

Commonly used attributes

The property name type instructions
backgroundColor Color The background color of the surface of this dialog box
children List The (optional) content of the dialog box is displayed in the SingleChildScrollView below the title
contentPadding EdgeInsetsGeometry Fill in the content.
elevation double Dialog box coordinates
semanticLable String The accessibility framework is used for semantic labels of dialog boxes that notify screen transitions when the dialog box is opened and closed
shape ShapeBorder The shape of the border of this dialog box
title Widget The (optional) title of the dialog box is displayed in large font at the top of the dialog box
titlePadding EdgeInsetsGeometry Fill in around the title.

A simple example

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

void main(){
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => new _State();
}

enum Answers{YES,NO,MAYBE}

class _State extends State<MyApp>{

  String _value = ' ';

  void _setValue(String value) => setState(() => _value = value);

  Future _askUser() async {
    switch(
    await showDialog(
        context: context,
        child: new SimpleDialog(
          title: new Text('test SimpleDialog'),
          semanticLabel: The '-',
          children: <Widget>[
            new SimpleDialogOption(child: new Text('Yes!!! '),onPressed: (){Navigator.pop(context, Answers.YES); },),new SimpleDialogOption(child: new Text('NO :('),onPressed: (){Navigator.pop(context, Answers.NO); },),new SimpleDialogOption(child: new Text('Maybe :|'),onPressed: (){Navigator.pop(context, Answers.MAYBE); },),],)) {case Answers.YES:
        _setValue('Yes');
        break;
      case Answers.NO:
        _setValue('No');
        break;
      case Answers.MAYBE:
        _setValue('Maybe');
        break; }}@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Name YK'),
        backgroundColor: Colors.red,
      ),
      body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Center(
          child: new Column(
            children: <Widget>[
              new Text(_value),
              new RaisedButton(onPressed: _askUser, child: new Text('Click me'"" "" "" "" "" "" }}Copy the code

AlertDialog

Introduction to the

A dialog that interrupts the user’s operation and requires user confirmation

Commonly used attributes

The property name type instructions
actions List The (optional) set of actions displayed at the bottom of the dialog box
backgroundColor Color The background color of the surface of this dialog box
content Widget The (optional) content of the dialog box is displayed in a light font in the center of the dialog box
contentPadding EdgeInsetsGeometry Fill the content
contentTextStyle TextStyle The style of text for this AlertDialog content
elevation double Z coordinates for this dialog box
semanticLable String The accessibility framework is used for semantic labels of dialog boxes that notify screen transitions when the dialog box is opened and closed.
title Widget The (optional) title of the dialog box is displayed in large font at the top of the dialog box.
titlePadding EdgeInsetsGeometry Fill in around the title
titleTextStyle TextStyle The AlertDialog title is the style of the text
shape ShapeBorder The shape of the border of this dialog box.

A simple example

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

void main(){
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => new _State();
}

//State is information of the application that can change over time or when some actions are taken.
class _State extends State<MyApp>{

  Future _showAlert(BuildContext context, String message) async {
    return showDialog(
        context: context,
        child: new AlertDialog(
          title: new Text(message),
          content: Text(message,style: TextStyle(fontSize: 14.0),),
          actions: <Widget>[
            new FlatButton(onPressed: () => Navigator.pop(context), child: new Text('no')),
            new FlatButton(onPressed: () => Navigator.pop(context), child: new Text('Ok')))); }@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Name here'),
        backgroundColor: Colors.red,
      ),
      //hit Ctrl+space in intellij to know what are the options you can use in flutter widgets
      body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Center(
          child: new Column(
            children: <Widget>[
              new Text('Add widgets here'),
              new RaisedButton(onPressed: () => _showAlert(context, 'Do you like flutter, I do! '), child: new Text('Click me'"" "" "" "" "" "" }}Copy the code

BottomSheet

Introduction to the

The BottomSheet is a list that slides up from the bottom of the screen (to show more content). You can call showBottomSheet() or showModalBottomSheet to pop up

Commonly used attributes

The property name type instructions
animationController AnimationController Animation that controls the bottom worksheet position
builder WidgetBuilder The builder of the worksheet content.
elevation double The z coordinate that places this material relative to its parent.
onClosing VoidCallback Called when the bottom sheet begins to close
enableDrag bool If true, you can drag the bottom paper up and down by sliding down

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: BottomSheetPage()));

class BottomSheetPage extends StatefulWidget {
  @override
  _BottomSheetPageState createState() => _BottomSheetPageState();
}

class _BottomSheetPageState extends State<BottomSheetPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BottomSheet sample'),
      ),
      body: Container(
        child: Center(
            child: FlatButton(
              color: Colors.red,
                onPressed: () => showBottom(context), child: Text('showBottomSheet'))))); } } Future<Widget> showBottom(BuildContext buildContext)async {
 return await showModalBottomSheet(
     context: buildContext, builder: (context){
   return ListView.builder(
       itemCount: 100,
       itemBuilder: (context,index){
     return ListTile(
       onTap: (){
         print("index:$index");
         Navigator.pop(context);
       },
       leading:Icon(Icons.ac_unit),title:Text('Dev_Yk:$index')); }); }); }Copy the code

ExpansionPanel

Introduction to the

The extension panel contains a creation process that allows you to lightly edit elements. The ExpansionPanel widget implements this component.

Commonly used attributes

The property name type instructions
body Widget The body of the extension panel is displayed below the title.
headerBuilder ExpansionPanelHeaderBuilder Build widget builders for extension panel titles.
isExpander bool Whether the panel is extended.

A simple example

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: ExpansionPanelListDemo(),
  ));
}

class ExpansionPanelListDemo extends StatefulWidget {
  @override
  _ExpansionPanelListDemoState createState() => _ExpansionPanelListDemoState();
}

class ExpandStateBean{
  var isOpen;
  var index;
  ExpandStateBean(this.index,this.isOpen);
}

class _ExpansionPanelListDemoState extends State<ExpansionPanelListDemo> {
  var currentPanelIndex = - 1;
  List<int> mList;
  List<ExpandStateBean> expandStateList;
  _ExpansionPanelListDemoState() {
    mList = new List(a); expandStateList=new List(a);for (int i = 0; i < 10; i++) {
      mList.add(i);
      expandStateList.add(ExpandStateBean(i, false));
    }
  }


  _setCurrentIndex(int index,isExpand) {
    setState(() {
      expandStateList.forEach((item){
        if (item.index==index) {
          item.isOpen=!isExpand;
        }
      });

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("ExpansionPanel sample"),
        ),
        body: SingleChildScrollView(child: ExpansionPanelList(
          children: mList.map((index) {
            return new ExpansionPanel(
              headerBuilder: (context, isExpanded) {
                return new ListTile(
                  title: new Text('I'm the $index title')); }, body:new Padding(
                padding: EdgeInsets.symmetric(horizontal: 5.0),
                child: Container(height: 100.0,
                  color: Colors.blue,
                  alignment: Alignment.center,
                  child:Icon(Icons.security,size: 35.0,),), ), isExpanded: expandStateList[index].isOpen, ); }).toList(), expansionCallback: (index, bol) { _setCurrentIndex(index,bol); },),)); }}Copy the code

SnackBar

Introduction to the

A lightweight message prompt with optional actions, displayed at the bottom of the screen.

Commonly used attributes

The property name type instructions
action SnackBarAction (Optional) Users can perform operations based on the snack bar.
animatiion Animation Animation of entrance and exit
backgroundColor Color Background color of Snackbar. By default, the color is dark gray
content Widget The main content
duration Duration The length of time should be displayed

A simple example

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: SnackBarPage(),
      ),
    );

class SnackBarPage extends StatefulWidget {
  @override
  _SnackBarPageState createState() => _SnackBarPageState();
}

class _SnackBarPageState extends State<SnackBarPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar sample'),
      ),
      body: Center(
        child: new ListView(
          children: <Widget>[
            new FlatButton(
              onPressed: null,
              child: new Text('I am the button'),),new Builder(builder: (BuildContext context) {
              return new Center(
                child: new GestureDetector(
                  onTap: () {
                    final mySnackBar = SnackBar(
                      content: new Text('I am a SnackBar),
                      backgroundColor: Colors.red,
                      duration: Duration(seconds: 1),
                      action: new SnackBarAction(label: 'I am the Scackbar button', onPressed: () {
                        print('Snackbar button was clicked'); })); Scaffold.of(context).showSnackBar(mySnackBar); }, child:new Text('Click on me to show SnackBar'),),); }),],),); }}Copy the code

Information display

Image

Refer to the catalog base Widget/ Image Image

Icon

Refer to the catalog base Widget/ Icon Icon

Chip

Introduction to the

Tag, a Material Widget. It can present a complex content entity, such as a contact, in a small block.

Commonly used attributes

The property name type instructions
avatar Widget The widget displayed before the chip label.
backgroudColor Color Color for an unselected enabled chip background
clipBehavior Clip Depending on this option, the content will be clipped (or not clipped)
deleteButtonTooltipMessage String Message for the chip delete button tooltip.
deleteIcon Widget The icon that is displayed when onDeleted is set.
deleteIconColor Color Delete the color of the icon. The default value is based on the environment icontheme.color
elevation double The elevation applied on a chip relative to its parent.
label Widget The main content of the chip
labelStyle TextStyle The style to apply to the chip label
materialTapTargetSize MaterialTapTargetSize Configures the minimum size of the click target
onDeleted VoidCallback Called when the user clicks deleteIcon to delete the chip
padding EdgeInsetsGeometry The filling between chip content and shape
shape ShapeBorder ShapeBorder is drawn around the chip

A simple example

import 'package:flutter/material.dart';

void main() =>runApp (MaterialApp(home: ClipSample()));

class ClipSample extends StatefulWidget {
  @override
  _ClipSampleState createState() => _ClipSampleState();
}

class _ClipSampleState extends State<ClipSample> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Clip Sample"),
      ),
      body: Center(
        child: Chip(
          avatar: CircleAvatar(
            backgroundColor: Colors.grey.shade800,
            child: Text('Dev'),
          ),
          label: Text('YKun'),),),); }}Copy the code

Tooltip

Introduction to the

A text prompt tool that helps explain a button or other user interface and displays a prompt label when the widget is held down for a long time (and when the user takes other appropriate actions).

Commonly used attributes

The property name type instructions
child widget The widget below this widget in the tree
excludeFromSemantics bool Whether the tooltip message should be excluded from the semantic tree.
height double The amount of vertical space a tooltip should occupy (within its fill).
message String Text to display in the tooltip
padding EdgeInsetsGeometry The amount of space to insert the child
preferBelow bool Whether the tooltip is displayed below the widget by default
verticalOffset double The amount of vertical distance between the widget and the displayed tooltip

A simple example

// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

void main()=>runApp(MaterialApp(home: TooltipDemo(),));
const String _introText =
    'Tooltips are short identifying messages that briefly appear in response to '
    'a long press. Tooltip messages are also used by services that make Flutter '
    'apps accessible, like screen readers.';

class TooltipDemo extends StatelessWidget {

  static const String routeName = '/material/tooltips';

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Tooltips'),
      ),
      body: Builder(
          builder: (BuildContext context) {
            return SafeArea(
              top: false,
              bottom: false,
              child: ListView(
                children: <Widget>[
                  Text(_introText, style: theme.textTheme.subhead),
                  Row(
                    children: <Widget>[
                      Text('Long press the ', style: theme.textTheme.subhead),
                      Tooltip(
                        message: 'call icon',
                        child: Icon(
                          Icons.call,
                          size: 18.0,
                          color: theme.iconTheme.color,
                        ),
                      ),

                      Tooltip(
                        message: 'Long press and it shows me.',
                        child: Text('Test click display', style: theme.textTheme.subhead),
                      ),
                      Text(' icon.', style: theme.textTheme.subhead),
                    ],
                  ),
         /* Center(child: IconButton(iconSize: 48.0, icon: const icon (iconicon.call), color: theme.icontheme.color, tooltip: 'Place a phone call', onPressed: () { Scaffold.of(context).showSnackBar(const SnackBar( content: Text('That was an ordinary tap.'), )); },),), * /
                ]
                    .map<Widget>((Widget widget) {
                  return Padding(
                    padding: const EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0), child: widget, ); }) .toList(), ), ); })); }}Copy the code

DataTable

Introduction to the

The data table shows the original data set. They are typically found in desktop enterprise products. The DataTable Widget implements this component

Commonly used attributes

The property name type instructions
columns List The configuration and labelling of the columns in the table.
onSelectAll ValueSetter Called when the user selects or deselects each row using the check box in the title row.
rows List The data displayed per row (excluding column header rows). Must not be null, but can be null.
sortAscending bool SortColumnIndex Specifies whether the columns mentioned in the column index are sorted in ascending order.
sortColumnIndex int The column of the current primary sort key.

A simple example

// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

void main()=>runApp(MaterialApp(home: DataTableDemo(),));
class Dessert {
  Dessert(this.name, this.calories, this.fat, this.carbs, this.protein, this.sodium, this.calcium, this.iron);
  final String name;
  final int calories;
  final double fat;
  final int carbs;
  final double protein;
  final int sodium;
  final int calcium;
  final int iron;

  bool selected = false;
}

class DessertDataSource extends DataTableSource {
  final List<Dessert> _desserts = <Dessert>[
    Dessert('Frozen yogurt'.159.6.0.24.4.0.87.14.1),
    Dessert('Ice cream sandwich'.237.9.0.37.4.3.129.8.1),
    Dessert('Eclair'.262.16.0.24.6.0.337.6.7),
    Dessert('Cupcake'.305.3.7.67.4.3.413.3.8),
    Dessert('Gingerbread'.356.16.0.49.3.9.327.7.16),
    Dessert('Jelly bean'.375.0.0.94.0.0.50.0.0),
    Dessert('Lollipop'.392.0.2.98.0.0.38.0.2),
    Dessert('Honeycomb'.408.3.2.87.6.5.562.0.45),
    Dessert('Donut'.452.25.0.51.4.9.326.2.22),
    Dessert('KitKat'.518.26.0.65.7.0.54.12.6),

    Dessert('Frozen yogurt with sugar'.168.6.0.26.4.0.87.14.1),
    Dessert('Ice cream sandwich with sugar'.246.9.0.39.4.3.129.8.1),
    Dessert('Eclair with sugar'.271.16.0.26.6.0.337.6.7),
    Dessert('Cupcake with sugar'.314.3.7.69.4.3.413.3.8),
    Dessert('Gingerbread with sugar'.345.16.0.51.3.9.327.7.16),
    Dessert('Jelly bean with sugar'.364.0.0.96.0.0.50.0.0),
    Dessert('Lollipop with sugar'.401.0.2.100.0.0.38.0.2),
    Dessert('Honeycomb with sugar'.417.3.2.89.6.5.562.0.45),
    Dessert('Donut with sugar'.461.25.0.53.4.9.326.2.22),
    Dessert('KitKat with sugar'.527.26.0.67.7.0.54.12.6),

    Dessert('Frozen yogurt with honey'.223.6.0.36.4.0.87.14.1),
    Dessert('Ice cream sandwich with honey'.301.9.0.49.4.3.129.8.1),
    Dessert('Eclair with honey'.326.16.0.36.6.0.337.6.7),
    Dessert('Cupcake with honey'.369.3.7.79.4.3.413.3.8),
    Dessert('Gingerbread with honey'.420.16.0.61.3.9.327.7.16),
    Dessert('Jelly bean with honey'.439.0.0.106.0.0.50.0.0),
    Dessert('Lollipop with honey'.456.0.2.110.0.0.38.0.2),
    Dessert('Honeycomb with honey'.472.3.2.99.6.5.562.0.45),
    Dessert('Donut with honey'.516.25.0.63.4.9.326.2.22),
    Dessert('KitKat with honey'.582.26.0.77.7.0.54.12.6),

    Dessert('Frozen yogurt with milk'.262.8.4.36.12.0.194.44.1),
    Dessert('Ice cream sandwich with milk'.339.11.4.49.12.3.236.38.1),
    Dessert('Eclair with milk'.365.18.4.36.14.0.444.36.7),
    Dessert('Cupcake with milk'.408.6.1.79.12.3.520.33.8),
    Dessert('Gingerbread with milk'.459.18.4.61.11.9.434.37.16),
    Dessert('Jelly bean with milk'.478.2.4.106.8.0.157.30.0),
    Dessert('Lollipop with milk'.495.2.6.110.8.0.145.30.2),
    Dessert('Honeycomb with milk'.511.5.6.99.14.5.669.30.45),
    Dessert('Donut with milk'.555.27.4.63.12.9.433.32.22),
    Dessert('KitKat with milk'.621.28.4.77.15.0.161.42.6),

    Dessert('Coconut slice and frozen yogurt'.318.21.0.31.5.5.96.14.7),
    Dessert('Coconut slice and ice cream sandwich'.396.24.0.44.5.8.138.8.7),
    Dessert('Coconut slice and eclair'.421.31.0.31.7.5.346.6.13),
    Dessert('Coconut slice and cupcake'.464.18.7.74.5.8.422.3.14),
    Dessert('Coconut slice and gingerbread'.515.31.0.56.5.4.316.7.22),
    Dessert('Coconut slice and jelly bean'.534.15.0.101.1.5.59.0.6),
    Dessert('Coconut slice and lollipop'.551.15.2.105.1.5.47.0.8),
    Dessert('Coconut slice and honeycomb'.567.18.2.94.8.0.571.0.51),
    Dessert('Coconut slice and donut'.611.40.0.58.6.4.335.2.28),
    Dessert('Coconut slice and KitKat'.677.41.0.72.8.5.63.12.12)];void _sort<T>(Comparable<T> getField(Dessert d), bool ascending) {
    _desserts.sort((Dessert a, Dessert b) {
      if(! ascending) {final Dessert c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  int _selectedCount = 0;

  @override
  DataRow getRow(int index) {
    assert(index >= 0);
    if (index >= _desserts.length)
      return null;
    final Dessert dessert = _desserts[index];
    return DataRow.byIndex(
      index: index,
      selected: dessert.selected,
      onSelectChanged: (bool value) {
        if(dessert.selected ! = value) { _selectedCount += value ?1 : - 1;
          assert(_selectedCount >= 0);
          dessert.selected = value;
          notifyListeners();
        }
      },
      cells: <DataCell>[
        DataCell(Text('${dessert.name}')),
        DataCell(Text('${dessert.calories}')),
        DataCell(Text('${dessert.fat.toStringAsFixed(1)}')),
        DataCell(Text('${dessert.carbs}')),
        DataCell(Text('${dessert.protein.toStringAsFixed(1)}')),
        DataCell(Text('${dessert.sodium}')),
        DataCell(Text('${dessert.calcium}% ')),
        DataCell(Text('${dessert.iron}% ')),,); }@override
  int get rowCount => _desserts.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;

  void _selectAll(bool checked) {
    for (Dessert dessert in _desserts)
      dessert.selected = checked;
    _selectedCount = checked ? _desserts.length : 0; notifyListeners(); }}class DataTableDemo extends StatefulWidget {
  static const String routeName = '/material/data-table';

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

class _DataTableDemoState extends State<DataTableDemo> {
  int _rowsPerPage = PaginatedDataTable.defaultRowsPerPage;
  int _sortColumnIndex;
  bool _sortAscending = true;
  final DessertDataSource _dessertsDataSource = DessertDataSource();

  void _sort<T>(Comparable<T> getField(Dessert d), int columnIndex, bool ascending) {
    _dessertsDataSource._sort<T>(getField, ascending);
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Data tables'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(20.0),
        children: <Widget>[
          PaginatedDataTable(
            header: const Text('Nutrition'),
            rowsPerPage: _rowsPerPage,
            onRowsPerPageChanged: (int value) { setState(() { _rowsPerPage = value; }); },
            sortColumnIndex: _sortColumnIndex,
            sortAscending: _sortAscending,
            onSelectAll: _dessertsDataSource._selectAll,
            columns: <DataColumn>[
              DataColumn(
                label: const Text('Dessert (100g serving)'),
                onSort: (int columnIndex, bool ascending) => _sort<String>((Dessert d) => d.name, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Calories'),
                tooltip: 'The total amount of food energy in the given serving size.',
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calories, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Fat (g)'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.fat, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Carbs (g)'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.carbs, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Protein (g)'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.protein, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Sodium (mg)'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.sodium, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Calcium (%)'),
                tooltip: 'The amount of calcium as a percentage of the recommended daily amount.',
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calcium, columnIndex, ascending),
              ),
              DataColumn(
                label: const Text('Iron (%)'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.iron, columnIndex, ascending), ), ], source: _dessertsDataSource, ), ], ), ); }}Copy the code

Card

Introduction to the

A Material Design card. Has a rounded corner and shadow

Commonly used attributes

The property name type instructions
borderOnForeground bool Whether to draw the shape frame 26 in front of the child
child Widget The widget below this widget in the tree
clipBebavior Clip Depending on this option, the content will be clipped (or not clipped)
color double Place the z coordinate of the card. This controls the size of the shadow under the card.
margin DegeInsetsGeometry The blank area around the card
semanticContainer bool Whether this widget represents a single semantic container or whether false represents a collection of single semantic nodes.
shape ShapeBorder The shape of the card material.

A simple example

// This sample shows creation of a [Card] widget that shows album information
// and two actions.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Code Sample for material.Card',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Card sample'), ), body: MyStatelessWidget(), ), ); }}class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context,index){
      return Card(
        margin: EdgeInsets.all(5.0),
        child: const ListTile(
          leading: Icon(Icons.album),
          title: Text('The Enchanted Nightingale'),
          subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.'),),); }); }}Copy the code

LinearProgressIndicator

Introduction to the

A linear progress bar, and a circular progress bar CircularProgressIndicator

Commonly used attributes

The property name type instructions
backgroudColor Color Background color of the progress indicator. By default, the current theme of ThemeData. BackgroundColor.

A simple example

import 'package:flutter/material.dart';

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

class LinearProgressIndicatorPage extends StatefulWidget {
  @override
  _LinearProgressIndicatorPageState createState() => _LinearProgressIndicatorPageState();
}

class _LinearProgressIndicatorPageState extends State<LinearProgressIndicatorPage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('LinearProgressIndicator sample'), ), body: LinearProgressIndicator( backgroundColor: Colors.red, ), ), ); }}Copy the code

layout

ListTile

Introduction to the

A line of fixed height, usually containing some text, and a front – or end-of-line icon.

Commonly used attributes

The property name type instructions
contentPadding EdgeInsetsGeometry Internal filling
dense bool Is this list block part of a vertically dense list
enable bool Is this list block interactive
isThreeLine bool Is this list block intended to display three lines of text
leading Widget The widget to be displayed before the title
onLongPress GestureTapCallback Called when the user long-presses this list tile
onTap GestureTapCallback Called when the user clicks on this list tile
selected bool If this block is also enabled, the icon and text will be rendered in the same color
title Widget Main Contents of the list
trailing Widget The widget displayed after the title
subtitle Widget Other content displayed below the title

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: ListTitlePage(),
    ));

class ListTitlePage extends StatefulWidget {
  @override
  _ListTitlePageState createState() => _ListTitlePageState();
}

class _ListTitlePageState extends State<ListTitlePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListTitle sample'),
      ),
      body: ListView.builder(
          itemCount: 100,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              leading: Icon(Icons.supervised_user_circle),
              title: Text('xiao Ming $index'), trailing: Icon(Icons.backup), ); })); }}Copy the code

Stepper

Introduction to the

A Material Design step indicator that shows the course of a series of steps

Commonly used attributes

The property name type instructions
controlsBuilder ControlsWidgetBuild Callback used to create a custom control
currentStep int Index of the index of the current step that displays the content
onStepCancel VoidCallback The callback is called when the cancel button is clicked
onStepTapped ValueChanged The index of the callback called when a step is called is passed as a parameter.
physics ScrollPhysics How the stepper’s scroll view should respond to user input.
steps List The step, title, subtitle, and icon of the stepper are always displayed.
type StepperType Determine the type of stepper for the layout. In the case of StepperType.Horizontal, the content of the current step is displayed below, rather than in the case of stepperType.vertical, where it is displayed between.

A simple example

import 'package:flutter/material.dart';

void main() =>
    runApp(new MaterialApp(title: "Stepper sample", home: new StepperPage()));

class StepperPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => StepperPageState();
}

class StepperPageState extends State<StepperPage> {
  int current_step = 0;
  List<Step> my_steps = [
    new Step(
        title: new Text("Step 1"), content: new Text("Hello"), isActive: true),
    new Step(
        title: new Text("Step 2"), content: new Text("World"), isActive: true),
    new Step(
        title: new Text("Step 3"),
        content: new Text("Hello World"),
        isActive: true)];@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar:
      new AppBar(title: new Center(child: new Text("Stepper sample"))),
      body: new Container(
        child: new Stepper(
          currentStep: this.current_step,
          steps: my_steps,
          type: StepperType.vertical,
          onStepTapped: (step) {
            setState(() {
              current_step = step;
            });
          },
          onStepCancel: () {
            setState(() {
              if (current_step > 0) {
                current_step = current_step - 1;
              } else {
                current_step = 0; }}); }, onStepContinue: () { setState(() {if (current_step < my_steps.length - 1) {
                current_step = current_step + 1;
              } else {
                current_step = 0; }}); },),),); }}Copy the code

Divider

Introduction to the

A logical 1 pixel thick horizontal divider with fills on both sides

Commonly used attributes

The property name type instructions
color Color Background color of dashed line
height double The height of the dotted line
indent double Divide the amount of blank space on the left

A simple example

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: ListTitlePage(),
    ));

class ListTitlePage extends StatefulWidget {
  @override
  _ListTitlePageState createState() => _ListTitlePageState();
}

class _ListTitlePageState extends State<ListTitlePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Divider sample'),
      ),
      body: Column(
        children: <Widget>[
          ListTile(
            leading: Icon(Icons.supervised_user_circle),
            title: Text('Ming'),
            trailing: Icon(Icons.backup),
          ),
          Divider(
            height: 10.0,
            color: Color(0xffff0000),
          ),
          ListTile(
            leading: Icon(Icons.supervised_user_circle),
            title: Text('Ming'),
            trailing: Icon(Icons.backup),
          ),
          Divider(
            height: 10.0,
            color: Color(0xffff0000)))))))); }}Copy the code

Thank you

  1. Because Chinese website
  2. The Flutter GitHub hosted address