You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Theme分离到独立Dart文件时出现‘Invalid constant value’错误求助

解决Flutter中ThemeData引用的"Invalid constant value"错误

错误原因

你在const MaterialApp中引用了非const的selfmadeTheme变量,Flutter要求const上下文里的所有参数必须是编译时常量;同时你的selfmadeTheme里的ScrollbarThemeData未使用const构造,导致整个ThemeData无法被标记为const,最终触发错误。

解决方法

方法一:将selfmadeTheme设为常量(推荐)

修改selfmade_basic_interface.dart代码,给ScrollbarThemeData添加const构造,同时将selfmadeTheme声明为const:

import 'package:flutter/material.dart';

const ThemeData selfmadeTheme = ThemeData(
  primarySwatch: const MaterialColor(
    0xff424242,
    {
      50: Color(0xfffafafa),
      100: Color(0xfff5f5f5),
      200: Color(0xffeeeeee),
      300: Color(0xffe0e0e0),
      350: Color(0xffd6d6d6),
      400: Color(0xffbdbdbd),
      500: Color(0xff9e9e9e),
      600: Color(0xff757575),
      700: Color(0xff616161),
      800: Color(0xff424242),
      850: Color(0xff303030),
      900: Color(0xff212121)
    },
  ),
  scaffoldBackgroundColor: const Color(0xff303030),
  drawerTheme: const DrawerThemeData(
    backgroundColor: Color(0xff424242),
  ),
  listTileTheme: const ListTileThemeData(
    textColor: Colors.white,
    iconColor: Colors.white,
  ),
  textTheme: const TextTheme(
    bodySmall: TextStyle(
      color: Colors.white,
    ),
    bodyMedium: TextStyle(
      color: Colors.white,
    ),
  ),
  scrollbarTheme: const ScrollbarThemeData(
    thumbColor: MaterialStateProperty.all(Colors.grey),
    thumbVisibility: MaterialStateProperty.all<bool>(true),
  ),
);

修改后selfmadeTheme成为编译时常量,main.dart里的const MaterialApp就能正常引用它,同时const组件还能提升性能,减少不必要的Widget重建。

方法二:移除MaterialApp的const修饰

如果不需要MaterialApp作为const组件,直接去掉它前面的const即可:

@override
Widget build(BuildContext context) {
  return MaterialApp( // 移除const修饰
    theme: selfmadeTheme,
    home: const Scaffold(
      body: SizedBox(),
    ),
  );
}

内容的提问来源于stack exchange,提问作者Yubin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:07:01