Flutter功能建议提交插件suggest_a_feature_firestore的使用

Flutter功能建议提交插件suggest_a_feature_firestore的使用

整理后的内容

标题:Flutter功能建议提交插件suggest_a_feature_firestore的使用

内容如下:

<section class="tab-content detail-tab-readme-content -active markdown-body"><h1>Suggest a Feature Firestore</h<h>
<p align="center">
  <a href="https://flutter.wtf/" rel="ugc">
    <img alt="What the Flutter logo.svg (1 " src="https://static.tildacdn.com/tild6330-3461-4139-a63-666435336663/Group_1.svg" height="100/">
  </a>
</p>
<p align="center">
  </p><h2 align="center">Crafted with passion by
    <a href="https://flutter.wtf/" rel="ugc">
    What the Flutter
    </a> 🦜
  </h2>
<p></p>
<p align="center">
  <a href="https://pub.dartlang.org/packages/suggest_a_feature_firestore" rel="ugc">
    <img alt="Pub badge.svg" src="https://img.shields.io/pub/v/suggest_a_feature_firestore">
  </a>
  <a href="https://github.com/What-the-Flutter/Suggest-a-Feature-Firestore/actions/workflows/build.yml?query=workflow%3ABuild" rel="ugc">
    <img alt="Build Status badge.svg" src="https://github.com/What-the-Flutter/Suggest-a-Feature-Firestore/actions/workflows/build.yml/badge.svg?event=push">
  </a>
  <a href="https://www.codefactor.io/repository/github/what-the-flutter/suggest-a-feature-firestore/badge.svg?branch=master"
    rel="ugc">
    <img alt="CodeFactor badge.svg"
         src="https://www.codefactor.io/repository/github/what-the-flutter/suggest-a-feature-firestore/badge">
  </a>
</p>
<hr>
<p>This package is a data source extension for
<a href="https://pub.dev/packages/suggest_a_feature">suggest_a_feature</a> package.</p>
<h2>Getting started</h<h>
<pre><code class="language-yaml">dependencies:
  suggest_a_feature: ^latest version
  suggest_a_feature_firestore: ^latest version
</code></pre>
<p>You need to add Firebase to your project following steps described in this link from official firebase website:
<a href="https://console.firebase.google.com/" rel="ugc">https://console.firebase.google.com/</a></p>
<h2>Usage</h<h>
<p>You need to place <code>FirestoreDataSource</code> class as a <code>suggestionsDataSource</code> field in <code>SuggestionsPage</code> widget. Don't forget to place <code>FirebaseFirestore.instance</code> as <code>firestoreInstance</code> field in <code>FirestoreDataSource</code> class.
For example:</p>
<pre><code class="language-dart">SuggestionsPage(
  userId: '1',
  suggestionsDataSource: FirestoreDataSource(
    userId: '1',
    firestoreInstance: FirebaseFirestore.instance,
  ),
  theme: SuggestionsTheme.initial() ,
  onUploadMultiplePhotos: null,
  onSaveToGallery: null,
  onGetUserById: () {},
);
</code></pre>
<h2>Firestore rules</h<h>
<p>You also must add following rules to your <em>Firestore</em> in <em>Firebase Console</em>:</p>
<pre><code class="language-dart">match /suggest_a_feature_suggestions/{suggest_a_feature_suggestion}{
  allow read, write: if request.auth != null;
}

match /suggest_a_feature_comments/{suggest_a_feature_comment}{
  allow read, write: if request.auth != null;
}
</code></pre>
<ul>
<li>only if those rules are not defined for all lists</li>
</ul>
<h2>Pay your attention</h<h>
<p>For each delete or update suggestion action we check either user have author rights to fulfil those actions. Author rights is such a concept that only the user who created a suggestion can manipulate it (delete or update it). If somehow happens the situation when user without author rights will try to delete/update a suggestion will be thrown an Exception</p>
<p>We provide batch deleting of all the comments related to deleting suggestion in order save storage place and keep your firestore collections clean.</p>
<h2>Cloud Firestore</h<h>
<p>Data collections names in firebase firestore will be the following ones:</p>
<ul>
<li><strong>suggest_a_feature_suggestions</strong> for suggestions collection</li>
<li><strong>suggest_a_feature_comments</strong> for comments collection</li>
</ul>
</section>

示例代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:suggest_a_feature/suggest_a_feature.dart';
import 'package:suggest_a_feature_firestore/suggest_a_feature_firestore.dart';

