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

Flutter:如何修改Stateful/StatelessWidget中的文本颜色?

解决Flutter中MyHomePage标题颜色修改问题

两种修改方式,按需选择:


方式一:在MyHomePage内部(State类)单独修改

MyHomePage的标题最终会在对应的_MyHomePageState组件中显示,直接在这里设置样式最直观,补全你的State代码即可:

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 设置页面背景为黑色
      backgroundColor: Colors.black,
      appBar: AppBar(
        // 设置AppBar背景为黑色
        backgroundColor: Colors.black,
        // 给标题文本设置白色样式
        title: Text(
          widget.title,
          style: const TextStyle(color: Colors.white),
        ),
      ),
      body: const Center(
        // 页面内其他文本也按需设置白色
        child: Text(
          '页面内容',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}

方式二:全局Theme统一修改(外部,在MyApp中配置)

如果希望整个App的标题、文本都统一白色+黑色背景,可以在ThemeData里全局配置,无需每个页面单独设置:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.black,
        // 配置AppBar全局样式
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.black,
          titleTextStyle: TextStyle(
            color: Colors.white,
            fontSize: 20, // 可选:调整字体大小
            fontWeight: FontWeight.w500, // 可选:调整字体粗细
          ),
        ),
        // 配置全局文本默认样式
        textTheme: const TextTheme(
          bodyLarge: TextStyle(color: Colors.white),
          bodyMedium: TextStyle(color: Colors.white),
        ),
      ),
      home: const MyHomePage(title: 'This is my app now! Mwuah Ha Ha!'),
    );
  }
}

两种方式的区别:

  • 内部修改:仅对当前MyHomePage生效,灵活可控,适合单页面样式调整。
  • 全局修改:整个App的对应组件都会应用该样式,适合统一App风格的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:40:41