Flutter API客户端插件flux_api_client的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter API客户端插件flux_api_client的使用

Flux API Client

Flux API Client 是一个用于轻松高效地处理HTTP请求的Flutter包,支持动态响应映射。

特性

  • 支持GET、POST、PUT和DELETE HTTP请求。
  • 简单的JSON序列化和反序列化。
  • 可定制化的错误处理,带有日志选项。
  • 与Flutter应用程序易于集成。

开始使用

创建模型类

定义一个表示API期望返回的数据的模型类。例如,对于Product实体:

class Product {
  final int? id;
  final String name;
  final String username;

  Product({this.id, required this.name, required this.username});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'],
      name: json['name'],
      username: json['username'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'username': username,
    };
  }
}
ProductsPage

ProductsPage是一个简单的UI,用于显示产品列表、创建新产品和删除现有产品。

class ProductsPage extends StatefulWidget {
  [@override](/user/override)
  _ProductsPageState createState() => _ProductsPageState();
}

class _ProductsPageState extends State<ProductsPage> {
  late Future<List<Product>?> futureProducts;
  final String url = 'https://jsonplaceholder.typicode.com/users';

  [@override](/user/override)
  void initState() {
    super.initState();
    futureProducts = fetchProducts();
  }

  Future<List<Product>?> fetchProducts() async {
    final getRequest = GetRequest<Product>(
      url: url,
      fromJson: (json) => Product.fromJson(json),
    );
    return await getRequest.fetchProducts();
  }

  Future<void> createProduct() async {
    final newProduct = Product(id: null, name: "shiboo", username: "sarvajeet");

    final postRequest = PostRequest<Product>(
      url: url,
      fromJson: (json) => Product.fromJson(json),
      body: newProduct.toJson(),
    );

    final response = await postRequest.send();
    if (response != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Product Created: ${response.name}')),
      );
      setState(() {
        futureProducts = fetchProducts();
      });
    }
  }

  Future<void> deleteProduct(int id) async {
    final deleteRequest = DeleteRequest<Product>(
      url: '$url/$id',
      fromJson: (json) => Product.fromJson(json),
      shouldPrintErrors: true,
      shouldPrintStackTrace: true,
    );

    final isDeleted = await deleteRequest.delete();
    if (isDeleted ) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Product Deleted Successfully.')),
      );
      setState(() {
        futureProducts = fetchProducts();
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Error deleting product.')),
      );
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Products')),
      body: FutureBuilder<List<Product>?>(
        future: futureProducts,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (snapshot.data == null || snapshot.data!.isEmpty) {
            return const Center(child: Text('No products found.'));
          } else {
            final products = snapshot.data!;
            return ListView.builder(
              itemCount: product.length,
              itemBuilder: (context, index) {
                final product = product[index];

                return ListTile(
                  title: Text(product.name),
                  subtitle: Text(product.username),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () => deleteProduct(product.id!),
                  ),
                );
              },
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: createProduct,
        tooltip: 'Create Product',
        child: const Icon(Icons.add),
      ),
    );
  }
}

使用示例

下面是一个完整的示例代码,展示了如何使用flux_api_client插件来处理HTTP请求并管理状态。

import 'package:flutter/material.dart';
import 'package:flux_api_client/flux_api_client.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ProductsPage(),
    );
  }
}

class ProductsPage extends StatefulWidget {
  [@override](/user/override)
  _ProductsPageState createState() => _ProductsPageState();
}

class _ProductsPageState extends State<ProductsPage> {
  late Future<List<Product>?> futureProducts;
  final String url = 'https://jsonplaceholder.typicode.com/users';

  [@override](/user/override)
  void initState() {
    super.initState();
    futureProducts = fetchProducts();
  }

  Future<List<Product>?> fetchProducts() async {
    final getRequest = GetRequest<Product>(
      url: url,
      fromJson: (json) => Product.fromJson(json),
    );
    return await getRequest.fetchProducts();
  }

