Flutter - Buttons

Flutter - Buttons 首页 / Flutter入门教程 / Flutter - Buttons

按钮是图形控制元素,可为用户提供触发事件的信息,Flutter提供了几种类型的按钮,它们具有不同的形状(shapes),样式(styles)和函数(features)。

按钮类型

以下是Flutter中可用的不同类型的按钮:

  • Flat Button
  • Raised Button
  • Floating Button
  • Drop Down Button
  • Icon Button
  • Inkwell Button
  • PopupMenu Button
  • Outline Button

让无涯教程详细讨论每个按钮。

Flat Button

Flat按钮具有两个必需的属性:child和onPressed()。它主要用于工具栏,对话框或与其他内容内联。默认情况下,Flat按钮没有颜色,并且其文本为黑色。但是,无涯教程可以分别使用color和textColor属性来为设置样式。

示例:   打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter FlatButton Example'),
          ),
          body: Center(child: Column(children: [
            Container(
              margin: EdgeInsets.all(25),
              child: FlatButton(
                child: Text('SignUp', style: TextStyle(fontSize: 20.0),),
                onPressed: () {},
              ),
            ),
            Container(
              margin: EdgeInsets.all(25),
              child: FlatButton(
                child: Text('LogIn', style: TextStyle(fontSize: 20.0),),
                color: Colors.blueAccent,
                textColor: Colors.white,
                onPressed: () {},
              ),
            ),
          ]
         ))
      ),
    );
  }
}

如果无涯教程运行此应用程序,无涯教程将看到以下屏幕:

Flutter Buttons

Raised Button

它类似于Flat按钮,但是其elevation将在按下按钮时增加。沿Z轴向UI添加尺寸。它具有多个属性,例如文本颜色(text color),形状(shape),填充(padding),按钮颜色(color),禁用时按钮的颜色,动画时间(animation time)等。

此按钮具有两个回调函数

onPressed()       -  按下按钮时触发。

onLongPress()  -  长按按钮时触发。

请注意,如果未指定onPressed()和onLongPressed()回调,则此按钮处于禁用状态。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  String msg = 'Flutter RaisedButton Example';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter RaisedButton Example'),
          ),
        body: Container(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(msg, style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic),),
                RaisedButton(
                  child: Text("Click Here", style: TextStyle(fontSize: 20),),
                  onPressed: _changeText,
                  color: Colors.red,
                  textColor: Colors.yellow,
                  padding: EdgeInsets.all(8.0),
                  splashColor: Colors.grey,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
  _changeText() {
    setState(() {
      if (msg.startsWith('F')) {
        msg = 'We have learned FlutterRaised button example.';
      } else {
        msg = 'Flutter RaisedButton Example';
      }
    });
  }
}

当无涯教程运行此示例时,它将提供下面的屏幕截图。如果无涯教程点击"Click Here"按钮,它将更改文本消息。显示第二个屏幕截图。

Flutter ButtonsFlutter Buttons

Floating Action Button

FAB按钮是一个圆形图标按钮,可触发无涯教程应用程序中的primary动作。它是当今应用程序中最常用的按钮。无涯教程可以使用此按钮来添加,刷新或共享内容。 Flutter建议每个屏幕最多使用一个FAB按钮。浮动操作按钮有两种类型:

FloatingActionButton                      -  它创建一个简单的圆形浮动按钮,其中带有一个子部件。它必须具有一个子参数才能显示小部件。

FloatingActionButton.extended  -  它会创建一个宽的浮动按钮以及其中的图标和标签。它使用标签和图标参数代替子部件。

示例:   打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(
      appBar: AppBar(
        title: Text("FAB Button Example"),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(icon: Icon(Icons.camera_alt), onPressed: () => {}),
          IconButton(icon: Icon(Icons.account_circle), onPressed: () => {})
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.navigation),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        onPressed: () => {},
      ),
      /*floatingActionButton:FloatingActionButton.extended(
        onPressed: () {},
        icon: Icon(Icons.save),
        label: Text("Save"),
      ), */
    ),
    );
  }
}

