Reputation: 7156
Instead of expected string value I get the Instance of Future<String>
in my widget:
(in the second line of winget should be a string value of 373,8)
(_rapport.isNotEmpty && _rapport.length == 3)
? Text((_distortion(_rapport, widget.printer)).toString()) // this function return Future<String>
: const Text(''), // rapport is empty
The function is:
Future<String> _distortion(String rapport, String printer) async {
final String record = await _getRecord(rapport);
print('record: ${record.toString()}'); // this gives me an expected valid output
final List row = record.toString().split(';');
final String d1 = row[1]; // tachys
final String d2 = row[3]; // onyx
switch (printer) {
case 'Tachys':
{
print('distortion: $d1'); // output: distortion: 373,8
return d1;
}
break;
default:
{
print('distortion: $d2');
return d2;
}
}
}
How can I get real value from Future in widget?
Upvotes: 2
Views: 268
Reputation: 1969
Either you can call the method in initState()
and set the value else use FutureBuilder
for handling future value.You can have a look at the documentation of FutureBuilder
Upvotes: 0
Reputation: 1745
The way to do that is using FutureBuilder() widget .
Change your build function to following
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future : _distortion()
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading....');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return (_rapport.isNotEmpty && _rapport.length == 3)
? Text(snapshot.data)
: (_rapport.isNotEmpty && _rapport.length < 3)
? const Text('wrong rapport')
: const Text(''), // rapport is empty
);
}
},
),
);
}
Upvotes: 1
Reputation: 21
I thinks you must to add async await when you call (_distortion) function as below:
(_rapport.isNotEmpty && _rapport.length == 3)
? Text(await (_distortion(_rapport, widget.printer)).toString()) // this function return Future<String>
: (_rapport.isNotEmpty && _rapport.length < 3)
? const Text('wrong rapport')
: const Text(''),
Upvotes: 0