Flutter Strapi集成插件simple_strapi的使用

Flutter Strapi 集成插件 simple_strapi 的使用

简介

一个为 Dart 开发者设计的 Strapi 库。通过它可以执行基本的查找、单个查找、计数等查询,以及复杂的图形查询。这是一个基础包,强烈推荐与 super_strapi 一起使用,后者支持从 Strapi 模型生成 Dart 类。

使用方法

配置

首先,需要配置 Strapi 插件的基本设置:

Strapi.i.host = "strapi.example.com";
Strapi.i.shouldUseHttps = true;
Strapi.i.verbose = false;
Strapi.i.maxListenersForAnObject = 8;

登录和注册

要使用 authenticateWithFirebaseUid 方法,首先需要在 Strapi 中添加一个启用 Firebase SDK 的自定义提供商,否则会收到 “This provider is disabled.” 的响应。你可以在这里了解如何将 Firebase 添加为认证方法:如何在 Strapi 中使用 Firebase 进行认证。目前,这是唯一支持的认证方法(因为我们项目只需要这一个,其他提供商将在后续版本中支持)。

示例代码如下:

final response = await Strapi.i.authenticateWithFirebaseUid(
  firebaseUid: firebaseToken,
  email: email,
  name: name,
);

if (response.failed) {
  print("登录失败");
  print(response);
} else {
  // 获取 JWT 令牌
  final jwt = response.body.first["jwt"];
}

注意:一旦登录成功,库会自动将 JWT 包含在未来的请求中。但是,JWT 令牌不会在应用重启后持久化。你需要负责保存并重新加载它,在下次应用启动时加载:

Strapi.i.strapiToken = "<your_saved_jwt>";

基本查询

Strapi 的基本查询如查找、单个查找、计数、删除、更新和创建等都由 StrapiCollection 支持:

final restaurants = await StrapiCollection.findMultiple(
  collection: "restaurants",
  limit: 20,
);

复杂图形查询

复杂图形查询应该是一个全新的主题,但这里我们来了解一下。

图形查询针对 Strapi 集合或引用列表(类似于 Strapi 中的可重复引用)。你可以根据数据结构中的引用字段进行嵌套。只有根查询需要 [collectionName],附加到根查询的任何 [collectionName] 都会被忽略,因为查询将针对字段名称。可以通过 [requiredFields] 来指定响应中包含的字段,[limit] 是响应中最大文档数量,[start] 可用于分页查询。

假设你有以下集合模型:

A 模型

{
  "id": "<value>",
  "name": "<value>",
  "single_reference_for_B": "<id>",
  "repeatable_reference_for_C": ["<id>", "<id>", ...],
}

B 模型

{
  "id": "<value>",
  "dob": "<value>",
}

C 模型

{
  "id": "<value>",
  "place": "<value>",
}

对于上述集合模型,如果你正在对集合 A 进行图形查询,可以这样传递所需的字段:

final query = StrapiCollectionQuery(
  collectionName: "A",
  requiredFields: [
    StrapiLeafField("id"),
    StrapiLeafField("name"),
  ],
);

// 对于 [StrapiLeafField],可以这样过滤,此查询返回只包含 id 的对象(必须返回一个)
// 查看 [StrapiFieldQuery] 以了解所有过滤可能性
query.whereField(
  field: StrapiLeafField("id"),
  query: StrapiFieldQuery.equalTo,
  value: "<value>",
);

你不能要求 fields single_reference_for_Brepeatable_reference_for_C,因为它们是引用。如果需要获取它们,必须嵌套查询,例如:

// 如果引用是单个引用,则使用 [StrapiModelQuery]
query.whereModelField(
  field: StrapiModelField("single_reference_for_B"),
  query: StrapiModelQuery(
    requiredFields: [
      StrapiLeafField("id"),
      StrapiLeafField("dob"),
    ],
  ),
);

// 如果引用是可重复引用(即前面提到的引用列表),则使用 [StrapiCollectionQuery]
query.whereCollectionField(
  field: StrapiCollectionField("repeatable_reference_for_C"),
  query: StrapiCollectionQuery(
    collectionName: "C",
    requiredFields: [
      StrapiLeafField("id"),
      StrapiLeafField("place"),
    ],
  ),
);

查询执行方式如下:

final strapiResponse = Strapi.i.graphRequest(queryString: query.query);

注意:目前 Strapi 支持嵌套图形查询最多 20 层。

注意:目前 Strapi 不支持查询组件,这不是 Strapi 当前支持的功能。

因此,要将它们包含在响应中,必须显式地传递字段名称,例如:

requireComponentField(
  field: StrapiComponentField("someField"),
  fields: "{ componentFieldA, componentFieldB, componentFieldC }",
);

示例代码

以下是完整的示例代码,演示了如何使用 simple_strapi 插件:

