zoukankan      html  css  js  c++  java
  • Flutter异步获取网络数据

    使用dio和futurebuilder,异步获取网络数据.在数据加载之前,页面显示加载图标.

    代码如下:

    import 'package:flutter/material.dart';
    import 'package:dio/dio.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @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> {
    
      Future<String> mockNetworkData() async {
    
        //请求url
        var url = 'http://xxx';
        try {
          Response response = await Dio().get(url);
          //print(response);
         // print("------------");
         // print(response.data.toString());
          return response.data.toString();
    
      } catch(e){
        print(e);
        return '获取数据失败';
      }
        
      }
    
      @override
      Widget build(BuildContext context) {
        
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
        
          child: FutureBuilder<String>(
            future: mockNetworkData(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              // 请求已结束
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  // 请求失败,显示错误
                  return Text("Error: ${snapshot.error}");
                } else {
                  // 请求成功,显示数据
                  return Text("Contents: ${snapshot.data}");
                }
              } else {
                // 请求未结束,显示loading
                return CircularProgressIndicator();
              }
            },
        ),
          ),
        
        );
      }
    }
    
    

    其中,FutureBuilder会依赖一个Future,它会根据所依赖的Future的状态来动态构建自身。

    FutureBuilder构造函数:

    FutureBuilder({
      this.future,
      this.initialData,
      @required this.builder,
    })
    
    • future:FutureBuilder依赖的Future,通常是一个异步耗时任务。

    • initialData:初始数据,用户设置默认数据。

    • builder:Widget构建器;该构建器会在Future执行的不同阶段被多次调用,构建器签名如下:Function (BuildContext context, AsyncSnapshot snapshot)
      snapshot会包含当前异步任务的状态信息及结果信息 ,比如可以通过snapshot.connectionState获取异步任务的状态信息、通过snapshot.hasError判断异步任务是否有错误等等,完整的定义可以查看AsyncSnapshot类定义。

  • 相关阅读:
    手动实现 SpringMVC
    2014年9月9日 高级命令command的使用(上)
    2014年8月29日 透视图补充及视图开头
    2014年8月24日 菜单 工具条 右键菜单(上下文菜单)
    2014年8月14日 透视图
    2014年8月8日
    2014年8月1日
    关于EMF中从schema到ecore转变中的默认处理问题
    JAVA一些常用的时间操作
    echarts基本使用
  • 原文地址:https://www.cnblogs.com/nolang/p/13291938.html
Copyright © 2011-2022 走看看