首页 > 解决方案 > 如何设置 Flutter OutlineButton 的背景颜色?

问题描述

class _HomePageState extends State<HomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("..."),
      ),
      body: Container(
        color: Colors.green,
        child: OutlineButton(
          onPressed: () { },
          color: Colors.orange,
          highlightColor: Colors.pink,
          child: Container(
            color: Colors.yellow,
            child: Text("A"),
          ),
          shape: CircleBorder(),
        ),
      ),
    );
  }
}

在此处输入图像描述

上面的代码给出了一个透明按钮。我怎样才能得到一个橙色的大纲按钮?

标签: flutter

解决方案


要修改OutlineButton的 backgroundColor,您可以使用DecoratedBoxTheme小部件。在这个答案的最后,你会找到一个简单的例子。

无论如何,我仍然建议简单地使用FlatButton及其color属性。

将您的OutlinedButton内部包裹起来DecoratedBox。将您的设置为shape与您DecoratedBox的相同的形状OutlinedButton。现在您可以使用您的color属性DecoratedBox来更改颜色。结果仍然会在OutlinedButton. 要删除它,您可以将DecoratedBox调整. 在你要设置的里面。ThemeButtonThemeButtonThemematerialTapTargetSize: MaterialTapTargetSize.shrinkWrap

在 Flutter 中添加了填充,以将按钮周围的点击区域增加到最小尺寸 48x48 (source)。设置materialTapTargetSizeMaterialTapTargetSize.shrinkWrap删除此最小尺寸。


FlatButton例子:

演示

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: FlatButton(
            color: Colors.pinkAccent,
            shape: CircleBorder(),
            onPressed: () => {},
            child: Text('A'),
          ),
        ),
      ),
    );
  }
}

OutlinedButton例子:

演示

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: MyButton(),
        ),
      ),
    );
  }
}

class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration:
          ShapeDecoration(shape: CircleBorder(), color: Colors.pinkAccent),
      child: Theme(
        data: Theme.of(context).copyWith(
            buttonTheme: ButtonTheme.of(context).copyWith(
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap)),
        child: OutlineButton(
          shape: CircleBorder(),
          child: Text('A'),
          onPressed: () => {},
        ),
      ),
    );
  }
}

推荐阅读