本文介绍了飞镖Flutter:如何在另一个类中调用一个类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

new to Dart here, sorry in advance if this is a redundant question; I couldn't find the answer.I created a function simulateRequest and then passed it to its own class SimReq and saved it in a file on its own.I imported the class in the main file, but when I try to execute it, I get an error, here is the class code:

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.
  }

推荐答案

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

You have to instantiate an object of the SimReq class if you want access to its methods like:

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

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

or use the static keyword to make this function accessible outside of this class

static void simulateRequest() async {

这篇关于飞镖Flutter:如何在另一个类中调用一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:31