Quick Start Learning Flutter (1)

Table of contents

Preface

New Project

Project entrance

Entrance to Dart (entrance to the project)

layout

view component

Container

Text

Image

Row (horizontal layout) and Column (vertical layout)

ListView (list view)

GridView (grid view)

Stack (cascading layout)

Card

AppBar

FloatingActionButton (floating action button)

TextField (text input box)

Button

Checkbox

Radio (radio button)

Switch

Slider

ProgressIndicator

AlertDialog (Dialog)


Preface

The previous steps of setting up the environment, creating projects, etc. are all too simple.
Without further ado~ let’s get started~ let’s go directly to the code~ and start learning.

New Project

Having created a new project, are you a bit confused and don’t know where to start writing our hello world?

I created a new project with two packages, android and ios. According to my personal understanding, both are preloaded with good interfaces written by Dart.

Generally, if there are special needs, you need to add the required configuration items to the corresponding project.

Here we are starting to learn, so I won’t go into more detail on this part.

document

Dart文档指南Learn to use the Dart language and libraries.icon-default.png?t=N7T8https://dart.dev/guides

Project entrance

Entrance to Dart (entrance to the project)

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '阿斯顿'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

layout

In this example, we used Stackto create a layered layout. In Stack, we used Positionedto implement absolute layout, Alignto implement relative layout, and Positioned.fillto implement weighted layout.

Each Positionedand Alignhas attributes such as top, left, right, bottometc., which are used to specify the position of sub-components. Positioned.fillThe child widget will fill the entire parent widget.

