Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter – Can't pass class field into child component

New to Flutter and I want to start making my app more dynamic. I’d like to start by passing data to my Text() widgets, but I am getting this weird null error and have NO idea why this is.

Currently I am doing this, where I pass in name and view it in the Text widget in the container:

class NameContainer extends StatelessWidget {
const NameContainer({ required this.name, Key? key}) : super(key : key);

final String name;

@override
Widget build(BuildContext context) {
  return Container(
    margin: const EdgeInsets.all(20.0),
    child: const Align(
      alignment: Alignment.center,
      child: Text(
        name,
        textAlign: 
        TextAlign.center, 
        style: const TextStyle(
          fontWeight: FontWeight.bold,
        )
      );
    )
  );
}

However its giving me a A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BUT, when I remove the Container and return just the Text like this:

class NameContainer extends StatelessWidget {
const NameContainer({ required this.name, Key? key}) : super(key : key);

final String name;

@override
Widget build(BuildContext context) {

  return Text(
    name,
    textAlign: 
    TextAlign.center, 
    style: const TextStyle(
      fontWeight: FontWeight.bold,
    )
  );
}

Its all good to go? I dont see the difference here… Can anyone share some insight on why this is?

>Solution :

You got the error because you used const keyword before Align widget and Align widget isn’t constructor type.

class NameContainer extends StatelessWidget {
 NameContainer({ required this.name, Key? key}) : super(key : key); // const remove from here 

final String name;

@override
Widget build(BuildContext context) {
  return Container(
    margin: const EdgeInsets.all(20.0),
    child:  Align( // here remove const
      alignment: Alignment.center,
      child: Text(
        name,
        textAlign: 
        TextAlign.center, 
        style: const TextStyle(
          fontWeight: FontWeight.bold,
        )
      )
    )
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading