Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘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 extends Color {
  /// Creates a color that has a small table of related colors called a "swatch".
  ///
  /// The `primary` argument should be the 32 bit ARGB value of one of the
  /// values in the swatch, as would be passed to the [new Color] constructor
  /// for that same color, and as is exposed by [value]. (This is distinct from
  /// the specific index of the color in the swatch.)
  const ColorSwatch(int primary, this._swatch) : super(primary);

  @protected
  final Map _swatch;

  /// Returns an element of the swatch table.
  Color? operator [](T index) => _swatch[index];

  @override
  bool operator ==(Object other) {
    if (identical(this, other))
      return true;
    if (other.runtimeType != runtimeType)
      return false;
    return super == other
        && other is ColorSwatch
        && mapEquals(other._swatch, _swatch);
  }

  @override
  int get hashCode => hashValues(runtimeType, value, _swatch);

  @override
  String toString() => '${objectRuntimeType(this, 'ColorSwatch')}(primary value: ${super.toString()})';
}

为什么Colors.blue或者其它颜色可以使用呢?
查看Colors的源码发现,white和black其它颜色都是MaterialColor类型。

  static const Color black = Color(0xFF000000);
  static const Color white = Color(0xFFFFFFFF);
  static const MaterialColor blue = MaterialColor(
    _bluePrimaryValue,
    <int, Color>{
       50: Color(0xFFE3F2FD),
      100: Color(0xFFBBDEFB),
      200: Color(0xFF90CAF9),
      300: Color(0xFF64B5F6),
      400: Color(0xFF42A5F5),
      500: Color(_bluePrimaryValue),
      600: Color(0xFF1E88E5),
      700: Color(0xFF1976D2),
      800: Color(0xFF1565C0),
      900: Color(0xFF0D47A1),
    },
  );

解决方法

到这里我们知道了,必须传入一个MaterialColor类型的变量才行,既然Flutter没有提供,那我们自己模仿创建一个即可。

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

const MaterialColor white = const MaterialColor(
  0xFFFFFFFF,
  const <int, Color>{
    50: const Color(0xFFFFFFFF),
    100: const Color(0xFFFFFFFF),
    200: const Color(0xFFFFFFFF),
    300: const Color(0xFFFFFFFF),
    400: const Color(0xFFFFFFFF),
    500: const Color(0xFFFFFFFF),
    600: const Color(0xFFFFFFFF),
    700: const Color(0xFFFFFFFF),
    800: const Color(0xFFFFFFFF),
    900: const Color(0xFFFFFFFF),
  },
);
const MaterialColor black = const MaterialColor(
  0xFFFFFFFF,
  const <int, Color>{
    50: const Color(0xFF000000),
    100: const Color(0xFF000000),
    200: const Color(0xFF000000),
    300: const Color(0xFF000000),
    400: const Color(0xFF000000),
    500: const Color(0xFF000000),
    600: const Color(0xFF000000),
    700: const Color(0xFF000000),
    800: const Color(0xFF000000),
    900: const Color(0xFF000000),
  },
);

class MyApp extends StatelessWidget {
  MyApp() {
    final router = FluroRouter();
    Routes.configureRoutes(router);
    Application.router = router;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: white,
      ),
      home: SplashPage(),
    );
  }
}

你可能感兴趣的:(Flutter踩坑集合,Flutter,dart,MaterialColor,ColorSwatch)