Through this layer-by-layer layout approach, we can achieve complex interface layouts.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack( // 使用绝对布局
          children: [
            Positioned( // 使用相对布局
              top: 50,
              left: 50,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.red,
              ),
            ),
            Positioned(
              top: 100,
              left: 100,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
              ),
            ),
            Align( // 使用相对布局
              alignment: Alignment.bottomCenter,
              child: Container(
                width: 200,
                height: 200,
                color: Colors.green,
              ),
            ),
            Positioned(
              top: 200,
              left: 200,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.yellow,
              ),
            ),
            Positioned.fill( // 使用权重布局
              child: Container(
                color: Colors.orange,
                child: Center(
                  child: Text(
                    'Hello World',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

view component

Container

Used to create a rectangular container, which can set properties such as background color, border, padding, etc.

  • Alignment: Set the alignment of subcomponents inside the Container.
  • padding: Set the padding of the internal subcomponents of the Container.
  • color: Set the background color of Container.
  • width: Set the width of Container.
  • height: Set the height of Container.
  • margin: Set the margin between the Container and its parent component.
  • decoration: Set the decoration of the Container, which can include background images, borders, etc.
  • child: Set the child component of Container.

Here is an example using annotations:

Container(
  // 设置Container的宽度为200
  width: 200,
  // 设置Container的高度为100
  height: 100,
  // 设置Container的背景颜色为红色
  color: Colors.red,
  // 设置Container与其父组件之间的外边距为10
  margin: EdgeInsets.all(10),
  // 设置Container内部子组件的对齐方式为居中
  alignment: Alignment.center,
  // 设置Container内部子组件的内边距为20
  padding: EdgeInsets.all(20),
  // 设置Container的装饰,包括背景图片和边框
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage('assets/images/background.png'),
      fit: BoxFit.cover,
    ),
    border: Border.all(
      color: Colors.black,
      width: 2,
    ),
    borderRadius: BorderRadius.circular(10),
  ),
  // 设置Container的子组件为一个文本组件
  child: Text('Hello World'),
)

Text

Used to display text content, and can set attributes such as font style, color, alignment, etc.

  • data: Set the text content displayed by Text.
  • style: Set the style of Text, including font, size, color, etc.
  • textAlign: Set the alignment of Text.
  • maxLines: Set the maximum number of lines displayed by Text.
  • overflow: Set the processing method when Text exceeds the maximum number of lines.
  • textDirection: Set the text direction of Text.
  • softWrap: Set whether Text wraps automatically.
  • textScaleFactor: Set the scaling ratio of Text

Here is an example using annotations:

Text(
  // 设置Text显示的文本内容为Hello World
  data: 'Hello World',
  // 设置Text的样式,包括字体、大小、颜色等
  style: TextStyle(
    fontSize: 20,
    fontWeight: FontWeight.bold,
    color: Colors.blue,
  ),
  // 设置Text的对齐方式为居中
  textAlign: TextAlign.center,
  // 设置Text显示的最大行数为2
  maxLines: 2,
  // 设置Text超出最大行数时的处理方式为省略号
  overflow: TextOverflow.ellipsis,
  // 设置Text的文本方向为从左到右
  textDirection: TextDirection.ltr,
  // 设置Text是否自动换行为true
  softWrap: true,
  // 设置Text的缩放比例为1.5
  textScaleFactor: 1.5,
)

Image

Used to display images, which can be loaded from local or network.

  • image: Specify the image to be displayed, which can be a local image, a network image or a memory image. You can use AssetImage, NetworkImage or MemoryImage to create ImageProvider objects.

  • Width: Specify the width of the image, which can be a specific value or a placeholder. For example: double.infinity means that the width fills the parent container.

  • height: Specify the height of the image, which can be a specific value or a placeholder. For example: double.infinity means the height fills the parent container.

  • fit: Specify the adaptation method of the picture, which can be BoxFit.contain (maintain the aspect ratio of the picture and display the picture completely in the container), BoxFit.cover (maintain the aspect ratio of the picture and display the picture completely in the container) and crop the excess part), BoxFit.fill (stretch the image to fill the container), BoxFit.fitWidth (maintain the aspect ratio of the image, fill the image width with the container), BoxFit.fitHeight (maintain the aspect ratio of the image, increase the image height filling container) etc.

  • Alignment: Specify the alignment of the image in the container, which can be Alignment.center (center alignment), Alignment.topLeft (upper left alignment), Alignment.bottomRight (lower right alignment), etc.

  • repeat: Specify the repetition method of the image, which can be ImageRepeat.noRepeat (no repeat), ImageRepeat.repeat (repeat both horizontally and vertically), ImageRepeat.repeatX (repeat horizontally), ImageRepeat.repeatY (repeat vertically), etc.

Here is an example using annotations:

Image(
  image: AssetImage('assets/images/flutter_logo.png'), // 指定要显示的本地图片
  width: 200, // 指定图片的宽度
  height: 200, // 指定图片的高度
  fit: BoxFit.cover, // 图片适应方式为完整地显示在容器内并裁剪超出部分
  alignment: Alignment.center, // 图片居中对齐
  repeat: ImageRepeat.noRepeat, // 图片不重复
)

Row (horizontal layout) and Column (vertical layout)

Used to arrange subcomponents horizontally or vertically.

  1. mainAxisAlignment (main axis alignment): used to control the alignment of subcomponents on the main axis.

    • MainAxisAlignment.start: The subcomponent is near the starting position on the main axis.
    • MainAxisAlignment.end: The subcomponent is near the end position on the main axis.
    • MainAxisAlignment.center: The subcomponent is centered on the main axis.
    • MainAxisAlignment.spaceBetween: The subcomponents are evenly distributed on the main axis, leaving no gaps at the beginning and end.
    • MainAxisAlignment.spaceAround: Subcomponents are evenly distributed on the main axis, leaving gaps at the beginning and end.
    • MainAxisAlignment.spaceEvenly: Subcomponents are evenly distributed on the main axis, including the head and tail.
  2. crossAxisAlignment: used to control the alignment of subcomponents on the cross axis.

    • CrossAxisAlignment.start: The child component is close to the starting position on the cross axis.
    • CrossAxisAlignment.end: The child component is near the end position on the cross axis.
    • CrossAxisAlignment.center: The child component is centered on the cross axis.
    • CrossAxisAlignment.stretch: The child component stretches to fill the parent container on the cross axis.
    • CrossAxisAlignment.baseline: Subcomponents are aligned to the baseline on the cross axis.
  3. mainAxisSize (main axis size): used to control the size of the main axis.

    • MainAxisSize.max: The main axis takes up as much space as possible in the parent container.
    • MainAxisSize.min: The main axis is shrunk as much as possible to the minimum space required by the subcomponent.
  4. verticalDirection (vertical direction): used to control the layout direction of subcomponents.

    • VerticalDirection.down: Subcomponents are arranged from top to bottom.
    • VerticalDirection.up: Subcomponents are arranged from bottom to top.

Here is an example using annotation instructions:

Row(
  // 主轴对齐方式:居中对齐
  mainAxisAlignment: MainAxisAlignment.center,
  // 交叉轴对齐方式:居中对齐
  crossAxisAlignment: CrossAxisAlignment.center,
  // 主轴尺寸:尽可能地占用父容器的空间
  mainAxisSize: MainAxisSize.max,
  // 垂直方向:从上到下排列
  verticalDirection: VerticalDirection.down,
  children: [
    // 子组件
    Text('Child 1'),
    Text('Child 2'),
    Text('Child 3'),
  ],
);

ListView (list view)

Used to display a scrollable list, which can be vertical or horizontal.

  1. scrollDirection: Specifies the scrolling direction of the list, which can be vertical (default) or horizontal.

    • Values: Axis.vertical (vertical direction, default value), Axis.horizontal (horizontal direction)
  2. reverse (reverse scrolling): Specifies whether the list scrolls in reverse direction.

    • Values: true, false (default)
  3. controller (scroll controller): The scroll controller of the specified list, which can be used to control the scroll position or listen for scroll events.

    • Value: ScrollController object
  4. primary (whether to fill in the main axis direction): specifies whether to fill in the main axis direction of the list.

    • Values: true, false (default)
  5. physics (scrolling physics effect): Specifies the scrolling physics effect of the list.

    • Value: ScrollPhysics object
  6. shrinkWrap (whether to resize based on child component size): Specifies whether the list is resized based on child component size.

    • Values: true, false (default)
  7. padding: Specify the padding of the list.

    • Value: EdgeInsets object
  8. itemExtent (subcomponent fixed size): Specifies the fixed size of the subcomponent to optimize performance.

    • Value: double type
  9. children (child component list): A list of child components of the specified list.

    • Value: List<Widget> object

The usage notes are as follows:

ListView(
  // 滚动方向为垂直方向
  scrollDirection: Axis.vertical,
  // 不反向滚动
  reverse: false,
  // 使用自定义的滚动控制器
  controller: ScrollController(),
  // 主轴方向上不填充
  primary: false,
  // 使用默认的滚动物理效果
  physics: null,
  // 根据子组件尺寸调整大小
  shrinkWrap: true,
  // 内边距为10.0
  padding: EdgeInsets.all(10.0),
  // 子组件固定尺寸为50.0
  itemExtent: 50.0,
  // 子组件列表
  children: [
    // 子组件1
    Container(),
    // 子组件2
    Container(),
    // ...
  ],
)

When encountering multiple layouts, we use ListView.builder to create a ListView containing 10 items. In itemBuilder, we decide to use different layouts based on the parity of the index. Even-numbered items use a red-background layout, and odd-numbered items use a blue-background layout. Each layout contains a centered text that displays the corresponding item number. Run the code and you will see a multi-layout ListView in which the background of even-numbered items is red and the background of odd-numbered items is blue.

import 'package:flutter/material.dart';

class MultiLayoutListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (BuildContext context, int index) {
        if (index % 2 == 0) {
          // 偶数项使用红色背景的布局
          return Container(
            color: Colors.red,
            height: 100,
            child: Center(
              child: Text(
                'Item $index',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          );
        } else {
          // 奇数项使用蓝色背景的布局
          return Container(
            color: Colors.blue,
            height: 150,
            child: Center(
              child: Text(
                'Item $index',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          );
        }
      },
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Multi Layout ListView'),
      ),
      body: MultiLayoutListView(),
    ),
  ));
}

