类型'Color'不是Flutter中'MaterialColor'类型错误的子类型?

Posted

技术标签:

【中文标题】类型\'Color\'不是Flutter中\'MaterialColor\'类型错误的子类型?【英文标题】:type 'Color' is not a subtype of type 'MaterialColor' error in Flutter?类型'Color'不是Flutter中'MaterialColor'类型错误的子类型? 【发布时间】:2021-07-13 12:05:39 【问题描述】:

**> ══╡ 小部件库发现异常

╞══════════════════════════════════════␕════════ ═════════════ 在构建 Builder 时抛出了以下 _TypeError:类型 'Color' 不是 “MaterialColor”类型的子类型

相关的导致错误的小部件是:MaterialApp file:///D:/FlutterExercise/FlutterExercise/07/spanishaudioplayer/lib/main.dart:9:12

当异常被抛出时,这是堆栈: #0 新 _HomePageState(包:spanishaudioplayer/HomePage.dart:22:35) #1 HomePage.createState (package:spanishaudioplayer/HomePage.dart:7:35) #2 新的 StatefulElement (package:flutter/src/widgets/framework.dart:4584:24) #3 StatefulWidget.createElement (package:flutter/src/widgets/framework.dart:916:38) ... 正常 元件安装(166 帧) #169 Element.inflateWidget(包:flutter/src/widgets/framework.dart:3541:14) #170 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6094:32) ... 正常 元件安装(300 帧) #470 Element.inflateWidget(包:flutter/src/widgets/framework.dart:3541:14) #471 Element.updateChild (包:flutter/src/widgets/framework.dart:3306:18) #472 RenderObjectToWidgetElement._rebuild(包:flutter/src/widgets/binding.dart:1182:16) #473 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1153:5) #474 RenderObjectToWidgetAdapter.attachToRenderTree。 (包:flutter/src/widgets/binding.dart:1095:18) #475 BuildOwner.buildScope(包:flutter/src/widgets/framework.dart:2647:19) #476 RenderObjectToWidgetAdapter.attachToRenderTree(包:flutter/src/widgets/binding.dart:1094:13) #477 WidgetsBinding.attachRootWidget(包:flutter/src/widgets/binding.dart:934:7) #478 WidgetsBinding.scheduleAttachRootWidget。 (package:flutter/src/widgets/binding.dart:915:7) (省略11帧 来自 _RawReceivePortImpl 类、_Timer 类、dart:async 和 飞镖:异步补丁)

════════════════════════════════════════════════ ══════════════════════════════════════════════════ ═══ W/InputMethodManager(14486): startInputReason = 8 W/IInputConnectionWrapper(14486):getExtractedText 处于非活动状态 InputConnection W/IInputConnectionWrapper(14486):getTextBeforeCursor 在非活动 InputConnection V/ActivityThread(14486) 上:完成停止 ActivityRecord801579c token=android.os.BinderProxy@63e470c com.example.spanishaudioplayer/com.example.spanishaudioplayer.MainActivity W/libEGL (14486):EGLNativeWindowType 0x76efee7010 断开连接失败 W/libEGL (14486):EGLNativeWindowType 0x7713667010 断开连接失败 V/ActivityThread(14486):句柄窗口 ActivityRecord801579c 令牌=android.os.BinderProxy@63e470c com.example.spanishaudioplayer/com.example.spanishaudioplayer.MainActivity 可见性:假**

/////////////////////////////////////// ///////////////////////////////////////// //// //main.dart

import 'package:flutter/material.dart';
import 'HomePage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget 
    @override
    Widget build(BuildContext context) 
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Spanish Audio Numbers',
        theme: ThemeData(
          primarySwatch: Colors.teal,
        ),
        home: HomePage(),
      );
    
  

/////////////////////////////////////////////////////////////////////////////////////////////////////
//HomePage.dart

import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'NumberAudio.dart';

class HomePage extends StatefulWidget 
    @override
    _HomePageState createState() => _HomePageState();
  

class _HomePageState extends State<HomePage> 
    AudioCache audioPlayer = AudioCache();
    List<NumberAudio> audioList = [
      NumberAudio("one.wav", Colors.red, "one"),
      NumberAudio("two.wav", Colors.blue, "two"),
      NumberAudio("three.wav", Colors.pink, "three"),
      NumberAudio("four.wav", Colors.orange, "four"),
      NumberAudio("five.wav", Colors.purple, "five"),
      NumberAudio("six.wav", Colors.cyan, "six"),
      NumberAudio("seven.wav", Colors.green, "seven"),
      NumberAudio("eight.wav", Colors.grey, "eight"),
      NumberAudio("nine.wav", Colors.yellow, "nine"),
      NumberAudio("ten.wav", Colors.black, "ten"),
    ];
    play(String audioFile) async 
      audioPlayer.play(audioFile);
    

    @override
    Widget build(BuildContext context) 
      return Scaffold(
        appBar: AppBar(
          title: Text(
            'Spanish Numbers',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.0,
              fontWeight: FontWeight.bold,
            ),
          ),
          //backgroundColor: Colors.teal,
        ),
        body: Center(
          child: Column(
            children: [
              Image(
                image: AssetImage("images/logo.png"),
              ),
              Expanded(
                child: GridView.builder(
                  padding: EdgeInsets.all(10.0),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    childAspectRatio: 1.0,
                    crossAxisCount: 2,
                    crossAxisSpacing: 5.0,
                    mainAxisSpacing: 5.0,
                  ),
                  itemCount: audioList.length,
                  itemBuilder: (context, index) => SizedBox(
                    height: 50.0,
                    width: 100.0,
                    child: RaisedButton(
                      child: Text(
                        audioList[index].buttonTitle,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      color: audioList[index].buttonColor,
                      onPressed: () 
                        play(audioList[index].audioFile);
                      ,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    


/////////////////////////////////////////////////////////////////////////////////////////////////////
//NumberAudio.dart

import 'package:flutter/material.dart';

class NumberAudio 
    String audioFile;
    MaterialColor buttonColor;
    String buttonTitle;
    NumberAudio(String audioFile, MaterialColor buttonColor, String buttonTitle) 
      this.audioFile = audioFile;
      this.buttonColor = buttonColor;
      this.buttonTitle = buttonTitle;
    

https://i.stack.imgur.com/LGfKS.png

【问题讨论】:

【参考方案1】:

Color 不是MaterialColor 的子类型。

theme: ThemeData(
  primarySwatch: Colors.teal,
),

这里primarySwatch 的类型为MaterialColor,但您输入的Colors.teal 的类型为Color

如果您想创建MaterialColor 的实例,请尝试以下操作:

static const MaterialColor colorPrimarySwatch = 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),
,

);

不要忘记将 buttonColor 类型从 MaterialColor 更改为 Color

class NumberAudio 
    String audioFile;
    Color buttonColor;
    String buttonTitle;

    NumberAudio(String audioFile, Color buttonColor, String buttonTitle) 
      this.audioFile = audioFile;
      this.buttonColor = buttonColor;
      this.buttonTitle = buttonTitle;
    

【讨论】:

以上是关于类型'Color'不是Flutter中'MaterialColor'类型错误的子类型?的主要内容,如果未能解决你的问题,请参考以下文章

Flutter null 安全性 - 参数类型“颜色?”不能分配给参数类型“颜色”

Flutter:类型“bool”不是类型转换中“RxBool”类型的子类型

Flutter 移动设备图像屏幕变大

“String”类型不是 Flutter 中“Item”类型的子类型

Flutter [错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:类型“int”不是类型转换中“String”类型的子类型

Flutter:小部件不是“ObstructingPreferredSizeWidget”类型的子类型