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
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.