  Future<void> createProduct() async {
    final newProduct = Product(id: null, name: "shiboo", username: "sarvajeet");

    final postRequest = PostRequest<Product>(
      url: url,
      fromJson: (json) => Product.fromJson(json),
      body: newProduct.toJson(),
    );

    final response = await postRequest.send();
    if (response != null {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Product Created: ${response.name}')),
      );
      setState(() {
        futureProducts = fetchProducts();
      });
    }
  }

  Future<void> deleteProduct(int id) async {
    final deleteRequest = DeleteRequest<Product>(
      url: '$url/$id',
      fromJson: (json) => Product.fromJson(json),
      shouldPrintErrors: true,
      shouldPrintStackTrace: true,
    );

    final isDeleted = await deleteRequest.delete();
    if (isDeleted {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Product Deleted Successfully.')),
      );
      setState(() {
        futureProducts = fetchProducts();
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Error deleting product.')),
      );
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Products')),
      body: FutureBuilder<List<Product>?>(
        future: futureProducts,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (snapshot.data == null || snapshot.data!.isEmpty) {
            return const Center(child: Text('No products found.'));
          } else {
            final products = snapshot.data!;
            return ListView.builder(
              itemCount: products.length,
              itemBuilder: (context, index) {
                final product = products[index];

                return ListTile(
                  title: Text(product.name),
                  subtitle: Text(product.username),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () => deleteProduct(product.id!),
                  ),
                );
              },
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: createProduct,
        tooltip: 'Create Product',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter API客户端插件flux_api_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter API客户端插件flux_api_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter API客户端插件flux_api_client的示例代码。这个示例假设你已经有一个Flutter项目,并且已经添加了flux_api_client插件到你的pubspec.yaml文件中。

首先,确保你的pubspec.yaml文件包含以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  flux_api_client: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

接下来,我们创建一个简单的Flutter应用来使用flux_api_client插件。假设你有一个API端点,你可以通过GET请求获取一些数据。

1. 初始化flux_api_client

首先,你需要在你的项目中初始化flux_api_client。通常,这会在一个单独的文件中完成,比如api_service.dart

// api_service.dart
import 'package:flux_api_client/flux_api_client.dart';
import 'dart:convert';

class ApiService {
  final ApiClient apiClient;

  ApiService({required String baseUrl})
      : apiClient = ApiClient(baseUrl: baseUrl);

  Future<Map<String, dynamic>> fetchData() async {
    final response = await apiClient.get(
      path: '/your-endpoint',  // 替换为你的API端点路径
    );

    if (response.statusCode == 200) {
      // 解析JSON响应
      return jsonDecode(response.body) as Map<String, dynamic>;
    } else {
      throw Exception('Failed to fetch data: ${response.statusCode}');
    }
  }
}

2. 使用ApiService

现在,你可以在你的Flutter组件中使用ApiService来获取数据并显示它。

// main.dart
import 'package:flutter/material.dart';
import 'api_service.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter API Client Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late ApiService apiService;
  Map<String, dynamic>? data;
  bool isLoading = true;
  String? errorMessage;

  @override
  void initState() {
    super.initState();
    apiService = ApiService(baseUrl: 'https://your-api-base-url.com');  // 替换为你的API基础URL
    fetchData();
  }

  void fetchData() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });
    try {
      data = await apiService.fetchData();
    } catch (e) {
      print(e);
      errorMessage = e.toString();
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter API Client Demo'),
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (errorMessage != null)
                  Text(
                    'Error: $errorMessage',
                    style: TextStyle(color: Colors.red),
                  ),
                if (data != null)
                  Text(
                    'Data: ${data!['someKey']}',  // 替换为实际的键名
                    style: TextStyle(fontSize: 20),
                  ),
              ],
            ),
    );
  }
}

在这个示例中,我们创建了一个ApiService类来处理API请求,并在MyHomePage组件中调用它来获取数据。我们还处理了加载状态和错误消息。

请确保将示例中的'/your-endpoint''https://your-api-base-url.com'替换为你实际的API端点和基础URL。同时,根据API返回的数据结构,调整解析和显示的部分。

回到顶部