【问题标题】:Dart & Flutter: How to call for a class method inside another classDart & Flutter:如何在另一个类中调用一个类方法
【发布时间】:2020-06-21 17:50:10
【问题描述】:

这里是 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.
  }
  

【问题讨论】:

  • 错误是什么?
  • @pedropimont 我刚刚添加了一条评论,它更好地解释了它。错误:Instance member 'simulateRequest' can't be accessed using static access.
  • 创建SimReq的实例并调用方法simulateRequest

标签: function class flutter dart execute


【解决方案1】:

如果你想访问它的方法,你必须实例化 SimReq 类的一个对象,例如:

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

或者使用static关键字使这个函数在这个类之外可以访问

static void simulateRequest() async {

【讨论】:

    猜你喜欢
    • 2019-03-04
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多