Mohamed Shaheen
Mohamed Shaheen

Reputation: 663

Async function await don't work and return is executed before await is done

I want the return to wait for the response to respond but it dont and returns Instance of 'Future<dynamic>' print waits for the response but the return don't how to solve this ?

Future getAPI(String url,var body)async{
  Response response;
  Dio dio = new Dio();
  response =await dio.get(baseURL+url, queryParameters: body);
  print(response.data);
  return response.data;
}

Upvotes: 0

Views: 89

Answers (1)

chunhunghan
chunhunghan

Reputation: 54367

You can copy paste run full code below
You need to use await getAPI() when you call this function

code snippet

void _incrementCounter() async{
    var data = await getAPI("test","test");
    print('data  ${data}');

output

I/flutter (28471): response.data  <!doctype html><html itemscope="" ...
I/flutter (28471): data  <!doctype html><html itemscope="" ...

full code

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  Future getAPI(String url, var body) async {
    Response response;
    Dio dio = new Dio();
    //response = await dio.get(baseURL + url, queryParameters: body);
    response = await Dio().get("http://www.google.com");
    print('response.data  ${response.data}');
    return response.data;
  }

  void _incrementCounter() async{
    var data = await getAPI("test","test");
    print('data  ${data}');
    setState(() {

      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 1

Related Questions