Flutter components (3) Button components

Flutter Development Notes
Flutter components (3) Button components

- Article information -
Author: Jack Lee (jcLee95)
Visit me at: https://jclee95.blog.csdn.net
Email: [email protected].
Shenzhen Chine
Address of this article:https://blog.csdn.net/qq_28550263/article/details/131387856

【介绍】:本文介绍 Flutter 按钮类组件。

Previous section: " Flutter Components (2) Text and Input Box Components " | Next section: " Flutter Components (4) Image Components "

Table of contents


1 Raised button: RaisedButton component

The RaisedButton component is a basic button component in Flutter, which has a raised three-dimensional effect. We can use this to create buttons with click events.

1.1 Create a RaisedButton component

To create a RaisedButton component in Flutter, we can use the RaisedButton constructor. For example:

RaisedButton(
  onPressed: () {
    
    
    // 点击事件处理
  },
  child: Text('点击我'),
)

1.2 Set RaisedButton style

We can use the color, , textColoretc. properties to style the RaisedButton component. Here is an example:

RaisedButton(
  onPressed: () {
    
    
    // 点击事件处理
  },
  child: Text('点击我'),
  color: Colors.blue,
  textColor: Colors.white,
)

1.3 Set RaisedButton shape

We can shapeset the shape for the RaisedButton component using properties. To do this, we need to create an ShapeBorderobject and pass to shapethe property. Here is an example:

RaisedButton(
  onPressed: () {
    
    
    // 点击事件处理
  },
  child: Text('点击我'),
  color: Colors.blue,
  textColor: Colors.white,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(10),
  ),
)

1.4 Set RaisedButton click event

We can onPressedset click event for RaisedButton component using properties. Here is an example:

RaisedButton(
  onPressed: () {
    
    
    // 点击事件处理
    print('按钮被点击');
  },
  child: Text('点击我'),
  color: Colors.blue,
  textColor: Colors.white,
)

1.5 Disable the RaisedButton component

To disable the RaisedButton component we can onPressedset the property to null. Buttons in the disabled state do not respond to click events. Here is an example:

RaisedButton(
  onPressed: null,
  child: Text('禁用按钮'),
  color: Colors.blue,
  textColor: Colors.white,
)

1.6 Summary

The RaisedButton component is a commonly used button component in Flutter, which has a raised three-dimensional effect. We can easily customize the display and function of the button by setting different properties, such as style, shape, click event, etc. In the next chapters, we will learn about other basic components like FlatButton and IconButton components.

1.7 Deprecated: TextButton is recommended instead.

According to the documentation, FlatButton, RaisedButton, and OutlineButton have been replaced by TextButton, ElevatedButton, and OutlinedButton, respectively. ButtonTheme has also been replaced by TextButtonTheme, ElevatedButtonTheme and OutlinedButtonTheme. Please refer to: https://docs.flutter.dev/release/breaking-changes/buttons

2 Flat button: FlatButton component

FlatButton is a button component in Flutter. It is a button without three-dimensional effect and is usually used for less prominent operations. FlatButton displays some visual effects, such as water ripples, when the user interacts with it. Next, we will introduce the basic usage and properties of the FlatButton component.

2.1 Create FlatButton

To create a FlatButton, we can use the FlatButton constructor. Here is a simple example:

FlatButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('点击我'),
)

2.2 Common properties

FlatButton has many customizable properties, the following are some commonly used properties:

  • onPressed: This is a callback function that will be triggered when the user clicks the button. If this property is null, the button will be disabled.
  • child: This attribute defines the content inside the button, usually a Text or Icon component.
  • color: Set the background color of the button.
  • disabledColor: Set the background color of the button in the disabled state.
  • highlightColor: Set the highlight color when the button is pressed.
  • splashColor: Set the color of the water ripple when the button is clicked.
  • textColor: Sets the color of the text inside the button.
  • padding: Set the padding inside the button.

2.3 Examples

Here's a simple example using FlatButton:

FlatButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('FlatButton被点击了');
  },
  child: Text('点击我'),
  color: Colors.blue,
  textColor: Colors.white,
  padding: EdgeInsets.all(16.0),
)

In this example, we create a FlatButton with a blue background and white text. When the user clicks the button, the console will output "FlatButton was clicked".

2.4 Deprecated: ElevatedButton is recommended instead.

According to the documentation, FlatButton, RaisedButton, and OutlineButton have been replaced by TextButton, ElevatedButton, and OutlinedButton, respectively. ButtonTheme has also been replaced by TextButtonTheme, ElevatedButtonTheme and OutlinedButtonTheme. Please refer to: https://docs.flutter.dev/release/breaking-changes/buttons

3. Outline button: OutlineButton component

In this section, we will introduce the OutlineButton component in Flutter, including creating an OutlineButton, setting the OutlineButton style, setting the OutlineButton shape, setting the OutlineButton click event, and disabling the OutlineButton component.

3.1 Create the OutlineButton component

To create an OutlineButton, we can use the OutlineButton constructor. Here is a simple example:

OutlineButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('点击我'),
)

3.2 Set the OutlineButton style

OutlineButton has many customizable properties, the following are some commonly used properties:

  • borderSide: Sets the style of the button border.
  • highlightedBorderColor: Sets the color of the border when the button is pressed.
  • disabledBorderColor: Set the color of the border of the button in the disabled state.
  • splashColor: Set the color of the water ripple when the button is clicked.
  • textColor: Sets the color of the text inside the button.
  • padding: Set the padding inside the button.

3.3 Set OutlineButton shape

We can shapeset the shape of OutlineButton through properties. For example, we can set the rounded corners of the button:

OutlineButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('点击我'),
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(10.0),
  ),
)

3.4 Set the OutlineButton click event

To set the click event of the OutlineButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

OutlineButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('OutlineButton被点击了');
  },
  child: Text('点击我'),
)

3.5 Disable the OutlineButton component

If we want to disable the OutlineButton component, we just need to onPressedset the property to null.

OutlineButton(
  onPressed: null,
  child: Text('我是禁用的按钮'),
)

3.6 Summary

In this section, we introduce the basic usage and some common properties of the OutlineButton component. By using OutlineButton, we can easily add a button with a border to our Flutter application.

3.7 Deprecated: OutlinedButton is recommended instead

According to the documentation, FlatButton, RaisedButton, and OutlineButton have been replaced by TextButton, ElevatedButton, and OutlinedButton, respectively. ButtonTheme has also been replaced by TextButtonTheme, ElevatedButtonTheme and OutlinedButtonTheme. Please refer to: https://docs.flutter.dev/release/breaking-changes/buttons

4. Icon button: IconButton component

Official document location: https://api.flutter.dev/flutter/material/IconButton-class.html

In this section, we will introduce the IconButton component in Flutter, including creating an IconButton, setting the IconButton style, setting the IconButton click event, and disabling the IconButton component.

4.1 Create IconButton component

To create an IconButton, we can use the IconButton constructor.

For example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('IconButton Example')),
        body: Center(
          child: IconButton(
            icon: Icon(Icons.favorite),
            // 在这里处理按钮点击事件
            onPressed: () {
    
    
              print('IconButton pressed!');
            },
            color: Colors.red,
            iconSize: 48,
            tooltip: 'Add to favorites',
          ),
        ),
      ),
    );
  }
}

In this example, we create an IconButton component.

Among them, iconthe attribute is set to a heart icon. The icon used here is Google’s built-in icon in Flutter. Icon is an icon class. You can refer to the blog post "Using Icons in Flutter (Including Self-made Icon Library Scheme)" , the address is: https://jclee95. blog.csdn.net/article/details/123309530 .

In the code, we set the onPressed attribute, and when the icon button is clicked, it will print "IconButton pressed!" on the console. The color of the icon is red and the size is 48. Through the tooltip attribute, we set a prompt message "Add to favorites", which will be displayed when the user presses the icon for a long time.
insert image description here
After clicking, you can see in the console:
insert image description here

4.2 Set IconButton style