GridView (grid view)

Used to display a list in a two-dimensional grid layout.

  1. scrollDirection: Set the scroll direction, the optional values ​​are Axis.vertical (vertical direction) and Axis.horizontal (horizontal direction).
  2. reverse: Set whether to scroll in reverse direction, the default is false.
  3. controller: Set the scroll controller, which can be used to control the scroll position and listen for scroll events.
  4. primary: Set whether to use the parent's PrimaryScrollController. The default is false.
  5. physics: Set scrolling physical effects, such as BouncingScrollPhysics, ClampingScrollPhysics, etc.
  6. shrinkWrap: Set whether to determine the length of the GridView based on the total length of the child items. The default is false.
  7. padding: Set the inner margin of GridView.
  8. crossAxisSpacing: Set the spacing of children in the cross axis direction.
  9. mainAxisSpacing: Set the spacing of children in the main axis direction.
  10. childAspectRatio: Set the aspect ratio of the child.
  11. children: Set the GridView's child list

Sample code using annotations is as follows:

GridView(
  // 设置滚动方向为垂直方向
  scrollDirection: Axis.vertical,
  // 设置是否反向滚动
  reverse: false,
  // 设置滚动控制器
  controller: ScrollController(),
  // 设置是否使用父级的PrimaryScrollController
  primary: false,
  // 设置滚动物理效果
  physics: BouncingScrollPhysics(),
  // 设置是否根据子项的总长度来确定GridView的长度
  shrinkWrap: false,
  // 设置GridView的内边距
  padding: EdgeInsets.all(10),
  // 设置子项在交叉轴方向的间距
  crossAxisSpacing: 10,
  // 设置子项在主轴方向的间距
  mainAxisSpacing: 10,
  // 设置子项的宽高比
  childAspectRatio: 1,
  // 设置GridView的子项列表
  children: [
    // 子项1
    Container(),
    // 子项2
    Container(),
    // 子项3
    Container(),
  ],
)

