Dart Flutter: функция не выполняется - PullRequest
0 голосов
/ 21 июня 2020

Я новичок в Dart & Flutter, я пытаюсь проверить работоспособность Future. Я написал короткую функцию async, в которой вложены два объекта Future. Проблема: Функция не выполняется, и когда я пытаюсь отнести ее к переменной, я получаю сообщение об ошибке This expression has a type of 'void' so its value can't be used. и Only static members can be accessed in initializers.. Вот код: [! [Введите описание изображения здесь] [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.stack.imgur.com/XmvY9.png

Ответы [ 2 ]

1 голос
/ 21 июня 2020

simulateRequest имеет тип возвращаемого значения void, поэтому, если вы пытаетесь сохранить эту функцию в переменной, вы не должны помещать скобки. Если вы используете круглые скобки, вы будете запускать функцию и присваивать ей возвращаемое значение void переменной funcex, и поэтому вы получаете: 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.');
  }
1 голос
/ 21 июня 2020

Попробуйте следующее:

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'),
        ),
      );
  }
}

Вам нужно вызвать simulateRequest() внутри примера метода initState, и, поскольку он ничего не возвращает, вы не можете присвоить его переменной.

...