[英]Dart & Flutter: How to call for a class method inside another class
new to Dart here, sorry in advance if this is a redundant question; Dart 的新手,如果这是一个多余的问题,请提前道歉; 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.我创建了一个 function simulateRequest
,然后将它传递给它自己的 class SimReq
,并单独保存在一个文件中。 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,但是当我尝试执行它时,出现错误,这是 class 代码:
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();
}
}
and here is the main file code:这是主要文件代码:
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.
}
You have to instantiate an object of the SimReq class if you want access to its methods like:如果您想访问它的方法,您必须实例化 SimReq class 的 object ,例如:
SimReq simReq = SimReq();
simReq.simulateRequest();
or use the static
keyword to make this function accessible outside of this class或使用static
关键字使此 function 在此 class 之外可访问
static void simulateRequest() async {
without instance没有实例
simReq().simulateRequest();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.