IconButton has many customizable properties, the following are some commonly used properties:

  • color: Sets the color of the icon.
  • highlightColor: Set the highlight color when the button is pressed.
  • splashColor: Set the color of the water ripple when the button is clicked.
  • iconSize: Sets the size of the icon.

4.3 Set IconButton click event

To set the click event of the IconButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

IconButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('IconButton被点击了');
  },
  icon: Icon(Icons.favorite),
)

4.4 Disable the IconButton component

If we want to disable the IconButton component, we just need to onPressedset the property to null.

IconButton(
  onPressed: null,
  icon: Icon(Icons.favorite),
)

4.5 Summary

In this section, we introduce the basic usage and some common properties of the IconButton component. By using IconButton, we can easily add icon buttons to our Flutter application.

5. Floating action button: FloatingActionButton component

Official document location: https://api.flutter.dev/flutter/material/FloatingActionButton-class.html

In this section, we will introduce the FloatingActionButton component in Flutter, including creating a FloatingActionButton, setting the FloatingActionButton style, setting the FloatingActionButton click event, and disabling the FloatingActionButton component.

5.1 Create FloatingActionButton component

To create a FloatingActionButton, we can use the FloatingActionButton constructor.

For example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FloatingActionButton Example')),
        body: Center(
          child: Text('Floating Action Button Example'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
    
    
            print('FloatingActionButton pressed!');
          },
          child: Icon(Icons.add),
          backgroundColor: Colors.blue,
          tooltip: 'Add new item',
        ),
      ),
    );
  }
}

insert image description here
In this example, we create a FloatingActionButton button and set its onPressedproperties. When the button is clicked, it will print "FloatingActionButton pressed!" to the console.

The child component of the button is a plus icon. The background color of the button is blue.

Through tooltipthe attribute, we set a prompt message "Add new item", which will be displayed when the user presses the button for a long time. The FloatingActionButton is added to the Scaffold property floatingActionButtonto make it float in the lower right corner of the screen.

5.2 Set the FloatingActionButton style

FloatingActionButton has many customizable properties, the following are some commonly used style properties:

  • backgroundColor: Set the background color of the button.
  • foregroundColor: Sets the color of the icon inside the button.
  • splashColor: Set the color of the water ripple when the button is clicked.
  • elevation: Set the shadow size of the button.
  • shape: Sets the shape of the button.

5.3 Set FloatingActionButton click event

To set the click event of the FloatingActionButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

FloatingActionButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('FloatingActionButton被点击了');
  },
  child: Icon(Icons.add),
)

5.4 Disable the FloatingActionButton component

If we want to disable the FloatingActionButton component, we only need to onPressedset the property to null.

FloatingActionButton(
  onPressed: null,
  child: Icon(Icons.add),
)

5.5 Summary

In this section, we introduce the basic usage and some common properties of the FloatingActionButton component. By using FloatingActionButton, we can easily add floating action buttons to Flutter applications, which are usually used to perform major actions in the application.

6. Popup menu button: PopupMenuButton component

Official document location: https://api.flutter.dev/flutter/material/PopupMenuButton-class.html

In this section, we will introduce the PopupMenuButton component in Flutter, including creating a PopupMenuButton, setting the PopupMenuButton style, setting the PopupMenuButton click event, and customizing the PopupMenuButton menu items.

6.1 Create PopupMenuButton component

To create a PopupMenuButton, we can use the PopupMenuButton constructor.

For example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('PopupMenuButton Example')),
        body: Center(
          child: PopupMenuButton<String>(
            itemBuilder: (BuildContext context) {
    
    
              return {
    
    'Option 1', 'Option 2', 'Option 3'}
                  .map((String choice) {
    
    
                return PopupMenuItem<String>(
                  value: choice,
                  child: Text(choice),
                );
              }).toList();
            },
            onSelected: (String value) {
    
    
              print('Selected: $value');
            },
            icon: Icon(Icons.more_vert),
            tooltip: 'Show menu',
          ),
        ),
      ),
    );
  }
}

