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

在Flutter中更改主题色为白色或黑色时遇到错误,因为`primarySwatch`需要`MaterialColor`而不是`Color`。Colors类中的blue等颜色是MaterialColor类型,而white和black则不是。解决方法是创建自定义的MaterialColor实例,如`const MaterialColor white = const MaterialColor(...)`。然后在`ThemeData`中使用这个自定义的MaterialColor。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



