Dart & Flutter: How to call for a class method inside another class

拥有回忆 提交于 2020-06-29 03:40:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!