Flutter: 发送 http 请求

Flutter: 发送 http 请求_第1张图片
首先下载安装 http 包,即修改 pubspec.yaml 并保存, 然后VS code flutter 会自动下载相应的 package:

dependencies:
  flutter:
    sdk: flutter
  provider: ^4.0.0
  intl: ^0.15.8
  http: ^0.12.0+2

( 最新的 http 包版本为 0.13.5, 0.12 的版本的用法与 0.13 的用法不同。)

然后在需要发送 http 请求的 .dart 文件中 import 相应的库:

import 'dart:convert';
import 'package:http/http.dart'
    as http; // use 'as http' to avoid possible name clashes

import 'dart:convert'; 是为了实现 JSON 数据的编码与解码。

后端以 firebase 为例:

// 返回 Future 是因为,需要显示 loading 状态,
Future<void> addProduct(Product product) {
    const url =
        'https://flutter-shop-app-810a8-default-rtdb.firebaseio.com/products.json';
    return http
        .post(
      url,
      body: json.encode({
        'title': product.title,
        'description': product.description,
        'imageUrl': product.imageUrl,
        'price': product.price,
        'isFavorite': product.isFavorite,
      }),
    )
        .then((response) {
      
      // 下面的 newProduct 与 http 关系不大,只是需要更新内存中的 product
      final newProduct = Product(
        title: product.title,
        description: product.description,
        price: product.price,
        imageUrl: product.imageUrl,
        // id: DateTime.now().toString(), // old code
        id: json.decode(response.body)['name'],
      );

      _items.add(newProduct);
      // _items.insert(0, newProduct); // at the start of the list
      notifyListeners();
    });
  }

设置是否在 loading,等待某些操作的完成:

var _isLoading = false;

void _saveForm() {
    final isValid = _form.currentState.validate();
    if (!isValid) {
      return;
    }
    _form.currentState.save();
    setState(() {
      _isLoading = true;
    });
    if (_editedProduct.id != null) {
      Provider.of<Products>(context, listen: false)
          .updateProduct(_editedProduct.id, _editedProduct);
      setState(() {
        _isLoading = false;
      });
      Navigator.of(context).pop();
    } else {
      Provider.of<Products>(context, listen: false)
          .addProduct(_editedProduct)
          .then((_) {   // 这里的 then 对应前面的 Future 返回类型
        setState(() {
          _isLoading = false;
        });
        Navigator.of(context).pop();
      });
    }
    // Navigator.of(context).pop();  // pop() 返回来时的页面
  }

显示 loading 状态, 组件使用 CircularProgressIndicator

body: _isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Padding(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _form,
                child: ListView(
                  children: <Widget>[

loading 状态显示:

Flutter: 发送 http 请求_第2张图片

你可能感兴趣的:(flutter,http)