Home > Blockchain >  Flutter - Can't pass class field into child component
Flutter - Can't pass class field into child component

Time:11-04

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.

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?

CodePudding user response:

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,
        )
      )
    )
  );
}
  • Related