Dart&Flutter:如何在另一个类中调用类方法

时间:2020-06-21 17:50:10

标签: function class flutter dart execute

这里是Dart的新手,如果这是一个多余的问题,请提前抱歉;我找不到答案。 我创建了一个函数simulateRequest,然后将其传递给了自己的类SimReq,并将其单独保存在文件中。 我将类导入了主文件,但是当我尝试执行该类时,出现错误,这是类代码:

class SimReq {
  void simulateRequest() async {

    // first future holds family name
    String famNameFunc = await Future.delayed(Duration(seconds: 2), (){
      String famName = 'Shanshi';
      return famName;
    });


    // second future holds first name
    String compName = await Future.delayed(Duration(seconds: 1), (){
      String fstName = 'Yoshi';
      String compName = '$fstName - $famNameFunc';
      return compName;
    });

    print(compName);
  }
    SimReq(){
    simulateRequest();
 }
}

这是主要的文件代码:

import 'package:flutter/material.dart';
import 'package:wtap/pages/simreq.dart';

class ChoseLocation extends StatefulWidget {
  @override
  _ChoseLocationState createState() => _ChoseLocationState();
}

class _ChoseLocationState extends State<ChoseLocation> {
  int counter = 0;
  @override
  void initState() {
    super.initState();
    print('This is the initial state.');
    SimReq.simulateRequest(); // I am trying to execute the function here.
  }
  

1 个答案:

答案 0 :(得分:1)

如果要访问SimReq类的对象,则必须实例化它的方法,例如:

SimReq simReq = SimReq();
simReq.simulateRequest();

或使用static关键字使该函数可在此类之外访问

static void simulateRequest() async {