尝试添加主色时,Flutter ThemeData 主色未从主题更改

EhC*_*COD 25 flutter flutter-theme

我在 LinkedIn Learning 上关注 London App Brewery 的 BMI 计算器应用程序。当尝试将 PrimaryColor 设置为红色时,即使我覆盖了 Primary Color,我的模拟器仍然显示浅蓝色默认 AppBar。这是代码

    import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.red,
      ),
      home: const InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  const InputPage({Key? key}) : super(key: key);

  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BMI CALCULATOR'),
      ),
      body: const Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const Icon(Icons.add),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 25

我也参加了 LondonAppBrewery 的相同培训。这段代码解决了这个问题。

Widget build(BuildContext context) {
return MaterialApp(
  title: "BMI Calculator",
  debugShowCheckedModeBanner: false,
  theme: ThemeData.dark().copyWith(
    appBarTheme:AppBarTheme(
      backgroundColor: Color(0xff0a0e21),
    ),
    scaffoldBackgroundColor: Color(0xff0a0e21),
  ),
  home: InputPage(),
);
Run Code Online (Sandbox Code Playgroud)


I_a*_*mer 22

使用主要Swatch

theme: ThemeData(
    primarySwatch: Colors.red,
  ),
Run Code Online (Sandbox Code Playgroud)


小智 15

这个问题已经在flutter github页面上指出了。他们说

我们最终会将所有组件从 ThemeData.primaryColor 中移走

所以你可以使用

 theme: ThemeData(
     colorScheme: ColorScheme.light().copyWith(primary: Colors.red),
 );
Run Code Online (Sandbox Code Playgroud)


Moh*_*him 5

使用以下方法,您可以完全控制 Themedata 中的各个属性

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.pink,
        appBarTheme: AppBarTheme(
          backgroundColor: Colors.orangeAccent,
        ),
      ),
      home: InputPage(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述