Flutter抽离AppBar为独立组件复用及Text非空报错问题
自定义AppBar组件抽离实现的问题与修正
原始需求
将页面内耦合的AppBar逻辑抽离为独立可复用组件,提升代码可读性与可维护性,预期调用方式为在页面Scaffold的appBar位置传入自定义组件实例。
抽离前的初始草稿代码:
class thisappbar extends StatelessWidget { thisappbar(this.isMe, this.username, {this.key}); final Key key; final bool isMe; String username; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0, automaticallyImplyLeading: false, backgroundColor: Colors.white, flexibleSpace: SafeArea( child: Container( padding: EdgeInsets.only(right: 16), child: Row( children: <Widget>[ IconButton( onPressed: (){ Navigator.pop(context); }, // 原代码截断部分
最初预期的页面调用方式:
class ChatScreen extends StatelessWidget { static const route = '/messages'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(thisappbar(),), body: Container( child: Column( children: <Widget>[ Expanded(child: Messages()), NewMessage(), ], )), ); } }
参考社区建议后的修改版本
参考实现PreferredSizeWidget接口的规范,将自定义类调整为可作为Scaffold.appBar入参的形式,修改后的自定义AppBar代码:
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { CustomAppBar({this.key, this.isMe, this.username}) : super(key: key); final Key key; final bool isMe; String username; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0, automaticallyImplyLeading: false, backgroundColor: Colors.white, flexibleSpace: SafeArea( child: Container( padding: EdgeInsets.only(right: 16), child: Row( children: <Widget>[ IconButton( onPressed: () { Navigator.pop(context); }, icon: Icon(Icons.arrow_back, color: Colors.black,), ), SizedBox(width: 2,), CircleAvatar( backgroundImage: NetworkImage( 'https://randomuser.me/api/portraits/men/5.jpg'), maxRadius: 20, ), SizedBox(width: 12,), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( username, style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600),), SizedBox(height: 6,), Text("Online", style: TextStyle( color: Colors.grey.shade600, fontSize: 13),), ], ), ), Icon(Icons.settings, color: Colors.black54,), ], ), ), ), ), ); } @override Size get preferredSize => Size.fromHeight(56); }
对应的页面调用代码:
class ChatScreen extends StatelessWidget { static const route = '/messages'; @override Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar(), body: Container( child: Column( children: <Widget>[ Expanded(child: Messages()), NewMessage(), ], )), ); } }
运行时异常
程序执行后抛出组件构建错误:
======== Exception caught by widgets library ======================================================= The following assertion was thrown building CustomAppBar(dirty): A non-null String must be provided to a Text widget. 'package:flutter/src/widgets/text.dart': Failed assertion: line 378 pos 10: 'data != null' The relevant error-causing widget was: CustomAppBar file:///Users/name/StudioProjects/project/lib/seitenleiste/nachrichten.dart:390:15 When the exception was thrown, this was the stack: #2 new Text (package:flutter/src/widgets/text.dart:378:10) #3 CustomAppBar.build (package:project/seitenleiste/nachrichten.dart:357:23) #4 StatelessElement.build (package:flutter/src/widgets/framework.dart:4646:28) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4572:15) #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4265:5) ...
核心错误点
- 多余组件嵌套:自定义AppBar的build方法中额外嵌套了一层
Scaffold,该组件本身就是作为外层页面Scaffold的appBar参数存在的,无需重复嵌套Scaffold容器。 - 参数传值缺失:实例化
CustomAppBar时没有传入username参数,该字段默认值为null,直接赋值给Text组件时触发非空校验失败。
修正后的可用代码
首先调整自定义AppBar组件,移除嵌套的Scaffold,将必填参数设置为非空类型,从构造函数层面避免null值传入:
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { const CustomAppBar({ super.key, required this.isMe, required this.username, }); final bool isMe; final String username; @override Widget build(BuildContext context) { return AppBar( elevation: 0, automaticallyImplyLeading: false, backgroundColor: Colors.white, flexibleSpace: SafeArea( child: Container( padding: const EdgeInsets.only(right: 16), child: Row( children: <Widget>[ IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back, color: Colors.black,), ), const SizedBox(width: 2,), const CircleAvatar( backgroundImage: NetworkImage( 'https://randomuser.me/api/portraits/men/5.jpg'), maxRadius: 20, ), const SizedBox(width: 12,), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( username, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.w600 ), ), const SizedBox(height: 6,), const Text( "Online", style: TextStyle( color: Colors.grey, fontSize: 13 ), ), ], ), ), const Icon(Icons.settings, color: Colors.black54,), ], ), ), ), ); } @override Size get preferredSize => const Size.fromHeight(56); }
页面调用时传入对应的业务参数即可:
class ChatScreen extends StatelessWidget { const ChatScreen({super.key}); static const route = '/messages'; @override Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar( isMe: false, username: "测试用户", ), body: Container( child: const Column( children: <Widget>[ Expanded(child: Messages()), NewMessage(), ], )), ); } }
内容的提问来源于stack exchange,提问作者user15368588
相关产品推荐
相关产品推荐

