Search code examples
flutterclasssubclasssuperclass

Flutter: Superclass variable to upper case without touching subclass


Here i have some pseudo code with this scenario.

The UpperCaseElement superclass has the text variable. If upperCase is true, the text variable should be turned into upperCase.

I have tried setting it in the constructor, but it is only the default value if it isn't defined.

import "package:flutter/material.dart";

abstract class UpperCaseElement extends StatelessWidget {
  // Should be uppercase if upperCase = true
  final String text;

  final bool upperCase;

  // My attempt to set this.text to upperCase, but it doesn't work.
  const UpperCaseElement({Key? key, this.text = text.toUpperCase(), this.upperCase = false})
      : super(key: key);
}

class TestWidget extends UpperCaseElement {
  const TestWidget({
    Key? key,
    super.text,
    super.upperCase,
  }) : super(key: key);

  @override
  Widget build(context) {
    // Yes, the checking and converting to upper case can be done here. But doing that on all subclasses would be a pain. That's why I want to do it on the superclass.
    return Text(text);
  }
}

class TestPage extends StatelessWidget {
  const TestPage({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(context) {
    return Scaffold(
      body: Column(children: const [
        // Should be TEST
        TestWidget(
          text: "test",
          upperCase: true,
        )
      ]),
    );
  }
}

Solution

  • Update: force on abstract class, you can't use const constructor.

    @immutable
    abstract class UpperCaseElement extends StatelessWidget {
      String text;
      final bool upperCase;
      UpperCaseElement({Key? key, required this.text, this.upperCase = false})
          : super(key: key) {
        text = upperCase ? text.toUpperCase() : text;
      }
    }
    

    For the UpperCaseElement is an abstract class, we can handle conditional inside TestWidget.

    class TestWidget extends UpperCaseElement {
      const TestWidget({
        Key? key,
        required super.text,
        super.upperCase,
      }) : super(key: key);
    
      @override
      Widget build(context) {
        return Text(upperCase ? text.toUpperCase() : text);
      }
    }
    
    abstract class UpperCaseElement extends StatelessWidget {
      final String text;
      final bool upperCase;
      const UpperCaseElement({
        Key? key,
        required this.text,
        this.upperCase = false,
      }) : super(key: key);
    }