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

Flutter中'background'已弃用,如何修改代码解决该警告?

修复Flutter中background已废弃的警告

警告内容

'background' is deprecated and shouldn't be used. Use surface instead. This feature was deprecated after v3.18.0-0.1.pre.
Try replacing the use of the deprecated member with the replacement

原代码

import 'package:flutter/material.dart';

// light mode
ThemeData lightMode = ThemeData(
  brightness: Brightness.light,
  colorScheme: ColorScheme.light(
    background: Colors.grey.shade300,
    primary: Colors.grey.shade200,
    secondary: Colors.grey.shade400,
    inversePrimary: Colors.grey.shade800,
  )
);

修复方案

从Flutter v3.18.0-0.1.pre版本开始,ColorScheme中的background属性被废弃,官方推荐用surface替代,只需完成两处修改:

  1. 更新ThemeData里的ColorScheme定义
    把background替换为surface:
import 'package:flutter/material.dart';

// light mode
ThemeData lightMode = ThemeData(
  brightness: Brightness.light,
  colorScheme: ColorScheme.light(
    surface: Colors.grey.shade300, // 替换background为surface
    primary: Colors.grey.shade200,
    secondary: Colors.grey.shade400,
    inversePrimary: Colors.grey.shade800,
  )
);
  1. 修改调用该属性的代码
    将原来调用background的部分替换为surface:
backgroundColor: Theme.of(context).colorScheme.surface

修改完成后警告即可消除,surface的作用和原background完全一致,用于设置界面背景色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:50:56