Flutter自定义Stateful组件如何接收Text类型参数并在Container中使用
实现方案
先修正现有代码的两处问题
- 不要在StatefulWidget中缓存State实例,Flutter框架会自动管理State的生命周期,手动存储会引发状态复用、更新异常的问题
- State类中可以通过
widget.参数名的方式访问父组件传入的公共参数
修改后的完整可运行代码
class TopBar extends StatefulWidget { final Text text; // 若text为必填参数可添加required标注 const TopBar({ Key? key, required this.text, }) : super(key: key); @override _TopBarState createState() => _TopBarState(); } class _TopBarState extends State<TopBar> { @override Widget build(BuildContext context) { return Align( child: Container( child: Row( children: [ // 直接通过widget.text引用传入的Text组件即可 widget.text, // 可在此处添加其他TopBar元素,比如返回按钮、操作图标等 ], ), ), ); } }
组件使用示例
// 页面中调用TopBar时直接传入Text组件即可 Scaffold( appBar: PreferredSize( preferredSize: Size.fromHeight(44), child: TopBar( text: Text("首页标题", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ), ), body: const SizedBox(), )
扩展建议
如果后续需要更灵活的配置标题样式,也可以直接传字符串参数而非Text组件,在TopBar内部统一管理标题的字体大小、颜色等样式,避免每个调用处重复写样式:
class TopBar extends StatefulWidget { final String title; final TextStyle? titleStyle; const TopBar({ Key? key, required this.title, this.titleStyle, }) : super(key: key); @override _TopBarState createState() => _TopBarState(); } // State的build方法里使用时: Text(widget.title, style: widget.titleStyle ?? const TextStyle(fontSize: 16, color: Colors.black))
内容的提问来源于stack exchange,提问作者user11856923
相关产品推荐
相关产品推荐

