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

作者: 蓝不蓝编程 | 来源:发表于2019-12-05 10:04 被阅读0次

    实现步骤

    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");
    }
    

    界面效果

    主要代码

    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<MyHomePage> {
      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: <Widget>[
                Text(
                  '$content',
                )
              ],
            ),
          ),
        );
      }
    }
    

    完整源代码

    https://gitee.com/cxyzy1/flutter_network_demo

    相关文章

      网友评论

        本文标题:Flutter实现网络请求(基于dio库)

        本文链接:https://www.haomeiwen.com/subject/nhylgctx.html