首页 > 解决方案 > 如何从另一个类访问函数 - Flutter

问题描述

我调用了这个函数,getTextColor但我不得不在另一个类中声明它。如何从不同的类访问此功能?

这是我尝试访问它的方式:

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来自其他类的代码?

标签: androidflutterdartmobile

解决方案


您需要创建另一个类的对象或使函数静态才能访问它。如果函数是静态的,那么你可以这样调用它:

ClassName.getTextColor();

如果函数不是静态的,那么您需要创建一个对象来调用它,如下所示:

var object = ClassName();
object.getTextColor();

推荐阅读