Flutter入门06----Dart异步操作和网络请求

2022-01-18  本文已影响0人  zyc_在路上

阻塞式调用与非阻塞式调用

Dart事件循环

Dart的异步操作

Future
import 'dart:io';

main(List<String> args) {
  print("main start");

  //发送一个网络请求 耗时操作
  var futurn = getNetworkData();

  //需要在futurn中回调函数有返回结果,才会执行下面的回调函数
  futurn.then((String value) {
    print(value);
  }).catchError((error) {
    print("---$error---");
  }).whenComplete(() {
    print("执行完毕");
  });

  print("main end");
}

//模拟一个网络请求
//futurn包裹网络请求 -- 耗时操作
//1.只要有返回结果,那么就执行Future对应的then的回调函数;
//2.如果没有返回结果(有错误信息),需要在Future回调中抛出一个异常;
Future<String> getNetworkData() {
  return Future<String>(() {
    sleep(Duration(seconds: 3));
    return "Hello World!!";
    // throw Exception("error");
  });
}
import 'dart:io';

main(List<String> args) {
  print("main start");

  Future(() {
    //1.发送的第一次请求
    sleep(Duration(seconds: 3));
    return "第一次的结果";
  }).then((value) {
    print(value);
    //2.发送第二次请求
    sleep(Duration(seconds: 3));
    // return "第二次的结果";
    throw Exception("第二次网络请求 抛出异常");
  }).then((value) {
    print(value);
    //3.发送第三次请求
    sleep(Duration(seconds: 3));
    return "第三次的结果";
  }).then((value) {
    print(value);
  }).catchError((error) {
    print(error);
  });

  print("main end");
}
main(List<String> args) {
  Future(() {
    return "Hello World!!!";
  }).then((value) {
    print(value);
  });

  Future.value("哈哈哈").then((value) {
    print(value);
  });

  Future.error("错误信息").catchError((error) {
    print(error);
  });

  //延迟
  Future.delayed(Duration(seconds: 3), () {
    return "Hello Flutter";
  }).then((value) {
    return "Hello World!!";
  }).then((value) {
    print(value);
  });
}
await 与 async
import 'dart:io';

main(List<String> args) {
  print("main start");

  getData();

  print("main end");
}

void getData() async {
  //链式调用
  var res1 = await getNetworkData("SF");
  print(res1);
  var res2 = await getNetworkData(res1);
  print(res2);
  var res3 = await getNetworkData(res2);
  print(res3);
}

//异步函数
//1.await必须在async函数中才能使用
//2.async函数返回的结果必须是一个Future
Future getNetworkData(String str) {
  return Future(() {
    sleep(Duration(seconds: 3));
    return "Hello World!!" + str;
  });
}

多核CPU的利用

Isolate
Isolate的创建
import 'dart:isolate';

main(List<String> args) {
  print("main start");
  //不会阻塞当前线程 
  Isolate.spawn(calc, 100);

  print("main end");
}

void calc(int count) {
  var total = 0;
  for (var i = 0; i < count; i++) {
    total += I;
  }
  print(total);
}
Isolate的通信机制
import 'dart:isolate';

main(List<String> args) async {
  print("main start");

  //1.创建管道
  ReceivePort port = ReceivePort();

  //2.创建Isolate
  Isolate isolate = await Isolate.spawn<SendPort>(foo, port.sendPort);

  //3.监听管道
  port.listen((message) {
    print(message);
    //关闭管道
    port.close();
    //Isolate销毁
    isolate.kill();
  });

  print("main end");
}

void foo(SendPort port) {
  return port.send("Hello World");
}
第三方网络请求库
image.png
class HttpConfig {
  static const String baseUtl = "http://httpbin/org";
  static const int timeout = 5000;
}
import 'package:Fluter01/service/http_config.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

class HttpReuquest {
  //基础配置
  static final BaseOptions baseOptions = BaseOptions(baseUrl: HttpConfig.baseUtl,connectTimeout: HttpConfig.timeout);
  //网络请求
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url,{String method = "get",Map<String,dynamic> params,Interceptor interceptor}) async{
    //配置 这里的option和上面代码中的baseOptions,Dio组件内部会自动帮我们合并的
    final options = Options(method: method);

    //全局拦截器
    Interceptor dInterceptor = InterceptorsWrapper(
        onRequest: (options){
          print("请求拦截");
          return options;
        },
        onResponse: (response) {
          print("响应拦截");
          return response;
        },
        onError: (error){
          print("错误拦截");
          return error;
        }
    );

    List<Interceptor> inters = [dInterceptor];

    //单独设置的拦截器
    if (interceptor != null){
      inters.add(interceptor);
    }

    dio.interceptors.addAll(inters);

    //发送网络请求
    try {
      Response response = await dio.request(url,queryParameters: params,options: options);
      return response.data;
    } on DioError catch(e) {
      return Future.error(e);
    }
  }
}
import 'package:flutter/material.dart';
import 'package:Fluter01/service/http_request.dart';

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

class SFMyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: SFHomePage());
  }
}

class SFHomePage extends StatefulWidget {
  @override
  _SFHomePageState createState() => _SFHomePageState();
}

class _SFHomePageState extends State<SFHomePage> {
  bool isShowFloatButton = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("基础widget")),
      body: SFHomeContent(),
      floatingActionButton: isShowFloatButton
          ? FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              onPressed: () {

              },
            )
          : null,
    );
  }
}

class SFHomeContent extends StatefulWidget {
  @override
  _SFHomeContentState createState() => _SFHomeContentState();
}

class _SFHomeContentState extends State<SFHomeContent> {

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

    //发送网络请求
    // ///1.创建dio对象
    // final dio = Dio();
    // ///2.发送网络请求
    // dio.get("http://httpbin.org/get").then((value) {
    //   print(value);
    // });
    
    HttpReuquest.request("http://httpbin.org/get",params: {"name" : "liyanyan"}).then((value) {
      print(value);
    });
    
    
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
      onNotification: (ScrollNotification notification){
        if(notification is ScrollStartNotification){
          print("开始滚动");
        }else if (notification is ScrollUpdateNotification){
          print("正在滚动 -- 总区域:${notification.metrics.maxScrollExtent} 当前位置: ${notification.metrics.pixels}");
        }else if (notification is ScrollEndNotification){
          print("结束滚动");

        }
        return true;
      },
      child: ListView.builder(
        itemBuilder: (BuildContext ctx, int index) {
          return ListTile(
            leading: Icon(Icons.people),
            title: Text("联系人$index"),
          );
        },
        itemCount: 100,
      ),
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读