简体   繁体   中英

flutter can not get response with http and dio

I want to get data from server.I test with http and dio for get data. in both of them if I get data from local server everything is ok and I can get the response but when I use url for get data from server it does not work.

it is my codes:

class MyAppState extends State<MyHome> {

  /* void getHttpDio() async {
    try{
      var url = 'https://reqres.in/api/users?page=2';
      var response = await http.get(url);
      print( response.body);
    }catch(e){
      print(e);
    }
  }*/

  Future getHttp() async {
    try{
      var dio=Dio();
      var response=await dio.get("https://reqres.in/api/users?page=2");
      print(response.data);
    }catch(e){
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
    getHttp();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("appbar title"),
      ),
      body: Text("clicksite"),
      floatingActionButton: FloatingActionButton(
        child: Text("run"),
        onPressed: () {
        },
      ),
    );
  }
}

and it is console:

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device Android SDK built for x86...
D/EGL_emulation( 3371): eglMakeCurrent: 0xe62690e0: ver 2 0 (tinfo 0xe6215630)

I tried your code and it works fine. The only issue that I encountered was that I'm unable to print the dynamic HashMap using print() . I needed to wrap the response data with '${response.data}' . Otherwise, it'll throw this error.

flutter: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String?'

Other than that, the snippet works well without issues. I'm running on Flutter 2.8 and dio 4.0.4

Future getHttp() async {
  try {
    var dio = Dio();
    var response = await dio.get("https://reqres.in/api/users?page=2");
    debugPrint(response.data);
  } catch (e) {
    debugPrint(e.toString());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM