最近我遇到以下问题:我在 ListView 里面有一张卡片,我想通过设置颜色来为卡片设置主题,Theme.of(context).colorScheme.surfaceContainer
但现在的问题是,当我切换主题时,颜色不会刷新。
我在这里创建了此问题的最小可重现示例
import 'package:flutter/material.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
@override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
ThemeMode _themeMode = ThemeMode.light;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(),
darkTheme: ThemeData(brightness: Brightness.dark),
themeMode: _themeMode,
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Column(
spacing: 8,
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () {
setState(() {
_themeMode = _themeMode == ThemeMode.light
? ThemeMode.dark
: ThemeMode.light;
});
},
child: Text("Change Theme")),
Expanded(child: MyList())
],
)),
),
),
);
}
}
class MyList extends StatelessWidget {
const MyList({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return Card(
color: Theme.of(context).colorScheme.surfaceContainer,
child: ListTile(
title: Text('Item $index'),
),
);
});
}
}
当我打开应用程序时,一切看起来都符合预期:
现在我点击“更改主题”按钮,然后发生以下情况:
不确定这是我遗漏了什么还是 Flutter 框架的问题(不太可能)。
我尝试删除ListView
,并且仅Card
在小部件内部放一个 即可解决问题,但当然,对于我的真实应用程序,我需要将卡片放在 中ListView
。
还要注意,滚动时,如果卡片超出屏幕范围,然后将其滚动回屏幕,它会重新获取颜色并正确显示。
我想在 Flutter GitHub repo 上提出问题之前先在这里问一下。
重命名
context
ListView.builder 中的参数itemBuilder
以避免与构建方法的上下文冲突。