Home > Back-end >  Flutter Class Properties (basics)
Flutter Class Properties (basics)

Time:10-23

How do you pass properties to a widget class in flutter.

Here is a basic class

class ToolbarToggle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return Text(label);
}}

I want to be able to call it

ToolbarToggle(label: 'a label')

Forgive the elementary question.

CodePudding user response:

class ToolbarToggle extends StatelessWidget {
  
  final String? label;
  
  const ToolbarToggle({this.label, Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Text(label ?? 'label is null');
  }}

Like this, you can pass properties, Its recommended to use const constructor and a key param ( to uniquely identify incase)

CodePudding user response:

First you declare a label property, like this:

class ToolbarToggle extends StatelessWidget {
  final String label;

  @override
  Widget build(BuildContext context) {
    return Text(label);
  }
}

final means the value is immutable, you should add it to every property on a StatelessWidget.

Now we need to declare a Constructor, here is how we do that:

ToolbarToggle(this.label);

This means that when creating a ToolbarToggle, we can do this: ToolbarToggle('some label');. In order to make parameters named, we need to declare the constructor like so:

ToolbarToggle({this.label});

Now it is possible to call ToolbarToggle(label: 'my label');. But this will give an error, because it's possible you don't actually pass any value when calling the constructor. To fix this, you should either make it a required parameter, or give it a default value:

ToolbarToggle({required this.label});
ToolbarToggle({this.label=''});

Here is the final class code:

class ToolbarToggle extends StatelessWidget {
  ToolbarToggle({required this.label});

  final String label;

  @override
  Widget build(BuildContext context) {
    return Text(label);
  }
}

CodePudding user response:

You missed using the label

class ToolbarToggle extends StatelessWidget {
  final String label;
  ToolbarToggle({required this.label});
  @override
  Widget build(BuildContext context) {
   return Text(label);
}}
  • Related