0
votes

I am calling a class (Titletext) that returns a row and while it works in my emulator the editor is giving me a warning so I am trying to figure out the proper way to handle this as the editor is displaying a warning.

I tried using a Stateless widget but it is supposed to accept values so that wouldn't work, I have tried google and here as well and while there are a good amount of posts on "This class (or a class which this class inherits from) is marked as '@immutable'" it doesn't really help me understand why what I'm doing is incorrect. When I add the final keyword, my constructor gets angry since my variables are then supposed to be final.

import 'package:flutter/material.dart';
import './header.dart';
import './title.dart';

class NotificationsScreen extends StatefulWidget {
  createState() {
    return NotificationsScreenState();
  }
}

class NotificationsScreenState extends State<NotificationsScreen> {
  String searchString = '';
  Widget header = new Header();
  Widget title = new TitleText(Icons.notifications, 'Notifications');

  //team logo centered
  //List of notifications
  Widget build(context) {
    return Container(
        margin: EdgeInsets.all(20.0),
        alignment: Alignment.center,
        child: Column(
          children: [
            header,
            Container(margin: EdgeInsets.only(top: 25.0)),
            title,
          ],
        ),
      );

  }
}
import 'package:flutter/material.dart';

class TitleText extends StatefulWidget {
  IconData icon = IconData(0);
  String title = '';

  TitleText(this.icon, this.title);

  @override
  _TitleState createState() => _TitleState();
}

class _TitleState extends State<TitleText> {
  @override
  Widget build(context) {
    return Container(
      width: double.infinity,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(widget.icon, size: 30),
          Text(widget.title),
        ],
      ),
    );
  }
}

The output works as intended but with the warning I am clearly handling this wrong, I am looking for the way I should be passing values to a class like this that returns a widget.

1

1 Answers

0
votes

Like the annotation says, all properties of a Widget subclass must be immutable/final.

As such, if you want to give your properties a default values, you have to do so in the constructor.

Instead of:

class Foo {
  String bar = "default";

  Foo({this.bar});
}

do:

class Foo {
  final String bar;
  Foo({this.bar = "default"});
}

or:

class Foo {
  final String bar;
  Foo({String bar}): bar = bar ?? "default";
}