在Android仿真器中运行应用程序,它将为UI类似于以下屏幕截图。第二个图像是 FAB.extended 按钮的输出。

Flutter ButtonsFlutter Buttons

DropDown Button

下拉(drop-down)按钮用于在屏幕上创建漂亮的叠加层,允许用户从多个选项中选择任何项目。 Flutter提供了一种简单的方法来实现下拉框或下拉按钮。此按钮显示当前选定的项目,并显示一个箭头,该箭头打开菜单以从多个选项中选择一个项目。

Flutter提供了一个DropdownButton小部件来实现下拉列表,无涯教程可以将其放置在应用程序中的任何位置。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  List _dropdownItems = [
    ListItem(1, "GeeksforGeeks"),
    ListItem(2, "Learnfk"),
    ListItem(3, "tutorialandexample"),
    ListItem(4, "guru99")
  ];

  List> _dropdownMenuItems;
  ListItem _itemSelected;

  void initState() {
    super.initState();
    _dropdownMenuItems = buildDropDownMenuItems(_dropdownItems);
    _itemSelected = _dropdownMenuItems[1].value;
  }

  List> buildDropDownMenuItems(List listItems) {
    List> items = List();
    for (ListItem listItem in listItems) {
      items.add(
        DropdownMenuItem(
          child: Text(listItem.name),
          value: listItem,
        ),
      );
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDown Button Example"),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: Container(
              padding: const EdgeInsets.all(5.0),
              decoration: BoxDecoration(
                  color: Colors.greenAccent,
                  border: Border.all()),
              child: DropdownButtonHideUnderline(
                child: DropdownButton(
                    value: _itemSelected,
                    items: _dropdownMenuItems,
                    onChanged: (value) {
                      setState(() {
                        _itemSelected = value;
                      });
                    }),
              ),
            ),
          ),
          Text("We have selected ${_itemSelected.name}"),
        ],
      ),
    );
  }
}

class ListItem {
  int value;
  String name;

  ListItem(this.value, this.name);
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。第二个图像是下拉菜单中包含的列表的输出。

Flutter ButtonsFlutter Buttons

Icon Button

IconButton是打印在“Material”小部件上的图片。这是一个有用的小部件,可为Flutter UI赋予实质性的设计感觉。无涯教程还可以自定义此按钮的外观。简而言之,它是一个图标,当用户触摸它时会做出反应。

示例: 打开 main.dart 文件并用以下代码替换它。

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("Icon Button Example"),
        ),
        body: Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}
double _speakervolume = 0.0;

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

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

class _MyStatefulWidgetState extends State {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
          icon: Icon(Icons.volume_up),
          iconSize: 50,
          color: Colors.brown,
          tooltip: 'Increase volume by 5',
          onPressed: () {
            setState(() {
              _speakervolume += 5;
            });
          },
        ),
        Text('Speaker Volume: $_speakervolume')
      ],
    );
  }
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。当无涯教程按下音量按钮时,它总是会增加5。

Flutter Buttons

Inkwell Button