In this example, we create a PopupMenuButton component . itemBuilderAttributes are used to build the options of the pop-up menu, we have created 3 options here, namely "Option 1", "Option 2" and "Option 3". Since the property is set onSelected, when the user selects an option, "Selected: " and the value of the option will be printed to the console. Sets iconthe property to a vertical three-dot icon. Through tooltipthe attribute, we set a prompt message "Show menu", which will be displayed when the user presses the button for a long time. As shown in the figure:
insert image description here
You can see the print results on the console:
insert image description here

6.2 Set PopupMenuButton style

PopupMenuButton has many customizable properties, the following are some commonly used properties:

  • icon: Set the icon of the button.
  • color: Set the color of the button.
  • shape: Sets the shape of the button.
  • elevation: Set the shadow size of the button.

6.3 Set PopupMenuButton click event

To set the click event of the PopupMenuButton, we need to onSelectedprovide a callback function for the property. This callback function will be triggered when the user clicks on a menu item.

PopupMenuButton(
  itemBuilder: (BuildContext context) {
    
    
    return [
      PopupMenuItem(
        value: 'item1',
        child: Text('菜单项1'),
      ),
      PopupMenuItem(
        value: 'item2',
        child: Text('菜单项2'),
      ),
    ];
  },
  onSelected: (value) {
    
    
    // 在这里处理菜单项点击事件
    print('选中的菜单项:$value');
  },
)

6.4 Customize the PopupMenuButton menu item

We can PopupMenuItemcustomize the style of menu items by modifying the properties. Here are some commonly used properties:

  • value: Set the value of the menu item, when the user clicks the menu item, this value will be passed to the onSelectedcallback function.
  • height: Set the height of the menu item.
  • enabled: Sets whether the menu item is clickable.
  • textStyle: Sets the style of the menu item text.

6.5 Summary

In this section, we introduce the basic usage and some common properties of the PopupMenuButton component. By using PopupMenuButton, we can easily add a popup menu button to the Flutter application, thus providing richer operation options.

7. iOS style button: CupertinoButton component

Official document location: https://api.flutter.dev/flutter/cupertino/CupertinoButton-class.html

In this section, we will introduce the CupertinoButton component in Flutter, including creating a CupertinoButton, setting the CupertinoButton style, setting the CupertinoButton click event, and disabling the CupertinoButton component. The CupertinoButton component is a button style designed for iOS, which can help us easily achieve interface effects similar to iOS native applications.

7.1 Create the CupertinoButton component

To create a CupertinoButton, we can use the CupertinoButton constructor. Here is a simple example:

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

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('CupertinoButton Example')),
        body: Center(
          child: CupertinoButton(
            onPressed: () {
    
    
              print('CupertinoButton pressed!');
            },
            color: Colors.blue,
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            borderRadius: BorderRadius.circular(8.0),
            child: const Text('Press me'),
          ),
        ),
      ),
    );
  }
}

insert image description here

In this example, we create a CupertinoButton component.

By setting onPressedthe property, when the button is clicked, it will print "CupertinoButton pressed!" to the console. The child component of the button is a text component that says "Press me".

The background color of the button is blue. With paddingthe attribute, we set the padding of the button to be 16 pixels horizontally and 8 pixels vertically. The property is set borderRadiusso that the button's corner radius is 8 pixels.

We click three times and we can see on the console:

insert image description here

7.2 Set CupertinoButton style

CupertinoButton has many customizable properties, the following are some commonly used properties:

  • color: Set the background color of the button.
  • disabledColor: Sets the color of the button in the disabled state.
  • padding: Set button padding.
  • borderRadius: Sets the corner radius of the button.
  • minSize: Sets the minimum size of the button.
  • pressedOpacity: Sets the transparency of the button in the pressed state.

7.3 Set CupertinoButton click event

To set the click event of the CupertinoButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

CupertinoButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('CupertinoButton被点击了');
  },
  child: Text('iOS样式按钮'),
)

7.4 Disable the CupertinoButton component

