📜  Flutter – 为按钮分配动作

📅  最后修改于: 2021-09-02 05:33:36             🧑  作者: Mango

Flutter是 Google 的 UI 工具包,用于从单个代码库为移动、Web 和桌面构建漂亮的、本地编译的应用程序。 Flutter提供了许多预构建的小部件以供使用。 Flutter SDK 提供了不同类型的 Button 小部件。在本文中,我们将了解如何向它们添加操作。

以下是Flutter SDK 附带的一些按钮小部件:

  • 文本按钮
  • 升高按钮
  • 轮廓按钮
  • 图标按钮
  • 浮动操作按钮

使用onPressed()函数分配操作。我们将看到两种分配动作的方法。

Note: We are not going to use any other dependencies for this application.

方法一

使用函数引用。在这个方法中,我们将在别处定义一个函数,然后使用该函数的引用作为一个动作。

推荐使用此方法,因为您可以多次重复使用相同的函数。

Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: ButtonsExample(),
    );
  }
}
  
// list all the buttons
class ButtonsExample extends StatelessWidget {
  final GlobalKey scaffoldKey = GlobalKey();
  
  void textButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Text/ Flat Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
  
  void elevatedButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Elevated/ Raised Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
  
  void outlineButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Outline/ Outlined Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
  
  void iconButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Icon Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
  
  void floatingActionButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Floating Action Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
    
  // assign actions to 
  // all the listed buttons
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: scaffoldKey,
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: textButtonHandler,
                child: Text('Text Button'),
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                onPressed: textButtonHandler,
                child: Text('Flat Button'),
              ),
              ElevatedButton(
                onPressed: elevatedButtonHandler,
                child: Text('Elevated Button'),
              ),
              RaisedButton(
                onPressed: elevatedButtonHandler,
                child: Text('Raised Button'),
              ),
              OutlineButton(
                onPressed: outlineButtonHandler,
                child: Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: outlineButtonHandler,
                child: Text('Outlined Button'),
              ),
              IconButton(
                icon: Icon(Icons.star),
                onPressed: iconButtonHandler,
              ),
              FloatingActionButton.extended(
                onPressed: floatingActionButtonHandler,
                label: Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: ButtonsExample(),
    );
  }
}
  
 // list all the buttons &
  // assign actions to 
  // all the listed buttons
class ButtonsExample extends StatelessWidget {
  final GlobalKey scaffoldKey = GlobalKey();
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: scaffoldKey,
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Text Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Text Button'),
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Flat Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Flat Button'),
              ),
              ElevatedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Elevated Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Elevated Button'),
              ),
              RaisedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Raised Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Raised Button'),
              ),
              OutlineButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outline Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outlined Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outlined Button'),
              ),
              IconButton(
                icon: Icon(Icons.star),
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Icon Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Floating Action Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                label: Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


输出:

如果您需要将一些参数传递给函数,请使用以下方法:

onPressed: () => nameOfFunction(...args)

-- OR --

onPressed: () {
  nameOfFunction(...args);
}

方法二:

直接在使用 Button 小部件的地方定义函数,这种方法不太适合大型应用程序,因为这会降低应用程序的可读性并导致调试过程中出现问题,如果多次使用相同的函数,则必须重复代码,这也是不是很好的做法。

Dart

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: ButtonsExample(),
    );
  }
}
  
 // list all the buttons &
  // assign actions to 
  // all the listed buttons
class ButtonsExample extends StatelessWidget {
  final GlobalKey scaffoldKey = GlobalKey();
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: scaffoldKey,
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Text Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Text Button'),
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Flat Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Flat Button'),
              ),
              ElevatedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Elevated Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Elevated Button'),
              ),
              RaisedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Raised Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Raised Button'),
              ),
              OutlineButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outline Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outlined Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outlined Button'),
              ),
              IconButton(
                icon: Icon(Icons.star),
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Icon Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Floating Action Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                label: Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

输出