Flutter:父类变量变为大写而不触及子类



这里我有一些伪代码。

UpperCaseElement超类有text变量。如果upperCase为true,则应将文本变量转换为大写。

我已经尝试在构造函数中设置它,但如果没有定义它,它只是默认值。

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

更新:强制抽象类,不能使用const构造函数

@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;
}
}

由于UpperCaseElement是一个抽象类,我们可以在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);
}

我的解决方案是定义一个getter函数,它将返回基于bool值的文本

abstract class UpperCaseElement extends StatelessWidget {
// Should be uppercase if upperCase = true
final String text;
final bool upperCase;
get getText => upperCase ? text.toUpperCase() : text;
// My attempt to set this.text to upperCase, but it doesn't work.
const UpperCaseElement({Key? key, required this.text, this.upperCase = false})
: super(key: key);
}
class TestWidget extends UpperCaseElement {
const TestWidget({
Key? key,
required String text,
required bool upperCase,
}) : super(key: key, text: text, upperCase: upperCase);
@override
Widget build(context) {
// calling getText function from superClass.
return Text(getText);
}
}
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,
)
]),
);
}
}

最新更新