Stack (cascading layout)

Used to lay out subcomponents in a cascading manner.

  1. Alignment: Specifies the alignment of subcomponents in the Stack.

    • Alignment object, the default value is AlignmentDirectional.topStart
  2. fit (how to handle unpositioned subcomponents): Specify how unpositioned subcomponents are handled in the Stack.

    • StackFit enumeration type, the default value is StackFit.loose
    • StackFit.loose: Unpositioned subcomponents are positioned based on their own size
    • StackFit.expand: Unpositioned subcomponents fill the full size of the Stack
  3. overflow (overflow processing method): Specify the processing method when the sub-component exceeds the scope of the Stack.

    • Overflow enumeration type, the default value is Overflow.clip
    • Overflow.clip: Crop the excess part
    • Overflow.visible: The excess part is still visible

The usage notes are as follows:

Stack(
  // 对齐方式为居中对齐
  alignment: Alignment.center,
  // 未定位的子组件根据自身大小来确定位置
  fit: StackFit.loose,
  // 超出部分裁剪掉
  overflow: Overflow.clip,
  children: [
    // 子组件1
    Positioned(
      // 子组件1的左上角对齐Stack的左上角
      top: 0,
      left: 0,
      child: Container(),
    ),
    // 子组件2
    Positioned(
      // 子组件2的右下角对齐Stack的右下角
      bottom: 0,
      right: 0,
      child: Container(),
    ),
    // 子组件3
    Container(),
  ],
)

Card

Used to create a card with rounded corners and shadow effects.

  1. color: The background color of the card, which can be a Color object. Example: color: Colors.blue

  2. elevation: the height of the card, used to create shadow effects, can be a double value. Example: elevation: 4.0

  3. shape: The shape of the card, which can be a ShapeBorder object. Example: shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0))

  4. margin: the outer margin of the card, which can be an EdgeInsets object. Example: margin: EdgeInsets.all(10.0)

  5. child: the content component of the card, which can be any Widget. Example: child: Text('Hello World')

Use annotation descriptions to provide more information by adding annotations before properties, for example:

Card(
  // 设置卡片的背景颜色为红色
  color: Colors.red,
  
  // 设置卡片的高度为8.0
  elevation: 8.0,
  
  // 设置卡片的形状为圆角矩形
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
  
  // 设置卡片的外边距为10.0
  margin: EdgeInsets.all(10.0),
  
  // 设置卡片的内容为一个文本部件
  child: Text('Hello World'),
)

AppBar

Used to create a top navigation bar that usually contains a title, icons, and action buttons.

  1. leading: Widget type, a control set on the left side of the AppBar, usually an icon button or a return button.
  2. title: Widget type, set the title control in the middle of AppBar.
  3. actions: List<Widget> type, set to the list of controls on the right side of the AppBar.
  4. backgroundColor: Color type, set the background color of AppBar.
  5. elevation: double type, sets the shadow height of AppBar.
  6. brightness: Brightness type, set the brightness mode of AppBar, which can be Brightness.light (light mode) or Brightness.dark (dark mode).
  7. centerTitle: bool type, sets whether the title is displayed in the center.
  8. automaticallyImplyLeading: bool type, sets whether to automatically display the leading control, the default is true.
  9. flexibleSpace: Widget type, sets the scalable space of AppBar, usually used to achieve some special effects, such as gradient background.
  10. bottom: PreferredSizeWidget type, sets the control at the bottom of AppBar, usually a TabBar or PreferredSize component.
  11. shape: ShapeBorder type, set the shape of AppBar, such as RoundedRectangleBorder.
  12. toolbarHeight: double type, sets the height of AppBar.
  13. toolbarOpacity: double type, sets the transparency of AppBar.

