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]
CodePudding user response:
The title needs to be required
because you made it not nullable. You can make it nullable if the title is optional:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key, this.title}) : super(key: key);
final String? title;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
However, now you need to handle the fact that you may not have a title in your build
function:
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title ?? "NO TITLE!?!"),
),
);
}
}
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.
CodePudding user response:
In addition to the answer given by @nvoigt, you can also supply a default value instead of making title
nullable:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key, this.title = 'Home Screen'}) : super(key: key);
final String title;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
This way, you don't have to supply a title, and if you don't, it will use Home Screen
as the title instead.