0
votes

So I am trying to create a custom widget in flutter that has multiple constructors. Essentially I am creating an arrow button but want to be able to create the button with arrow icons facing in different directions.

Currently my code looks like this:

class RotateButton extends StatefulWidget {
  RotateButton.left() {
    _RotateButtonState createState() => _RotateButtonState.left();
  }

  RotateButton.right() {
    _RotateButtonState createState() => _RotateButtonState.right();
  }

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

class _RotateButtonState extends State<RotateButton> {
  IconData icon;

  _RotateButtonState();

  _RotateButtonState.left() {
    icon = Icons.arrow_back;
  }

  _RotateButtonState.right() {
    icon = Icons.arrow_forward;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: kPrimaryColor,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Icon(
          icon,
          size: 70,
        ),
      ),
    );
  }
}

Every time I use my widget it just defaults to the default constructor and shows no Icon child.

Is there a way to build a class without making a default constructor.

Also is there a way I can build this widget without using a stateful widget as it kind of just overcomplicates it.

I am getting a message that says:

The declaration 'createState' isn't referenced

This message is coming up next to the named constructors in the rotatebutton class.

Any help is very much appreciated.

1
add IconData icon; in RotateButton class and for example use RotateButton.left() : icon = Icons.arrow_back; then inside _RotateButtonState simply use widget.icon - pskink
Awesome! that works but only problem is I am now getting a message that says: This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: RotateButton.icon - Daniel Booth
"[...] but one or more of its instance fields aren't final: RotateButton.icon" - come in, the message is self explaining... - pskink

1 Answers

0
votes

Use something like this:

class SomeWidget extends StatelessWidget {
  final bool isRight;

  const SomeWidget({Key key, this.isRight}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Icon(isRight?Icons.arrow_forward:Icons.arrow_back),
    );
  }
}