Here is an example using annotations:

AppBar(
  // 设置AppBar左侧的返回按钮
  leading: IconButton(
    icon: Icon(Icons.arrow_back),
    onPressed: () {
      // 返回上一页的操作
    },
  ),
  // 设置AppBar中间的标题
  title: Text('App Bar'),
  // 设置AppBar右侧的控件列表
  actions: [
    IconButton(
      icon: Icon(Icons.search),
      onPressed: () {
        // 执行搜索操作
      },
    ),
    IconButton(
      icon: Icon(Icons.more_vert),
      onPressed: () {
        // 执行更多操作
      },
    ),
  ],
  // 设置AppBar的背景颜色
  backgroundColor: Colors.blue,
  // 设置AppBar的阴影高度
  elevation: 4.0,
  // 设置AppBar的亮度模式为浅色模式
  brightness: Brightness.light,
  // 设置标题居中显示
  centerTitle: true,
  // 设置AppBar的高度
  toolbarHeight: 56.0,
)

FloatingActionButton (floating action button)

Used to create a circular button suspended on the interface, usually used to perform main operations.

  1. onPressed: The callback function triggered when the button is clicked.
  2. tooltip: The text tip displayed when the user long presses the button.
  3. child: The child component of the button, usually an icon.
  4. backgroundColor: The background color of the button.
  5. foregroundColor: The foreground color of the button, used for icons and text.
  6. elevation: The height of the button's shadow.
  7. highlightElevation: The height of the button's shadow when pressed.
  8. disabledElevation: Shadow height when the button is disabled.
  9. shape: The shape of the button, which can be round, rectangular, etc.
  10. heroTag: A unique identifier used to specify the button when switching pages.
  11. mini: Whether to set the button to a small size.
  12. isExtended: Whether to set the button to extended size.
  13. clipBehavior: The clipping behavior of the button, used to handle the situation when the sub-component exceeds the scope of the button.

These properties can be combined as needed, for example:

FloatingActionButton(
  onPressed: () {
    // 点击按钮时触发的回调函数
  },
  tooltip: 'Add',
  child: Icon(Icons.add),
  backgroundColor: Colors.blue,
  foregroundColor: Colors.white,
  elevation: 4.0,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(20.0),
  ),
)

In the above example, when the user clicks the button, a callback function is triggered. A plus sign icon is displayed on the button with a blue background color, a white foreground color, a shadow height of 4.0, and a rounded rectangle shape.

TextField (text input box)

Used to receive text input from the user.

  1. controller: TextEditingController type, used to control the content of the text input box.
  2. focusNode: FocusNode type, used to control the focus of the text input box.
  3. decoration: InputDecoration type, used to set the decoration style of the text input box, such as borders, prompt text, etc.
  4. keyboardType: TextInputType type, used to set the keyboard type, such as numeric keyboard, email keyboard, etc.
  5. textInputAction: TextInputAction type, used to set the type of keyboard action button, such as Done, Next, etc.
  6. style: TextStyle type, used to set the style of the text in the text input box, such as font, color, etc.
  7. onChanged: ValueChanged<String> type, callback function triggered when the content of the text input box changes.
  8. onSubmitted: ValueChanged<String> type, callback function triggered when the user submits text input.
  9. maxLength: int type, limits the maximum number of characters in the text input box.
  10. obscureText: bool type, whether to hide the input content in password form.
  11. autocorrect: bool type, whether to automatically correct the text entered by the user.
  12. autofocus: bool type, whether to automatically obtain focus.
  13. enabled: bool type, whether to enable the text input box.
  14. textAlign: TextAlign type, sets the alignment of text in the text input box.
  15. cursorColor: Color type, set the color of the cursor.

Here is an example using annotations:

