如何从另一个 class 访问函数 - Flutter
How to access a function from another class - Flutter
我有一个名为 getTextColor
的函数,但我不得不在另一个 class 中声明它。如何从不同的 class 访问此功能?
这是我尝试访问它的方式:
class _NextPageState extends State<NextPage> with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
),
body: Center(
child: Container(
child: RichText(
text: TextSpan(children: [
TextSpan(
text: widget.result + ' ',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: getTextColor(widget.result), // Here is the problem.
height: 2.5,
letterSpacing: 0.7,
)),
该函数的逻辑在一个名为 class _MainScreenState extends State<MainScreen>
的 class 中
综上所述,我如何告诉代码getTextColor
来自另一个class?
您需要创建另一个类的对象或将函数设为静态才能访问它。
如果函数是静态的,那么你可以这样调用它:
ClassName.getTextColor();
如果函数不是静态的,那么您需要创建一个对象来调用它:
var object = ClassName();
object.getTextColor();
我有一个名为 getTextColor
的函数,但我不得不在另一个 class 中声明它。如何从不同的 class 访问此功能?
这是我尝试访问它的方式:
class _NextPageState extends State<NextPage> with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
),
body: Center(
child: Container(
child: RichText(
text: TextSpan(children: [
TextSpan(
text: widget.result + ' ',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: getTextColor(widget.result), // Here is the problem.
height: 2.5,
letterSpacing: 0.7,
)),
该函数的逻辑在一个名为 class _MainScreenState extends State<MainScreen>
综上所述,我如何告诉代码getTextColor
来自另一个class?
您需要创建另一个类的对象或将函数设为静态才能访问它。 如果函数是静态的,那么你可以这样调用它:
ClassName.getTextColor();
如果函数不是静态的,那么您需要创建一个对象来调用它:
var object = ClassName();
object.getTextColor();