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

Flutter父组件自定义Theme颜色无法传递至showGeneralDialog子组件问题

最小可复现代码

void main() => runApp(MaterialApp(home: FooPage()));

class FooPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Theme(
        data: ThemeData(textTheme: TextTheme(bodyText2: TextStyle(color: Color(0xFF123456)))),
        child: Builder(
          builder: (context) => ElevatedButton(
            child: Text('Button'),
            onPressed: () => Bar.show(context), // Passing new context which has 123456 color
          ),
        ),
      ),
    );
  }
}

class Bar {
  static void show(BuildContext context) {
    print('color1: ${Theme.of(context).textTheme.bodyText2?.color}'); // This is 123456 color

    showGeneralDialog(
      context: context,
      pageBuilder: (context, _, __) {
        print('color2: ${Theme.of(context).textTheme.bodyText2?.color}'); // But this is not
        return FlutterLogo();
      },
    );
  }
}

不符合预期的根本原因

  • Flutter 中所有通过showDialog、showGeneralDialog等方法弹出的弹窗,本质都是挂载在全局Overlay节点下的子组件,而这个全局Overlay是MaterialApp/WidgetsApp的直属子节点,和你在FooPage中嵌套的自定义Theme子树属于不同的Widget分支,不存在继承关系。
  • 你传入Bar.show的context是自定义Theme子树内部的context,沿着该context向上查找Theme时,会命中你自定义的Theme配置,因此color1打印结果符合预期。
  • pageBuilder回调返回的context是弹窗自身所在的Overlay子树的context,沿着这个context向上查找Theme时,只会沿着Overlay所在的树向上遍历到MaterialApp的默认Theme,不会访问到你在FooPage局部嵌套的自定义Theme,因此color2无法拿到预期的颜色值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:15:10