TextField(
  // 用于控制文本输入框的内容
  controller: _textEditingController,
  
  // 用于控制文本输入框的焦点
  focusNode: _focusNode,
  
  // 用于设置文本输入框的装饰样式
  decoration: InputDecoration(
    labelText: 'Username',
    hintText: 'Enter your username',
    border: OutlineInputBorder(),
  ),
  
  // 用于设置键盘类型
  keyboardType: TextInputType.text,
  
  // 用于设置键盘动作按钮的类型
  textInputAction: TextInputAction.done,
  
  // 用于设置文本输入框中文本的样式
  style: TextStyle(
    fontSize: 16.0,
    color: Colors.black,
  ),
  
  // 当文本输入框的内容发生变化时触发的回调函数
  onChanged: (value) {
    // 处理文本变化的逻辑
  },
  
  // 当用户提交文本输入时触发的回调函数
  onSubmitted: (value) {
    // 处理文本提交的逻辑
  },
  
  // 限制文本输入框的最大字符数
  maxLength: 20,
  
  // 是否将输入内容隐藏为密码形式
  obscureText: false,
  
  // 是否自动纠正用户输入的文本
  autocorrect: true,
  
  // 是否自动获取焦点
  autofocus: false,
  
  // 是否启用文本输入框
  enabled: true,
  
  // 设置文本在文本输入框中的对齐方式
  textAlign: TextAlign.start,
  
  // 设置光标的颜色
  cursorColor: Colors.blue,
)

Button

Used to create a clickable button that can set styles and click events.

  1. onPressed: Specifies the callback function when the button is clicked. Callback functions are typically defined using anonymous functions or method references. For example: onPressed: () { /* Code executed after clicking the button */ }

  2. child: Specifies the child widget displayed on the button. It can be Text, Icon, etc. For example: child: Text('button text')

  3. color: Specifies the background color of the button. You can use Color objects or Color values. For example: color: Colors.blue

  4. textColor: Specifies the color of the button text. You can use Color objects or Color values. For example: textColor: Colors.white

  5. disabledColor: Specifies the background color of the button in the disabled state. For example: disabledColor: Colors.grey

  6. disabledTextColor: Specifies the text color of the button in the disabled state. For example: disabledTextColor: Colors.white

  7. padding: Specifies the padding of the button. You can use the EdgeInsets object to define the top, bottom, left, and right margin values. For example: padding: EdgeInsets.all(10.0)

  8. shape: Specifies the shape of the button. You can use RoundedRectangleBorder, CircleBorder and other shapes. For example: shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0))

  9. splashColor: Specifies the color of the water ripple when the button is pressed. For example: splashColor: Colors.red

  10. elevation: Specifies the shadow height of the button. For example: elevation: 5.0

Use annotations to add comments to your code that explain what each property does, for example:

FlatButton(
  onPressed: () {
    // 点击按钮后执行的代码
  },
  child: Text('按钮文本'),
  color: Colors.blue, // 按钮背景颜色
  textColor: Colors.white, // 按钮文本颜色
  disabledColor: Colors.grey, // 禁用状态下的背景颜色
  disabledTextColor: Colors.white, // 禁用状态下的文本颜色
  padding: EdgeInsets.all(10.0), // 按钮内边距
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), // 按钮形状
  splashColor: Colors.red, // 按钮按下时的水波纹颜色
  elevation: 5.0, // 按钮阴影高度
)

Checkbox

Used to indicate an option that can be checked or unchecked.

  1. value: bool type, indicating the selected state of the check box. If true, the checkbox is selected; if false, the checkbox is not selected.
  2. onChanged: ValueChanged<bool> type, indicating the callback function when the selected state of the check box changes. The checked state of the checkbox can be updated in the callback function.
  3. activeColor: Color type, indicating the color of the check box when it is selected. The default is theme color.
  4. checkColor: Color type, indicating the color of the check mark inside the check box. Default is white.
  5. tristate: bool type, indicating whether the check box supports three states (selected, unselected, uncertain). The default is false, which means tri-state is not supported.
  6. materialTapTargetSize: MaterialTapTargetSize type, indicating the click target size of the check box. The default is MaterialTapTargetSize.padded.
  7. visualDensity: VisualDensity type, indicating the visual density of the check box. Default is VisualDensity.comfortable.

Use annotations to add comments to your code that explain what each property does, for example:

Checkbox(
  value: _isChecked, // 当前复选框的选中状态
  onChanged: (bool newValue) {
    setState(() {
      _isChecked = newValue; // 更新复选框的选中状态
    });
  },
  activeColor: Colors.blue, // 复选框选中时的颜色
  checkColor: Colors.white, // 复选框内部勾选标记的颜色
  tristate: false, // 不支持三态
  materialTapTargetSize: MaterialTapTargetSize.padded, // 复选框的点击目标大小
  visualDensity: VisualDensity.comfortable, // 复选框的视觉密度
)

Radio (radio button)

