Before null-safety, I can pass widget, if check it is null, will show other widget. On null-safety environment, is there a way if I didn't pass widget image
or note
?
class Message extends StatelessWidget {
const Message({
Key key,
this.image,
this.title = "",
this.subtitle = "",
this.note,
this.onTap
}) : super(key: key);
final Widget image;
final String title;
final String subtitle;
final Widget note;
final Function onTap
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Column(
children:[
image ?? Container(),
if(note != null) note
]
)
);
}
};
You can declare your image and note as nullable types. If you need to make any of the field mandatory, you can mark it as required .
class Message extends StatelessWidget {
const Message({
Key? key,
this.image,
this.title = "",
this.subtitle = "",
this.note,
required this.onTap,
}) : super(key: key);
final Widget? image;
final String title;
final String subtitle;
final Widget? note;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Column(
children:[
image ?? Container(),
note ?? Container(),
]
)
);
}
}
Use ?
if the child can be null
.
class FooWidget extends StatelessWidget { final Widget? child; // <-- Nullable, use '?' FooWidget({ this.child, }); //... }
Use required
if the child can't be null
.
class FooWidget extends StatelessWidget { final Widget child; // <-- Non-nullable FooWidget({ required this.child, // <-- Use 'required' }); //... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.