void main() async {
  final dataSource = FirestoreDataSource(
    userId: 'user-id',
    firestoreInstance: FirebaseFirestore.instance,
  );

  final createSuggestionModel = CreateSuggestionModel(
    title: 'My suggestion',
    description: 'Here is what I think should be added to the app...',
    authorId: '',
    isAnonymous: true,
    labels: [],
  );
  final createdSuggestion =
      await dataSource.createSuggestion(createSuggestionModel);

  await dataSource.deleteSuggestionById(createdSuggestion.id);
}

使用说明

1 这个示例展示了如何使用 suggest_a_feature_firestore 插件来创建和删除功能建议。首先,你需要在你的项目中添加 suggest_a_feature_firestoresuggest_a_feature 包。然后,在 main.dart 文件中初始化 FirestoreDataSource 类,并将其作为 suggestionsDataSource 字段传递给 SuggestionsPage

以下是一个完整的示例:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:suggest_a_feature/suggest_a_feature.dart';
import 'package:suggest_a_feature_firestore/suggest_a_feature_firestore.dart';

void main() async {
  // 初始化 FirestoreDataSource
  final dataSource = FirestoreDataSource(
    userId: 'user-id', // 替换为实际的用户ID
    firestoreInstance: FirebaseFirestore.instance,
  );

  // 创建一个功能建议模型
  final createSuggestionModel = CreateSuggestionModel(
    title: 'My suggestion',
    description: 'Here is what I think should be added to the app...',
    authorId: '', // 可以设置为实际的作者ID
    isAnonymous: true,
    label: [], // 可以添加标签
  );

  // 创建功能建议
  final createdSuggestion = await dataSource.createSuggestion(createSuggestionModel);

  // 删除功能建议
  await dataSource.deleteSuggestionById(createdSuggestion.id);
}

更多关于Flutter功能建议提交插件suggest_a_feature_firestore的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter功能建议提交插件suggest_a_feature_firestore的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter的suggest_a_feature_firestore插件(假设这是一个用于向Firestore提交功能建议的自定义插件)的示例代码。请注意,由于suggest_a_feature_firestore并非一个真实存在的官方插件,这里的代码将模拟其功能,展示如何与Firestore交互来提交功能建议。

首先,确保你的Flutter项目已经集成了Firebase和Firestore。你可以按照Firebase的官方文档进行集成。

1. 添加Firebase依赖

在你的pubspec.yaml文件中添加Firebase和Firestore的依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0 # 确保使用最新版本
  cloud_firestore: ^3.1.0 # 确保使用最新版本

2. 初始化Firebase

在你的main.dart文件中初始化Firebase:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FeatureSuggestionScreen(),
    );
  }
}

3. 创建功能建议提交页面

创建一个新的Dart文件,例如feature_suggestion_screen.dart,并编写以下代码:

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

class FeatureSuggestionScreen extends StatefulWidget {
  @override
  _FeatureSuggestionScreenState createState() => _FeatureSuggestionScreenState();
}

class _FeatureSuggestionScreenState extends State<FeatureSuggestionScreen> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  void _submitSuggestion() async {
    // 获取当前用户(假设已经进行了用户认证)
    // User? user = FirebaseAuth.instance.currentUser;

    // 提交功能建议到Firestore
    await FirebaseFirestore.instance.collection('featureSuggestions').add({
      'title': _titleController.text,
      'description': _descriptionController.text,
      // 'userId': user?.uid, // 如果需要记录提交用户的ID
      'timestamp': FieldValue.serverTimestamp(),
    });

    // 清除控制器内容
    _titleController.clear();
    _descriptionController.clear();

    // 显示提交成功的Snackbar
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('功能建议已提交!')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('提交功能建议'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: _titleController,
              decoration: InputDecoration(labelText: '标题'),
            ),
            SizedBox(height: 16),
            TextField(
              controller: _descriptionController,
              maxLines: 6,
              decoration: InputDecoration(labelText: '描述'),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: _submitSuggestion,
              child: Text('提交'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 运行应用

确保你已经按照Firebase的文档配置了你的Firestore数据库,然后运行你的Flutter应用。你现在应该能够看到一个界面,允许你输入功能建议的标题和描述,并提交到Firestore中。

注意

  • 上述代码示例假设用户已经通过Firebase Authentication进行了认证,并且你的应用有权访问Firestore。如果尚未进行用户认证,你需要先实现用户认证功能。
  • FieldValue.serverTimestamp()用于在Firestore中记录提交时间。
  • 根据实际需求,你可能需要调整Firestore集合的名称和字段。

这个示例展示了如何使用Flutter和Firestore来提交功能建议,尽管suggest_a_feature_firestore插件是假设的,但这个过程适用于任何需要与Firestore交互的场景。

回到顶部