Used to represent a single option within a set of options.

  1. value: T type, indicating the value of the radio button. When the radio button is selected, its value will be passed to groupValue.
  2. groupValue: T type, representing the value of the radio button group. When the value of the radio button is equal to the groupValue, the radio button will be selected.
  3. onChanged: ValueChanged<T> type, indicating the callback function when the selected state of the radio button changes. The value of groupValue can be updated in the callback function.
  4. activeColor: Color type, indicating the color of the radio button when it is selected. The default is theme color.
  5. materialTapTargetSize: MaterialTapTargetSize type, indicating the click target size of the radio button. The default is MaterialTapTargetSize.padded.
  6. visualDensity: VisualDensity type, indicating the visual density of the radio button. Default is VisualDensity.comfortable.

Use annotations to add comments to your code that explain what each property does, for example:

Radio(
  value: _selectedValue, // 当前单选框的值
  groupValue: _groupValue, // 单选框组的值
  onChanged: (T newValue) {
    setState(() {
      _groupValue = newValue; // 更新单选框组的值
    });
  },
  activeColor: Colors.blue, // 单选框选中时的颜色
  materialTapTargetSize: MaterialTapTargetSize.padded, // 单选框的点击目标大小
  visualDensity: VisualDensity.comfortable, // 单选框的视觉密度
)

Switch

A component used to represent a switch state.

  1. value: bool type, indicating the current status of the switch, true means on, false means off.

  2. onChanged: Function type, callback function triggered when the switch status changes.

  3. activeColor: Color type, indicating the color in the open state.

  4. activeTrackColor: Color type, indicating the track color in the open state.

  5. inactiveThumbColor: Color type, indicating the color of the slider in the closed state.

  6. inactiveTrackColor: Color type, indicating the track color in the closed state.

  7. activeThumbImage: ImageProvider type, indicating the slider image in the open state.

  8. inactiveThumbImage: ImageProvider type, representing the slider image in the closed state.

  9. dragStartBehavior: DragStartBehavior type, indicating the behavior of sliding start.

Here is an example that demonstrates how to use the Switch component and its properties:

bool switchValue = false; // 开关的初始状态为关闭

Switch(
  value: switchValue, // 开关的当前状态
  onChanged: (bool newValue) {
    setState(() {
      switchValue = newValue; // 开关状态改变时更新状态值
    });
  },
  activeColor: Colors.blue, // 开启状态下的颜色为蓝色
  activeTrackColor: Colors.blue[200], // 开启状态下的轨道颜色为浅蓝色
  inactiveThumbColor: Colors.grey, // 关闭状态下的滑块颜色为灰色
  inactiveTrackColor: Colors.grey[300], // 关闭状态下的轨道颜色为浅灰色
  activeThumbImage: AssetImage('assets/images/switch_on.png'), // 开启状态下的滑块图片为switch_on.png
  inactiveThumbImage: AssetImage('assets/images/switch_off.png'), // 关闭状态下的滑块图片为switch_off.png
  dragStartBehavior: DragStartBehavior.start, // 滑动开始的行为为从滑块开始
)

In the above example, when the status of the switch changes, the onChanged callback function is called to update the status value of the switch. The color when turned on is blue, the track color is light blue, the slider color is gray, and the track color is light gray. At the same time, the slider image in the on state is switch_on.png, and the slider image in the closed state is switch_off.png. The sliding start behavior is from the slider.

Slider

Used to represent a draggable slider that can select a range of values.

  1. value: double type, indicating the current value of the slider.

  2. onChanged: Function type, callback function triggered when the value of the slider changes.

  3. onChangeStart: Function type, callback function triggered when the slider starts sliding.

  4. onChangeEnd: Function type, callback function triggered when the slider stops sliding.

  5. min: double type, indicating the minimum value of the slider.

  6. max: double type, indicating the maximum value of the slider.

  7. divisions: int type, indicating the number of discrete intervals of the slider.

  8. label: String type, indicating the label of the current value of the slider.

  9. activeColor: Color type, indicating the active color of the slider.

  10. inactiveColor: Color type, indicating the inactive color of the slider.

Here is an example that demonstrates how to use the Slider component and its properties:

double sliderValue = 0.0; // 滑块的初始值为0

