Mehdi Rezzag Hebla
Mehdi Rezzag Hebla

Reputation: 334

Dart Flutter: Function not executing

I am new to Dart & Flutter, I am trying to test Future functionality. I wrote a short async function, in which two Future objects are nested. Problem: The function does not execute, and when I try to attribute it to a variable I get an error This expression has a type of 'void' so its value can't be used. and Only static members can be accessed in initializers.. Here is the code: [![enter image description here][1]][1]

  @override
  _ChoseLocationState createState() => _ChoseLocationState();
}

class _ChoseLocationState extends State<ChoseLocation> {
  int counter = 0;
  
  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);
  }

  dynamic funcex = simulateRequest();

  @override
  void initState() {
    super.initState();
    print('This is the initial state.');
  }
  
  
  @override
  Widget build(BuildContext context) {
    print('This is the build function processing.');
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text('Set Location'),
          centerTitle: true,
          ),
        body: RaisedButton(
          onPressed: (){
          setState(() {
            counter++;
          });
        },
          color: Colors.blue,
          child: Text('Counter is: $counter'),
        ),
      );
  }
}```

[1]: https://i.sstatic.net/XmvY9.png

Upvotes: 0

Views: 3178

Answers (3)

Divyanshu Kumar
Divyanshu Kumar

Reputation: 1461

In my case, 1st function does not invokes performTask function. But 2nd function invoked performTask and executes as expected. Below is an illustration.

Conclusion - Try including parentheses ( ) at the end of your invoking void function

 // 1st Function - Not working
 void someFunction(int A, void Function()? performTask) {
    if (A == 1) {

      // performTask did not invoked 
      performTask;
    } else {
     // Do something else
    }
  }

  // 2nd Function - Working
  void someFunction(int A, void Function()? performTask) {
    if (A == 1) {
      if (performTask != null) {

      // performTask is invoked 
        performTask();
      }
    } else {
     // Do something else
    }
  }

Upvotes: 0

pedro pimont
pedro pimont

Reputation: 3084

simulateRequest has a return type of void, so if you'r trying to store this function in the variable you shouldn't put parenthesis. If you use the parenthesis you'll be running the function and assigning it's returned value which is void to the variable funcex and thats why u're getting: This expression has a type of 'void' so its value can't be used.

      @override
  void initState() {
    dynamic funcex = simulateRequest;
    funcex();
    super.initState();
    print('This is the initial state.');
  }

Upvotes: 2

Peter Haddad
Peter Haddad

Reputation: 80924

Try the following:

class ChoseLocation extends StatefulWidget {
  ChoseLocation({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ChoseLocationState createState() => _ChoseLocationState();
}

class _ChoseLocationState extends State<ChoseLocation> {
  int counter = 0;
  
  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);
  }

//   dynamic funcex = simulateRequest();

  @override
  void initState() {
    super.initState();
    simulateRequest();
    print('This is the initial state.');
  }
  
  
  @override
  Widget build(BuildContext context) {
    print('This is the build function processing.');
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text('Set Location'),
          centerTitle: true,
          ),
        body: RaisedButton(
          onPressed: (){
          setState(() {
            counter++;
          });
        },
          color: Colors.blue,
          child: Text('Counter is: $counter'),
        ),
      );
  }
}

You need to call simulateRequest() inside a method example initState, and since it doesnt return anything then you cannot assign it to a variable.

Upvotes: 1

Related Questions