Flutter高性能网络通信插件flutter_rocket的使用

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

Flutter高性能网络通信插件flutter_rocket的使用

Flutter Rocket介绍

Flutter Rocket 是一个为 Flutter 开发者提供的高性能网络通信插件。它包含多个子包,如 rocket_modelrocket_client 等,帮助开发者简化网络请求和 数据管理。

示例代码

下面是一个完整的示例代码,展示了如何使用 Flutter Rocket 进行网络请求和数据管理。

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

void main() {
  configureRequest();
  runApp(const App());
}

void configureRequest() {
  const String baseUrl = 'https://jsonplaceholder.typicode.com';
  // 创建请求对象
  RocketClient request = RocketClient(url: baseUrl);
  // 保存到全局存储,以便在任何屏幕中使用
  Rocket.add(request);
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
      title: '🚀 Rocket Package 🚀',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
    );
  }
}

// ignore: must_be_immutable
class MyApp extends StatelessWidget {
  final ValueNotifier<double> dx = ValueNotifier<double>(0.1);
  int index = 0;
  MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('🚀 Rocket Package 🚀'),
        centerTitle: true,
      ),
      body: Center(
        child: SizedBox(
          height: context.height * 0.8,
          child: const Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Text(
                '🚀 Rocket Package 🚀',
                style: TextStyle(
                    fontSize: 32.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.brown),
              ),
              Example("Mini View", "miniView"),
              Example("Counter View", "counter"),
              Example("10 Users", "users"),
              Example("100 Posts", "posts"),
              Example("5000 Photos", "photos"),
              Example("200 Todos", "todos"),
            ],
          ),
        ),
      ),
    );
  }
}

class Example extends StatelessWidget {
  final String title, to;
  const Example(this.title, this.to, {Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: context.width * 0.6,
      height: context.height * 0.1,
      child: TextButton(
        key: Key(to),
        child: Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 24.0,
            color: Colors.brown),
        ),
        onPressed: () =&gt; context.go("/$to", extra: title),
      ),
    );
  }
}

extension SizeDevice on BuildContext {
  double get height =&gt; MediaQuery.of(this).size.height;
  double get width =&gt; MediaQuery.of(this).size.width;
}

使用说明

  1. 初始化请求

    void configureRequest() {
      const String baseUrl = 'https://jsonplaceholder.typicode.com';
      // 创建请求对象
      RocketClient request = RocketClient(url: baseUrl);
      // 保存到全局存储,以便在任何屏幕中使用
      Rocket.add(request);
    }
    
  2. 创建请求方法

    class GetPosts {
      static Future getPosts(Post postModel) =&gt;
          Rocket.get(rocketRequestKey).request(
            // endpoint
            postsEndpoint,
            // your model
            model: postModel,
            // parameters for send it with request
            // params:{"key":"value"},
            // inspect method for determine exact json use for generate your model in first step
            // if your api send data directly without any supplement values you not should define it
            // inspect:(data)=&gt;data["response"]
            // or
            // target: ['response']
          );
    }
    
  3. 构建 RocketView Widget

    class PostExample extends StatelessWidget {
      final Post post = Rocket.add<Post>(postsEndpoint, Post(), readOnly: true);
    
      PostExample({Key? key, required this.title}) : super(key: key);
      final String title;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text(
              "Refresh Posts with swipe to down or from here =&gt;",
              style: TextStyle(fontSize: 11.0),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.data_usage),
                onPressed: () =&gt; GetPosts.getPosts(post)
              ),
            ],
          ),
          body: SizedBox(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: RefreshIndicator(
              onRefresh: () {
                return GetPosts.getPosts(post);
              },
              child: RocketView(
                call: () =&gt; GetPosts.getPosts(post),
                model: post,
                callType: CallType.callIfModelEmpty,
                loader: CustomLoading(),
                onError: (RocketException exception, Function() reload) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(exception.exception),
                        if (exception.statusCode != HttpStatus.ok) ...[
                          Text(exception.response),
                          Text(Rocket.get(rocketRequestKey)
                              .msgByStatusCode(exception.statusCode))
                        ],
                        TextButton(
                          onPressed: reload,
                          child: const Text("retry")
                        ),
                      ],
                    ),
                  );
                },
                builder: (context, state) {
                  return SizedBox(
                    height: MediaQuery.of(context).size.height * 0.852,
                    child: ListView.builder(
                      itemCount: post.all!.length,
                      itemBuilder: (BuildContext context, int index) {
                        // your data saved in multi list as Post model
                        Post currentPost = post.all![index];
                        return ListTile(
                          leading: Text(currentPost.id.toString()),
                          title: Text(currentPost.title!),
                          trailing: IconButton(
                            color: Colors.brown,
                            icon: const Icon(Icons.update),
                            onPressed: () {
                              List titles = post.all!
                                  .toJson(include: ["title"], onlyValues: true)
                                  .map((e) =&gt; e[0])
                                  .toList();
                              log("$titles");
                              // update post data
                              currentPost.updateFields(
                                titleField: "This Title changed"
                              );
                            },
                          ),
                          onTap: () =&gt; Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (BuildContext context) {
                                return Details(index);
                              },
                            ),
                          );
                        },
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        );
      }
    }
    
    class Details extends StatelessWidget {
      final int index;
      final Post post = Rocket.get<Post>();
      Details(this.index, {Key? key}) : super(key: key);
      @override
      Widget build(BuildContext context) {
        Post currentPost = post.all![index];
        return Scaffold(
          appBar: AppBar(title: Text(currentPost.title!)),
          body: Center(
            child: ListTile(
              leading: Text(currentPost.id.toString()),
              title: Text(currentPost.title!),
              subtitle: Text(currentPost.body!),
            ),
          ),
        );
      }
    }
    

