Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘MaterialColor‘

在Flutter中更改主题色为白色或黑色时遇到错误,因为`primarySwatch`需要`MaterialColor`而不是`Color`。Colors类中的blue等颜色是MaterialColor类型,而white和black则不是。解决方法是创建自定义的MaterialColor实例,如`const MaterialColor white = const MaterialColor(...)`。然后在`ThemeData`中使用这个自定义的MaterialColor。
class MyApp extends StatelessWidget {
   
   
  @override
  Widget build(BuildContext context) {
   
   
    return MaterialApp(
      title: 'Futter App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
      	//更改主题色为白色
        primarySwatch: Colors.white,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashPage(),
    );
  }
}

在Flutter中,如果我们把默认主题色更改为白色(Colors.white)或黑色(Colors.black),会发生以下错误:

	I/flutter ( 6397): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY╞═══════════════════════════════════════════════════════════
    I/flutter ( 6397): The following assertion was thrown attaching to the render tree:
    I/flutter ( 6397): type 'Color' is not a subtype of type 'MaterialColor'
    I/flutter ( 6397): Either the assertion indicates an error in the framework itself, or we should provide 
    substantially
    I/flutter ( 6397): more information in this error message to help you determine and fix the underlying cause.
    I/flutter ( 6397): In either case, please report this assertion by filing a bug on GitHub:
    I/flutter ( 6397):   https://github.com/flutter/flutter/issues/new

原因

查看错误提示,说的是Color不是MaterialColor的子类,打开ThemeData的源码发现,primarySwatch是一个MaterialColor类型的变量,而MaterialColor继承自ColorSwatch。
源码如下

/// A color that has a small table of related colors called a "swatch".
///
/// The table is indexed by values of type `T`.
///
/// See also:
///
///  * [MaterialColor] and [MaterialAccentColor], which define material design
///    primary and accent color swatches.
///  * [material.Colors], which defines all of the standard material design
///    colors.
@immutable
class ColorSwatch<T&g
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值