Flutter如何改变FloatingActionButton中子元素图标的颜色

16

我刚接触Flutter,想要改变FloatingActionButton中的子图标颜色,默认为白色。

我该怎么做呢?

以下是我所写的代码。

floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
        backgroundColor: Colors.yellow,

      ), // This trailing comma makes auto-formatting nicer for build methods.
    ); 

谢谢。

4个回答

35

你可以使用 IconTheme 包裹它

child: new IconTheme(
    data: new IconThemeData(
        color: Colors.yellow), 
    child: new Icon(Icons.add),
),

或者使用Theme,其中iconTheme按您想要的方式设置

(未经测试)


19

要更改子图标的颜色,您需要在Icon()小部件中设置颜色。

这里我分享一个代码片段,我已经设置了红色。

floatingActionButton: FloatingActionButton(
        tooltip: 'Increment',
        child: new Icon(Icons.add, color: Colors.red,),
        backgroundColor: Colors.yellow,
      ),

谢谢,兄弟,它起作用了。接受Günter Zöchbauer的答案,因为他先回答了。 - Sachin Varma
1
没有问题,一点都不 :) - Dhrumil Shah - dhuma1981
抬头,@DhrumilShah-dhuma1981 - Piyush Kumar

4

Flutter v17.4

如果你只想更改图标的颜色,可以采用以下方法:

floatingActionButton: FloatingActionButton(
    child: Icon(Icons.add,
      color: Colors.black, //The color which you want set.
    ),
    onPressed: () => {},
  ),

1

MaterialApp主题:ThemeData

如果在您的MaterialApp中使用ThemeData来为您的应用程序着色,如下所示:

    return MaterialApp(
        title: 'Flutter Demo',
        theme: lightThemeData, // this guy
        darkTheme: darkThemeData, // and perhaps this guy
        home: MyHomePage()
    );

你可以用以下两种方式之一在ThemeData中设置FloatingActionButton(FAB)图标的颜色:
  1. floatingActionButtonTheme: const FloatingActionButtonThemeData(foregroundColor: myColor)
  2. onSecondary: myColor(仅当↑↑↑缺失时使用)
final lightThemeData = ThemeData.from(
    colorScheme: ColorScheme.fromSeed(
      seedColor: Colors.blue,
      brightness: Brightness.light,
      primary: blue,
      secondary: blue,
      onSecondary: white, // FAB Icon color if FABTheme not provided like below
    ),
).copyWith(
  floatingActionButtonTheme: const FloatingActionButtonThemeData(foregroundColor: Colors.green), // this guy works
  iconTheme: const IconThemeData(color: white), // DOES NOT affect FAB Icon
  accentIconTheme: const IconThemeData(color: purpleRain), // argumentFormerlyKnownAsFabIconColor - deprecated, DON'T USE THIS
);

在上面的themeData示例中,FAB图标将被着色为绿色
因为onSecondary用于仅在缺少floatingActionButtonTheme时对FAB图标进行着色。
如果没有提供上述主题颜色,则FAB图标将回退到黑色。 iconThemeaccentIconTheme 都不会影响 FAB图标颜色。
FAB accentIconTheme在Flutter 1.17中发生了变化

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接