import 'package:simple_strapi/simple_strapi.dart';

void main() async {
  // 配置 Strapi 插件
  Strapi.i.host = "strapi.example.com";
  Strapi.i.shouldUseHttps = true;
  Strapi.i.verbose = false;
  Strapi.i.maxListenersForAnObject = 8;

  // 登录
  final response = await Strapi.i.authenticateWithFirebaseUid(
    firebaseUid: "firebaseToken",
    email: "email@example.com",
    name: "User Name",
  );

  if (response.failed) {
    print("登录失败");
    print(response);
  } else {
    // 获取 JWT 令牌
    final jwt = response.body.first["jwt"];
    print("登录成功,JWT: $jwt");

    // 设置 JWT 令牌
    Strapi.i.strapiToken = jwt;

    // 执行基本查询
    final restaurants = await StrapiCollection.findMultiple(
      collection: "restaurants",
      limit: 20,
    );
    print("餐厅列表: $restaurants");

    // 构建复杂的图形查询
    final query = StrapiCollectionQuery(
      collectionName: "A",
      requiredFields: [
        StrapiLeafField("id"),
        StrapiLeafField("name"),
      ],
    );

    query.whereField(
      field: StrapiLeafField("id"),
      query: StrapiFieldQuery.equalTo,
      value: "someValue",
    );

    query.whereModelField(
      field: StrapiModelField("single_reference_for_B"),
      query: StrapiModelQuery(
        requiredFields: [
          StrapiLeafField("id"),
          StrapiLeafField("dob"),
        ],
      ),
    );

    query.whereCollectionField(
      field: StrapiCollectionField("repeatable_reference_for_C"),
      query: StrapiCollectionQuery(
        collectionName: "C",
        requiredFields: [
          StrapiLeafField("id"),
          StrapiLeafField("place"),
        ],
      ),
    );

    final strapiResponse = Strapi.i.graphRequest(queryString: query.query);
    print("图形查询结果: $strapiResponse");
  }
}

更多关于Flutter Strapi集成插件simple_strapi的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Strapi集成插件simple_strapi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


simple_strapi 是一个用于在 Flutter 应用中与 Strapi 后端集成的插件。它简化了与 Strapi API 的交互,使得在 Flutter 应用中获取、创建、更新和删除数据变得更加容易。

安装 simple_strapi

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

dependencies:
  flutter:
    sdk: flutter
  simple_strapi: ^1.0.0  # 请确保使用最新版本

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

初始化 simple_strapi

在使用 simple_strapi 之前,你需要在你的 Flutter 应用中初始化它。通常在 main.dart 中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 SimpleStrapi
  await SimpleStrapi.initialize(
    baseUrl: 'https://your-strapi-instance.com', // 你的 Strapi 实例的 URL
  );
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Strapi Flutter Demo',
      home: HomeScreen(),
    );
  }
}

使用 simple_strapi

1. 获取数据

你可以使用 SimpleStrapi 来从 Strapi 获取数据。例如,获取所有的文章:

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<dynamic> articles = [];

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

  Future<void> fetchArticles() async {
    try {
      var response = await SimpleStrapi.instance.get('articles'); // 获取所有文章
      setState(() {
        articles = response['data'];
      });
    } catch (e) {
      print('Error fetching articles: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Strapi Articles'),
      ),
      body: ListView.builder(
        itemCount: articles.length,
        itemBuilder: (context, index) {
          var article = articles[index];
          return ListTile(
            title: Text(article['attributes']['title']),
            subtitle: Text(article['attributes']['description']),
          );
        },
      ),
    );
  }
}

2. 创建数据

你可以使用 post 方法来创建新的数据。例如,创建一篇新文章:

Future<void> createArticle() async {
  try {
    var response = await SimpleStrapi.instance.post(
      'articles',
      data: {
        'data': {
          'title': 'New Article',
          'description': 'This is a new article created from Flutter.',
        },
      },
    );
    print('Article created: ${response['data']}');
  } catch (e) {
    print('Error creating article: $e');
  }
}

3. 更新数据

你可以使用 putpatch 方法来更新数据。例如,更新一篇文章:

Future<void> updateArticle(String id) async {
  try {
    var response = await SimpleStrapi.instance.put(
      'articles/$id',
      data: {
        'data': {
          'title': 'Updated Article',
          'description': 'This article has been updated from Flutter.',
        },
      },
    );
    print('Article updated: ${response['data']}');
  } catch (e) {
    print('Error updating article: $e');
  }
}

4. 删除数据

你可以使用 delete 方法来删除数据。例如,删除一篇文章:

Future<void> deleteArticle(String id) async {
  try {
    await SimpleStrapi.instance.delete('articles/$id');
    print('Article deleted');
  } catch (e) {
    print('Error deleting article: $e');
  }
}
回到顶部