更多关于Flutter高性能网络通信插件flutter_rocket的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter高性能网络通信插件flutter_rocket的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用flutter_rocket插件来实现高性能网络通信的示例代码。flutter_rocket是一个用于Flutter的高性能HTTP客户端插件,旨在提供比diohttp等更高效的网络请求能力。

首先,你需要在你的pubspec.yaml文件中添加flutter_rocket依赖:

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

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

接下来,是一个简单的示例代码,展示如何使用flutter_rocket进行GET和POST请求:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? responseData;
  late RocketClient client;

  @override
  void initState() {
    super.initState();
    // 初始化RocketClient
    client = RocketClient(
      baseUrl: 'https://api.example.com', // 替换为你的API基础URL
      timeout: const Duration(seconds: 30),
    );

    // 发起GET请求
    fetchData();
  }

  void fetchData() async {
    try {
      Response response = await client.get(
        path: '/endpoint', // 替换为你的API端点
        queryParameters: {'key': 'value'}, // 可选的查询参数
      );

      // 处理响应数据
      setState(() {
        responseData = response.data.toString();
      });
    } catch (e) {
      // 处理错误
      print('Error fetching data: $e');
    }
  }

  void postData() async {
    try {
      Response response = await client.post(
        path: '/endpoint', // 替换为你的API端点
        body: {
          'key1': 'value1',
          'key2': 'value2',
        },
        headers: {
          'Content-Type': 'application/json',
        },
      );

      // 处理响应数据
      setState(() {
        responseData = response.data.toString();
      });
    } catch (e) {
      // 处理错误
      print('Error posting data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Rocket Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Response Data:'),
              if (responseData != null)
                Text(responseData!),
              ElevatedButton(
                onPressed: fetchData,
                child: Text('Fetch Data (GET)'),
              ),
              ElevatedButton(
                onPressed: postData,
                child: Text('Post Data (POST)'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们:

  1. pubspec.yaml中添加了flutter_rocket依赖。
  2. MyApp类的initState方法中初始化了RocketClient实例。
  3. 定义了fetchData方法来进行GET请求,并在UI中显示响应数据。
  4. 定义了postData方法来进行POST请求,并在UI中显示响应数据。
  5. 使用ElevatedButton组件来触发GET和POST请求。

请注意,你需要将baseUrl和API端点替换为你自己的API信息。此外,你还可以根据需求自定义请求头、查询参数和请求体。

这个示例展示了如何使用flutter_rocket进行基本的网络通信。如果你需要更高级的功能,如文件上传、下载、拦截器等,请参考flutter_rocket的官方文档以获取更多信息和示例。

回到顶部