If we want to disable the CupertinoButton component, we just need to onPressedset the property to null.

CupertinoButton(
  onPressed: null,
  child: Text('iOS样式按钮'),
)

7.5 Summary

In this section, we introduce the basic usage and some common properties of the CupertinoButton component. By using CupertinoButton, we can easily add iOS-style buttons to the Flutter application, so as to achieve an interface effect similar to that of iOS native applications.

8. Text button: TextButton component (button without outline or fill color)

Official document location: https://api.flutter.dev/flutter/material/TextButton-class.html

In this section, we will introduce the TextButton component in Flutter, including creating a TextButton, setting the TextButton style, setting the TextButton click event, and disabling the TextButton component. TextButton is a simple text button without background and border, usually used for secondary or secondary actions.

8.1 Create TextButton component

To create a TextButton, we can use the TextButton constructor. Here is a simple example:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('TextButton Example')),
        body: Center(
          child: TextButton(
            onPressed: () {
    
    
              print('TextButton pressed!');
            },
            style: TextButton.styleFrom(
              foregroundColor: Colors.blue,
              padding:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            ),
            child: const Text(
              'Press me',
              style: TextStyle(fontSize: 20),
            ),
          ),
        ),
      ),
    );
  }
}

insert image description here

In this example, we create a TextButton component.

The subcomponent of the button is a text component that displays "Press me" with a font size of 20 pixels. Through the style attribute and the TextButton.styleFrom method, we set the text color of the button to be blue, and the padding to be 16 pixels horizontally and 8 pixels vertically.

By setting onPressedthe property, when the button is clicked, it will print "TextButton pressed!" to the console:

insert image description here
(here I ordered twice)

8.2 Set TextButton style

TextButton has many customizable properties, the following are some commonly used properties:

  • style: Use to ButtonStyleset the style of the button, including text color, background color, border, etc.
  • onSurface: Set the text color of the button in disabled state.

Here is an example of styling a TextButton:

TextButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('TextButton'),
  style: ButtonStyle(
    foregroundColor: MaterialStateProperty.all(Colors.red),
  ),
)

8.3 Set TextButton click event

To set the click event of the TextButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

TextButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('TextButton被点击了');
  },
  child: Text('TextButton'),
)

8.4 Disable the TextButton component

If we want to disable the TextButton component, we only need to onPressedset the property to null.

TextButton(
  onPressed: null,
  child: Text('TextButton'),
)

8.5 Summary

In this section, we introduce the basic usage and some common properties of the TextButton component. By using TextButton, we can easily add concise text buttons to our Flutter application for a clear and easy-to-understand interface.

9. Elevate button: ElevatedButton component

In this section, we will introduce the ElevatedButton component in Flutter, including creating an ElevatedButton, setting the ElevatedButton style, setting the ElevatedButton click event, and disabling the ElevatedButton component. ElevatedButton is a Material Design style button that has a floating effect and shows a shadow when pressed.

9.1 Create an ElevatedButton component

To create an ElevatedButton, we can use the ElevatedButton constructor. Here is a simple example:

ElevatedButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('ElevatedButton'),
)

9.2 Setting the style of ElevatedButton

ElevatedButton has many customizable properties, the following are some commonly used properties:

  • style: Use to ButtonStyleset the style of the button, including background color, border, shadow, etc.
  • onPrimary: Set the color of the button text and icon.
  • elevation: Set the shadow size of the button.

For example:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('ElevatedButton Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
    
    
              print('ElevatedButton pressed!');
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              padding:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
            child: const Text(
              'Press me',
              style: TextStyle(fontSize: 20),
            ),
          ),
        ),
      ),
    );
  }
}

insert image description here

In this example, we create an ElevatedButton component.

The subcomponent of the button is a text component that displays "Press me" with a font size of 20 pixels. Through stylethe property and the ElevatedButton.styleFrom method, we set the background color of the button to be blue, and the padding to be 16 pixels horizontally and 8 pixels vertically. Additionally, we set the shape of the button to be a rounded rectangle with a corner radius of 8 pixels.

