见图:

1、添加dependencies,在pubspec.yaml文件里

Flutter 配置网络

2、打开pubspec.yaml文件

Flutter 配置网络

在environment下的第一个dependencies里写上http: 0.12.0,然后点击右上角的Package get,这样就会去下载http包Flutter 配置网络

大约2秒就好了,这样的话我们的网络http包就导入进来了,这样就可以访问网络了。

新建一个networkbackground.dart文件

导入以下代码

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:isolate';

void main() {
  runApp(SampleApp());
}

class SampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SampleAppPage(),
    );
  }
}

class SampleAppPage extends StatefulWidget {
  SampleAppPage({Key key}) : super(key: key);

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

class _SampleAppPageState extends State<SampleAppPage> {
  List widgets = [];

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

  showLoadingDialog() {
    if (widgets.length == 0) {
      return true;
    }

    return false;
  }

  getBody() {
    if (showLoadingDialog()) {
      return getProgressDialog();
    } else {
      return getListView();
    }
  }

  getProgressDialog() {
    return Center(child: CircularProgressIndicator());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Sample App"),
        ),
        body: getBody());
  }

  ListView getListView() => ListView.builder(
      itemCount: widgets.length,
      itemBuilder: (BuildContext context, int position) {
        return getRow(position);
      });

  Widget getRow(int i) {
    return Padding(padding: EdgeInsets.all(10.0), child: Text("Row ${widgets[i]["title"]}"));
  }

  loadData() async {
    ReceivePort receivePort = ReceivePort();
    await Isolate.spawn(dataLoader, receivePort.sendPort);

    // The 'echo' isolate sends its SendPort as the first message
    SendPort sendPort = await receivePort.first;

    List msg = await sendReceive(sendPort, "https://jsonplaceholder.typicode.com/posts");

    setState(() {
      widgets = msg;
    });
  }

  // the entry point for the isolate
  static dataLoader(SendPort sendPort) async {
    // Open the ReceivePort for incoming messages.
    ReceivePort port = ReceivePort();

    // Notify any other isolates what port this isolate listens to.
    sendPort.send(port.sendPort);

    await for (var msg in port) {
      String data = msg[0];
      SendPort replyTo = msg[1];

      String dataURL = data;
      http.Response response = await http.get(dataURL);
      // Lots of JSON to parse
      replyTo.send(json.decode(response.body));
    }
  }

  Future sendReceive(SendPort port, msg) {
    ReceivePort response = ReceivePort();
    port.send([msg, response.sendPort]);
    return response.first;
  }
}

3、点击运行,网络获取的数据就完成了

Flutter 配置网络

如果您没有导入http库的话,那么import 'package:http/http.dart' as http;会报错,找不到网络库。

如果您的http包引入的位置有错误的话,也会报这个错:Mapping values are not allowed here. Did you miss a colon earlier?

集成http库

https://pub.dartlang.org/packages/http
添加依赖
dependencies:
  http: ^0.12.0
安装
flutter packages get
导入
import 'package:http/http.dart' as http;

常用方法

get(dynamic url, { Map<String, String> headers }) → Future<Response>
  • (必须)url:请求地址
  • (可选)headers:请求头
post(dynamic url, { Map<String, String> headers, dynamic body, Encoding encoding }) → Future<Response>
  • (必须)url:请求地址
  • (可选)headers:请求头
  • (可选)body:参数
  • (编码)Encoding:编码 例子
http.post('https://flutter-cn.firebaseio.com/products.json',
            body: json.encode(param),encoding: Utf8Codec())
    .then((http.Response response) {
      final Map<String, dynamic> responseData = json.decode(response.body);
     //处理响应数据
     
    }).catchError((error) {
      print('$error错误');
    });

返回值都用到Dart Futures, 类似JavaScript中的promise 官方推荐使用async/await来调用网络请求

  void addProduct(Product product) async {
    Map<String, dynamic> param = {
      'title': product.title,
      'description': product.description,
      'price': product.price
    };
    try {
      final http.Response response = await http.post(
          'https://flutter-cn.firebaseio.com/products.json',
          body: json.encode(param),
          encoding: Utf8Codec());

      final Map<String, dynamic> responseData = json.decode(response.body);
      print('$responseData 数据');
      
    } catch (error) {
      print('$error错误');
    }
  }

用 try catch来捕获错误 两种写法都可以,个人觉得第二种语法思路更明确.

参考链接:dart中的http包讲解flutter官方网站Dart语言官方网站

 

相关文章:

猜你喜欢
  • 2021-11-03
  • 2021-10-31
  • 2022-01-07
  • 2022-01-07
相关资源
相似解决方案