Skip to content

[Flutter] 使用 TextButton 製作文字按鈕

在 Flutter 中有許多製作按鈕的方法,其中文字按鈕 TextButton 可說是最簡易的按鈕,適用於任何我們想要顯示文字、並讓使用者點擊後進一步展開其他功能的情況。


TextButton 使用方法

在本篇文章中不紀錄如何在點擊按鈕時呼叫函式,但基本上只要將你想要觸發的功能寫在 onPressed 後即可。

本篇文章主要紀錄該如何呈現 TextButton,示範禁用(Disable)與啟用(Enable)的按鈕呈現效果,並仿照官方教學列出漸層背景的效果。

漸層背景其實就只是使用 Stack 佈局將漸層的 Container 元件與 TextButton 元件疊在一起。關於 Stack 與漸層 Container 可以參考文末的連結。

以下是段範例程式碼,重點全在中間的三個 TextButton 元件。

import 'package:flutter/material.dart';


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


class MyApp extends StatelessWidget {
  String _title = "TextButton Demo";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: Text(_title)),
        body: MyTextButtonPage(),
      ),
    );
  }
}


class MyTextButtonPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Ceter
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          // TextButton_Disable
          TextButton(
            onPressed: null,
            child: Text("TextButton_Disable"),
          ),

          // TextButton_Enable
          TextButton(
            onPressed: () {},
            child: Text('TextButton_Enable')
          ),

          // TextButton_Style
          ClipRRect(
            // Put the TextButton on the Gradient Container
            child: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                // Container
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Colors.pink,
                          Colors.red,
                          Colors.orange,
                        ],
                      ),
                    ),
                  ),
                ),

                // TextButton_Gradient
                TextButton(
                  onPressed: () {},
                  child: Text('TextButton_Gradient'),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}


Output:

TextButton 很單純,很簡單就可以定製出來。


References


Read More

Tags:

Leave a Reply