Flutter实现网络请求(基于dio库)

实现步骤

  1. 添加依赖
dio: 3.0.7
  1. 发起网络请求
void _initAsync() async {
  Response response;
  Dio dio = new Dio();
  response = await 
  dio.get("https://gitee.com/cxyzy1/flutter_network_demo/raw/master/data.txt");
}

界面效果

Flutter实现网络请求(基于dio库)_第1张图片

主要代码

import 'package:dio/dio.dart';
import 'package:flutter/material.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'),
    );
  }
}

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

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

class _MyHomePageState extends State {
  String content = "loading...";

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

  void _initAsync() async {
    Response response;
    Dio dio = new Dio();
    response = await dio.get("https://gitee.com/cxyzy1/flutter_network_demo/raw/master/data.txt");
    setState(() {
      content = response.data.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '$content',
            )
          ],
        ),
      ),
    );
  }
}

完整源代码

https://gitee.com/cxyzy1/flutter_network_demo

你可能感兴趣的:(Flutter实现网络请求(基于dio库))