Home Articles

如何为屏幕设置不同的主题?

Asked
Viewed 765 times
3

我创建了Friendly Chat app并希望添加一个具有不同主题的新屏幕,但它不起作用:-(

整个应用程序有一个 Brightness.dark 主题:

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

class MyApp extends StatelessWidget {

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    print("build MaterialApp");
    return new MaterialApp(
      title: 'Friendly Chat',
      theme: kTheme,
      home: new ChatScreen(),
      routes: <String, WidgetBuilder>{
        SettingsScreen.PATH: (BuildContext context) => new SettingsScreen()
      },
    );
  }
}

final ThemeData kTheme = new ThemeData(
  primarySwatch: Colors.indigo,
  primaryColor: Colors.indigoAccent[100],
  primaryColorBrightness: Brightness.dark,
);

当用户单击按钮时,我按下设置屏幕:

Map results = await Navigator.of(context).pushNamed(SettingsScreen.PATH);

在设置屏幕中,我更改 AppBarbackgroundColorbrightness 但新的/不同的 brightness 无效(更改 backgroundColor 工作)

class SettingsScreen extends StatefulWidget {

  @override
  State createState() => new SettingsScreenState();
}

class SettingsScreenState extends State<SettingsScreen> {

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      onWillPop: _onWillPop,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text("Settings"),
          backgroundColor: Colors.amberAccent[700],
          brightness: Brightness.light,
        ),
      ),
    );
  }
}

如何将设置屏幕AppBar主题更改为轻量级主题?

EDIT

最后我想要:

  • 所有屏幕都有一个黑色的AppBar背景色,带有白色 Headers 和图标

  • 设置屏幕(仅)具有浅色的AppBar背景颜色,带有黑色 Headers 和图标

Bonus points: 如何为整个屏幕设置不同的主题,而不仅仅是AppBar

1 Answer

  • 4

    您可以通过在Theme小部件中包装所需的小部件来覆盖当前主题

    通常你会有类似的东西:

    class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
      final AppBar appBar;
    
      CustomAppBar(): appBar = new AppBar();
    
      @override
      Widget build(BuildContext context) {
        return new Theme(
          child: appBar,
          data: new ThemeData.dark()
        );
      }
    
      @override
      Size get preferredSize => appBar.preferredSize;
    }
    

    必须创建一个自定义类,因为 Scaffold 需要 PreferredSizeWidget .

    EDIT

    要回答你的“奖励点”,这很简单 .

    而不是将 AppBar 包裹在 Theme 中,而是包裹 Scaffold .

Related