By setting onPressedthe property, when the button is clicked, it will print "ElevatedButton pressed!" to the console.
insert image description here
(here I ordered 3 times)

9.3 Set ElevatedButton click event

To set the click event of the ElevatedButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

ElevatedButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('ElevatedButton被点击了');
  },
  child: Text('ElevatedButton'),
)

9.4 Disable the ElevatedButton component

If we want to disable the ElevatedButton component, we just need to onPressedset the property to null.

ElevatedButton(
  onPressed: null,
  child: Text('ElevatedButton'),
)

9.5 Summary

In this section, we introduce the basic usage and some common properties of the ElevatedButton component. By using ElevatedButton, we can easily add Material Design-style buttons to the Flutter application to achieve a beautiful and interactive interface.

10. Outline button: OutlinedButton component

In this section, we will introduce the OutlinedButton component in Flutter, including creating an OutlinedButton, setting the OutlinedButton style, setting the OutlinedButton click event, and disabling the OutlinedButton component. An OutlinedButton is a button with a border and no background color, usually used for secondary actions or to distinguish it from other buttons.

10.1 Create the OutlinedButton component

To create an OutlinedButton, we can use the OutlinedButton constructor. For example:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('OutlinedButton Example')),
        body: Center(
          child: OutlinedButton(
            onPressed: () {
    
    
              print('OutlinedButton pressed!');
            },
            style: OutlinedButton.styleFrom(
              foregroundColor: Colors.blue,
              side: const BorderSide(color: Colors.blue, width: 2),
              padding:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
            child: const Text(
              'Press me',
              style: TextStyle(fontSize: 20),
            ),
          ),
        ),
      ),
    );
  }
}

In this example, we create an OutlinedButton component.

The subcomponent of the button is a text component that displays "Press me" with a font size of 20 pixels.

Through the style attribute and the OutlinedButton.styleFrom method, we set the text color of the button to be blue, the border color to be blue, the border width to be 2 pixels, and the padding to be 16 pixels horizontally and 8 pixels vertically. Additionally, we set the shape of the button to be a rounded rectangle with a corner radius of 8 pixels.
insert image description here
By setting its onPressedproperty, when the button is clicked, it will print "OutlinedButton pressed!" to the console:

insert image description here

(I clicked 2 times here)

10.2 Setting OutlinedButton style

OutlinedButton has many customizable properties, the following are some commonly used properties:

  • style: Use to ButtonStyleset the style of the button, including text color, border color, border width, etc.
  • onSurface: Set the text color of the button in disabled state.

Here is an example of styling an OutlinedButton:

OutlinedButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
  },
  child: Text('OutlinedButton'),
  style: ButtonStyle(
    foregroundColor: MaterialStateProperty.all(Colors.red),
    side: MaterialStateProperty.all(BorderSide(color: Colors.red, width: 2)),
  ),
)

10.3 Set OutlinedButton click event

To set the click event of the OutlinedButton, we need to onPressedprovide a callback function for the property. This callback function will be fired when the user clicks the button.

OutlinedButton(
  onPressed: () {
    
    
    // 在这里处理按钮点击事件
    print('OutlinedButton被点击了');
  },
  child: Text('OutlinedButton'),
)

10.4 Disable the OutlinedButton component

If we want to disable the OutlinedButton component, we only need to onPressedset the property to null.

OutlinedButton(
  onPressed: null,
  child: Text('OutlinedButton'),
)

10.5 Summary

In this section, we introduce the basic usage and some common properties of the OutlinedButton component. By using OutlinedButton, we can easily add a bordered button to our Flutter application for a clear and easy-to-understand interface. Outline buttons are better suited for secondary actions or for differentiation from other buttons than other types of buttons.

11. Fill button: FilledButton component

Components added in Flutter 2.6.

In this chapter, we will learn how to use FilledButton component in Flutter. FilledButton is a filled button that can be used in various scenarios, such as submitting forms, triggering events, etc. We'll start by creating the FilledButton component, then style the component, and finally handle the event.

11.1 Create FilledButton component

