问题
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();
}
}
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.
}
回答1:
You have to instantiate an object of the SimReq class if you want access to its methods like:
SimReq simReq = SimReq();
simReq.simulateRequest();
or use the static
keyword to make this function accessible outside of this class
static void simulateRequest() async {
来源:https://stackoverflow.com/questions/62502376/dart-flutter-how-to-call-for-a-class-method-inside-another-class