Slider(
  value: sliderValue, // 滑块的当前值
  onChanged: (double newValue) {
    setState(() {
      sliderValue = newValue; // 滑块值改变时更新状态值
    });
  },
  onChangeStart: (double startValue) {
    print('滑块开始滑动,当前值为:$startValue'); // 滑块开始滑动时的回调函数
  },
  onChangeEnd: (double endValue) {
    print('滑块停止滑动,当前值为:$endValue'); // 滑块停止滑动时的回调函数
  },
  min: 0.0, // 滑块的最小值为0
  max: 100.0, // 滑块的最大值为100
  divisions: 5, // 滑块的离散间隔数量为5
  label: sliderValue.toString(), // 滑块当前值的标签
  activeColor: Colors.blue, // 滑块的激活颜色为蓝色
  inactiveColor: Colors.grey, // 滑块的非激活颜色为灰色
)

In the above example, when the slider's value changes, the onChanged callback function is called to update the slider's state value. The minimum value of the slider is 0, the maximum value is 100, and the number of discrete intervals is 5. The active color of the slider is blue and the inactive color is gray. A label for the slider's current value appears above the slider. When the slider starts to slide, the onChangeStart callback function is triggered and the current value is printed. When the slider stops sliding, the onChangeEnd callback function is triggered and the current value is printed.

ProgressIndicator

Used to display a progress indicator, which can be circular, linear, or a custom style.

  1. value: The value indicating the current progress, the value range is 0.0 to 1.0, and the default is 0.0.
  2. backgroundColor: The background color of the indicator.
  3. valueColor: The foreground color of the indicator, which can be a fixed color or an animated color.
  4. strokeWidth: The line width of the indicator.
  5. semanticsLabel: A label used for accessibility that describes the meaning of the progress indicator.

Here is an example that demonstrates how to use a CircularProgressIndicator and set its properties:

import 'package:flutter/material.dart';

class MyProgressIndicator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Progress Indicator Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CircularProgressIndicator(  // 使用CircularProgressIndicator
              value: 0.5,  // 设置进度值为0.5
              backgroundColor: Colors.grey,  // 设置背景颜色为灰色
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),  // 设置前景颜色为蓝色
              strokeWidth: 5.0,  // 设置线条宽度为5.0
              semanticsLabel: 'Loading',  // 设置辅助功能标签
            ),
            SizedBox(height: 20.0),  // 添加间距
            LinearProgressIndicator(  // 使用LinearProgressIndicator
              value: 0.8,  // 设置进度值为0.8
              backgroundColor: Colors.grey,  // 设置背景颜色为灰色
              valueColor: AlwaysStoppedAnimation<Color>(Colors.green),  // 设置前景颜色为绿色
              minHeight: 10.0,  // 设置最小高度为10.0
              semanticsLabel: 'Loading',  // 设置辅助功能标签
            ),
          ],
        ),
      ),
    );
  }
}

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

In the example above, we created a page with two progress indicators. The first is a CircularProgressIndicator with a progress value of 0.5, a background color of gray, a foreground color of blue, a line width of 5.0, and an accessibility label of "Loading". The second one is a LinearProgressIndicator with a progress value of 0.8, a background color of gray, a foreground color of green, a minimum height of 10.0, and an accessibility label of "Loading".

AlertDialog (Dialog)

Used to display a dialog box, usually used to prompt the user or obtain the user's confirmation.

  1. title: The title of the dialog box, the type is Widget, the default is.
  2. content: The content of the dialog box, the type is Widget, the default is.
  3. actions: Action button of the dialog box, type is List<Widget>, default is.
  4. shape: The shape of the dialog box, type is ShapeBorder, default is a rounded rectangle.
  5. backgroundColor: The background color of the dialog box, type is Color, and the default is white.
  6. elevation: the height of the dialog box, type is double, the default is 24.0.
  7. semanticLabel: The semantic label of the dialog box, type is String, the default is.

Here is an example that demonstrates how to create an AlertDialog and set its properties:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AlertDialog Example'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Show Dialog'),
            onPressed: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text('Confirmation'),
                    content: Text('Are you sure you want to delete this item?'),
                    actions: [
                      FlatButton(
                        child: Text('Cancel'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      FlatButton(
                        child: Text('Delete'),
                        onPressed: () {
                          // Perform delete operation
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

In this example, we created an AlertDialog, set the title to "Confirmation", and the content to "Are you sure you want to delete this item?". The dialog box has two operation buttons, one is "Cancel", which closes the dialog box after clicking it, and the other is "Delete", which performs the delete operation and closes the dialog box after clicking it.

Guess you like

Origin blog.csdn.net/yuhui77268769/article/details/132872343