InkWell按钮用于触摸响应。通过添加手势反馈来创建交互式的应用程序UI。它主要用于增加波纹效果(splash ripple effect)。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  int _volume = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('InkWell Button Example'),
        ),
        body: Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                splashColor: Colors.green,
                highlightColor: Colors.blue,
                child: Icon(Icons.ring_volume, size: 50),
                onTap: () {
                  setState(() {
                    _volume += 2;
                  });
                },
              ),
              Text (
                  _volume.toString(),
                  style: TextStyle(fontSize: 50)
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。每次无涯教程按铃声音量按钮,音量都会增加2。

Flutter Buttons

PopupMenu Button

它是一个按钮,当按下该按钮时会显示菜单,然后调用onSelected方法关闭菜单。此按钮包含文本和图像。它主要与“Setting”菜单一起使用以列出所有选项。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  Choice _selectedOption = choices[0];

  void _select(Choice choice) {
    setState(() {
      _selectedOption = choice;
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('PopupMenu Button Example'),
          actions: [
            PopupMenuButton(
              onSelected: _select,
              itemBuilder: (BuildContext context) {
                return choices.skip(0).map((Choice choice) {
                  return PopupMenuItem(
                    value: choice,
                    child: Text(choice.name),
                  );
                }).toList();
              },
            ),
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(10.0),
          child: ChoiceCard(choice: _selectedOption),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.name, this.icon});
  final String name;
  final IconData icon;
}

const List choices = const [
  const Choice(name: 'Wi-Fi', icon: Icons.wifi),
  const Choice(name: 'Bluetooth', icon: Icons.bluetooth),
  const Choice(name: 'Battery', icon: Icons.battery_alert),
  const Choice(name: 'Storage', icon: Icons.storage),
];

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.headline;
    return Card(
      color: Colors.greenAccent,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(choice.icon, size: 115.0, color: textStyle.color),
            Text(choice.name, style: textStyle),
          ],
        ),
      ),
    );
  }
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。当无涯教程单击屏幕左上角显示的三个点时,它将弹出多个选项。在这里,无涯教程可以选择任何选项,它将保留在卡中,如第二幅图所示。

无涯教程网

Flutter ButtonsFlutter Buttons

Outline Button

它类似于Flat按钮,但包含一个细灰色的圆角矩形边框。它的轮廓边框由shape属性定义。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Outline Button Example'),
          ),
          body: Center(child: Column(children: [
            Container(
              margin: EdgeInsets.all(25),
              child: OutlineButton(
                child: Text("Outline Button", style: TextStyle(fontSize: 20.0),),
                highlightedBorderColor: Colors.red,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)),
                onPressed: () {},
              ),
            ),
            Container(
              margin: EdgeInsets.all(25),
              child: FlatButton(
                child: Text('Flat Button', style: TextStyle(fontSize: 20.0),),
                color: Colors.blueAccent,
                textColor: Colors.white,
                onPressed: () {},
              ),
            ),
          ]
          ))
      ),
    );
  }
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。

Flutter Buttons

Button Bar

Flutter提供了将按钮排列成条形或行形的灵活性。 ButtonBar小部件包含三个属性:alignment,children和mainAxisSize。

  • alignment         -  用于将对齐选项呈现给整个按钮栏小部件。
  • children            -  用于获取栏中的按钮数量。
  • mainAxisSize  - 用于为按钮栏提供水平空间。

示例:  打开 main.dart 文件并用以下代码替换它。

import 'package:flutter/material.dart';

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

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

class _State extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter ButtonBar Example'),
        ),
        body: Padding(
            padding: EdgeInsets.all(10),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(15),
                  child: new ButtonBar(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      RaisedButton(
                        child: new Text('Learnfk'),
                        color: Colors.lightGreen,
                          onPressed: () {/** */},
                      ),
                      FlatButton(
                        child: Text('Flutter'),
                        color: Colors.lightGreen,
                        onPressed: () {/** */},
                      ),
                      FlatButton(
                        child: Text('MySQL'),
                        color: Colors.lightGreen,
                        onPressed: () {/** */},
                      ),
                    ],
                  ),
                ),
              ],
            )
        )
    );
  }
}

在android模拟器中运行该应用程序,它将提供类似于以下屏幕截图的UI。在这里,无涯教程可以看到三个按钮放置在水平条或行中。

Flutter Buttons

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

正则表达式入门课 -〔涂伟忠〕

手机摄影 -〔@随你们去〕

数据分析思维课 -〔郭炜〕

攻克视频技术 -〔李江〕

搞定音频技术 -〔冯建元 〕

遗留系统现代化实战 -〔姚琪琳〕

零基础学Python(2023版) -〔尹会生〕

结构执行力 -〔李忠秋〕

云时代的JVM原理与实战 -〔康杨〕

好记忆不如烂笔头。留下您的足迹吧 :)