MaterialApp 中的主题在小部件 Flutter 中不起作用

Apo*_*dey 4 flutter flutter-web

这是我的代码,我明确定义了主题,如下所示。但是,Chrome 浏览器中容器的颜色home仍然是蓝色。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Spotify UI',
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.dark,
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        appBarTheme: const AppBarTheme(backgroundColor: Colors.black),
        scaffoldBackgroundColor: const Color(0xFF121212),
        backgroundColor: const Color(0xFF121212),
        primaryColor: Colors.black,
        accentColor: const Color(0xFF1DB954),
        iconTheme: const IconThemeData().copyWith(color: Colors.white),
        fontFamily: 'Montserrat',
        textTheme: TextTheme(
          headline2: const TextStyle(
            color: Colors.white,
            fontSize: 32.0,
            fontWeight: FontWeight.bold,
          ),
          headline4: TextStyle(
            fontSize: 12.0,
            color: Colors.grey[300],
            fontWeight: FontWeight.w500,
            letterSpacing: 2.0,
          ),
          bodyText1: TextStyle(
            color: Colors.grey[300],
            fontSize: 14.0,
            fontWeight: FontWeight.w600,
            letterSpacing: 1.0,
          ),
          bodyText2: TextStyle(
            color: Colors.grey[300],
            letterSpacing: 1.0,
          ),
        ),
      ),
      home: Column(
        children: [
          Expanded(
            child: Container(
              color: Theme.of(context).primaryColor,
            ),
          )
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Gio*_*gio 5

这是因为您的小部件的颜色Container取自,它是方法context的参数。buildMyApp

MaterialApp有主题,但MyApp没有主题。因此,当您使用contextofMyApp获取主色时,该上下文还没有任何主题,并且您将获得默认的主色。

相反,你可以做的是:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Spotify UI',
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.dark,
      darkTheme: ThemeData(
        // ...
      ),
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Container(
            color: Theme.of(context).primaryColor,
          ),
        )
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)