首頁>科技>

本文核心要點

Theme Widget可以為Material APP 定義主題資料(ThemeData),Material元件庫裡很多Widget都使用了主題資料,如導航欄顏色、標題字型、Icon樣式等。Theme內會使用InheritedWidget來為其子樹Widget共享樣式資料。

main.dart檔案解說
import 'package:flutter/material.dart';void main() {  runApp(MaterialApp(    debugShowCheckedModeBanner: false,    home: MyHome(),    // Set the theme's primary color, accent color,    //這段程式碼是關鍵    theme: ThemeData(      primarySwatch: Colors.green,//設定顏色      accentColor: Colors.lightGreenAccent,//      // Set background color      backgroundColor: Colors.black12,    ),  ));}class MyHome extends StatelessWidget {  @override  Widget build(BuildContext context) {    return Scaffold(      // AppBar      appBar: AppBar(        // AppBar Title        title: Text("Using Theme"),      ),      body: Container(        // Another way to set the background color        decoration: BoxDecoration(color: Colors.black87),        child: Center(          child: Container(            // use the theme accent color as background color for this widget            color: Theme.of(context).accentColor,            child: Text(              'Hello World!',              // Set text style as per theme              style: Theme.of(context).textTheme.title,            ),          ),        ),      ),      floatingActionButton: Theme(        // override the accent color of theme for this widget only        data: Theme.of(context).copyWith(          colorScheme:              Theme.of(context).colorScheme.copyWith(secondary: Colors.pinkAccent),        ),        child: FloatingActionButton(          onPressed: null,          child: Icon(Icons.add),        ),      ),    );  }}
primarySwatch

flutter的主題(build下面的theme)中有個主題顏色(primarySwatch):

目前的主題顏色(primarySwatch)只有下面幾個值可以選擇,其他的暫不支援:

red,

pink,

purple,

deepPurple,

indigo,

blue,

lightBlue,

cyan,

teal,

green,

lightGreen,

lime,

yellow,

amber,

orange,

deepOrange,

brown,

blueGrey,

如果我要把主題色改成白色,或者黑色的話,用上面的就會報錯啦,因為在primarySwatch中的顏色是呼叫 MaterialColor這種顏色類,內部會有一個主色,一個map儲存固定的幾種主色周邊的顏色。

primaryColor:如果要把頂部導航欄和狀態列的顏色修改成黑色或者白色,需要用到這個屬性:

  • 整治雙十一購物亂象,國家再次出手!該跟這些套路說再見了
  • 心痛!小米 10 釋出會或推遲