是否可以在flutter中不需要传递参数
是否可以在没有必需的情况下传递 this.title ,我看过他们这样做的一些教程,但是当我尝试时,它要求我将必需添加到 this.title 。由于我的 2 屏幕不包含 appBar 标题,我想在不需要的情况下传递它。是否可以?
如果我将 required 添加到 this.title ,我的代码可以正常工作。
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../logic/cubit/counter_cubit.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key, this.title}) : super(key: key);
final String title;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
[SS of code][1]
is it possible to pass this.title without required, i have seen some tutorial they doing so, but when i try it asks me to add required to this.title. As my 2 screen doesn't contain appBar title i want to pass it without required. is it possible?
here my code works fine if i add required to this.title.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../logic/cubit/counter_cubit.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key, this.title}) : super(key: key);
final String title;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
[SS of code][1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标题必须是
必需
,因为您将其设置为不可可为空。如果标题是可选的,您可以将其设置为可为空:但是,现在您需要处理您的
build
函数中可能没有标题的事实:显然您没有不想“没有标题!?!”出现在你的标题中,但由于我不知道你想要什么,所以你必须更改该部分。
The title needs to be
required
because you made it not nullable. You can make it nullable if the title is optional:However, now you need to handle the fact that you may not have a title in your
build
function:Obviously you don't want "NO TITLE!?!" to be in your title, but since I don't know what you want instead, you will have to change that part.
除了@nvoigt给出的答案之外,您还可以提供一个默认值,而不是使
title
可以为空:这样,您就不必提供标题,如果您不提供,它将使用
主屏幕
作为标题。In addition to the answer given by @nvoigt, you can also supply a default value instead of making
title
nullable:This way, you don't have to supply a title, and if you don't, it will use
Home Screen
as the title instead.