Home > Software design >  Adding an explicit non- "null" default value to parameters in flutter
Adding an explicit non- "null" default value to parameters in flutter

Time:01-29

this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of dart/flutter

Developer Level: Beginner
Project type & language: I'm developing a Tasks App, using flutter.

THIS IS MY CODE FOR THE TASKS CARD (WIDGET)-

class TaskCardWidget extends StatelessWidget {

//const TaskCardWidget({ Key? key }) : super(key: key);

final String title;  
TaskCardWidget({this.title}); 

//  THE ERROR IS RETURNING HERE, IN THE LINE JUST ABOVE <<
//   ⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀⁀

  @override
  Widget build(BuildContext context) {
    return Container(
  
...
// I WANT IT TO WORK LIKE THIS - 
// if title comes null,
// it should change to "Unnamed Task" 

          Text(
            title ?? "(Unnamed Task)",
           //style: TextStyle(),
          ),
...

    );}}

PROBLEM/ERROR - The code is returning this error below.

The parameter 'title' can't have a value of 'null' because of its type, but the implicit default value is 'null'.

Try adding an explicit non- "null" default value ...

LIMITATION - The limitation of the App is, it might get null values for title.
If it happens, I want to simply change the title value to "(Unnamed task)".

HOW DO I GET THE CONSTRUCTOR TO ACCEPT THE 'title' VALUE AS IT IS
AND DEAL WITH 'null' VALUE LATER IN CODE

CodePudding user response:

change

final String title;

to

final String? title;
  •  Tags:  
  • Related