First, we need to create a FilledButton component. In Flutter, you can use FilledButtonthe constructor to create a FilledButton component.

The following is an example officially provided by Flutter:

import 'package:flutter/material.dart';

/// Flutter code sample for [FilledButton].

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      theme: ThemeData(
          colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true),
      home: Scaffold(
        appBar: AppBar(title: const Text('FilledButton Sample')),
        body: Center(
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Column(children: <Widget>[
                const SizedBox(height: 30),
                const Text('Filled'),
                const SizedBox(height: 15),
                FilledButton(
                  onPressed: () {
    
    },
                  child: const Text('Enabled'),
                ),
                const SizedBox(height: 30),
                const FilledButton(
                  onPressed: null,
                  child: Text('Disabled'),
                ),
              ]),
              const SizedBox(width: 30),
              Column(children: <Widget>[
                const SizedBox(height: 30),
                const Text('Filled tonal'),
                const SizedBox(height: 15),
                FilledButton.tonal(
                  onPressed: () {
    
    },
                  child: const Text('Enabled'),
                ),
                const SizedBox(height: 30),
                const FilledButton.tonal(
                  onPressed: null,
                  child: Text('Disabled'),
                ),
              ])
            ],
          ),
        ),
      ),
    );
  }
}

dButton component and added it to the center of the Scaffold.  ](https://img-blog.csdnimg.cn/9941161adb5847acabd2276dd27d4c62.gif)

11.2 Setting component styles

Next, we'll learn how to style the FilledButton component. The FilledButton component provides some properties, eg style, that can be used to customize the style of the component. Here is an example of styling a FilledButton:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('FilledButton 样式示例'),
        ),
        body: Center(
          child: FilledButton(
            onPressed: () {
    
    
              print('点击了 FilledButton');
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
              foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
              textStyle: MaterialStateProperty.all<TextStyle>(
                const TextStyle(fontSize: 20),
              ),
              padding: MaterialStateProperty.all<EdgeInsetsGeometry>(
                const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
              ),
            ),
            child: const Text('点击我'),
          ),
        ),
      ),
    );
  }
}

insert image description here

In this example, we set the background color, foreground color, text style and padding of the FilledButton.

Another example with richer styles is:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('FilledButton Example')),
        body: Center(
          child: TextButton(
            onPressed: () {
    
    
              print('FilledButton pressed!');
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.orange),
              foregroundColor: MaterialStateProperty.all(Colors.white),
              padding: MaterialStateProperty.all(
                  const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0)),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.0),
              )),
              side: MaterialStateProperty.all(
                  const BorderSide(color: Colors.deepOrange, width: 3)),
              elevation: MaterialStateProperty.all(6.0),
              shadowColor: MaterialStateProperty.all(Colors.orangeAccent),
            ),
            child: const Text(
              'Press me',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),
    );
  }
}

In this example, we add the following styles to the FilledButton:

  • The button background color is orange.
  • The text color on the button is white, the font size is 20, and the font is bold.
  • Button padding is 24px horizontally and 12px vertically.
  • The shape of the button is a rounded rectangle with a corner radius of 12 pixels.
  • The button border is dark orange and has a width of 3 pixels.
  • The button shadow height is 6.0 and the shadow color is orange.

The effect is:

insert image description here
insert image description here

11.3 Event Handling

Finally, we will learn how to handle the events of the FilledButton component. When the user clicks the FilledButton, onPressedthe event can be handled through the property. Here's an example of handling a FilledButton click event:

import 'package:flutter/material.dart';

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

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

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('FilledButton 事件示例'),
        ),
        body: Center(
          child: FilledButton(
            onPressed: () {
    
    
              print('点击了 FilledButton');
              // 在这里处理点击事件
            },
            child: const Text('点击我'),
          ),
        ),
      ),
    );
  }
}

In this example, we onPressedadded a callback function in the property to handle the click event of the FilledButton.

11.4 Summary

In this section, we introduced how to use the FilledButton component in Flutter , including how to create a FilledButton component, set the component style, and handle events.

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/131387856