【问题标题】:Flutter: CRUD clarifications over FirebaseFlutter:对 Firebase 的 CRUD 澄清
【发布时间】:2020-09-05 11:23:09
【问题描述】:

自从我一周前开始学习 Flutter 以来,我一直在从事一个关于 Flutter 的小项目,我只是想知道如何从 Firebase 的 @ 中检索特定的 sn-p 数据987654322@数据库。

以下是相关文件的代码:

database.dart

import 'package:plannus/models/user.dart';

class DatabaseMethods {

  final String uid;
  DatabaseMethods({this.uid});

  final CollectionReference users = Firestore.instance.collection("users");


  Future<void> updateUserData(String name, String handle) async {
    print(uid);
    return await users.document(uid).updateData({
      'name' : name,
      'handle' : handle,
    });
  }

  Future<void> updateSpecificUserData(String uid, String name, String handle) async {
    print(uid);
    return await users.document(uid).updateData({
      'name' : name,
      'handle' : handle,
    });
  }

  Future<Set<Set<String>>> getUserData() {
    return users.document(uid).get().then((value) => {
      if (value.exists) {
        value.data['handle']
      }
    });
  }

  void getSpecificUserData(String uid, String capture) async {
    DocumentSnapshot snapshot =  await users.document(uid).get();
    capture = snapshot.data['handle'];
    print(capture);
  }

  Future<String> retrieveData(String uid) async {
    DocumentSnapshot snap = await users.document(uid).get();
    Map<String, String> map = snap.data;
    String handle = map['name'];
    return handle;
  }
//
  uploadUserInfo(userMap) {
    Firestore.instance.collection("users").add(userMap);
  }


  // user data from snapshot
  Stream<QuerySnapshot> get userInfo {
    return users.snapshots();
  }

}

profile.dart

import 'package:flutter/material.dart';
import 'package:plannus/messages/database.dart';
import 'package:plannus/models/user.dart';
import 'package:plannus/services/auth.dart';
import 'package:provider/provider.dart';

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {

  final AuthService auth = AuthService();
  final formKey = GlobalKey<FormState>(); // 'id' of form
  bool loading = false;
  // text field state
  String name = '';
  String password = '';
  String handle = '';
  String error = '';

  DatabaseMethods databaseMethods = new DatabaseMethods();
  QuerySnapshot currentUser;


  @override
  Widget build(BuildContext context) {

    User user = Provider.of<User>(context);
    String handle = '';
    print(user.uid);
    Future<String> str = databaseMethods.retrieveData(user.uid);
    str.then((value) => {
      handle = value
    });
    print(handle);
      return new Scaffold(
//          appBar: AppBar(
//            title:
//          ),
          body: Container(
            padding: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
            child: Form(
              key: formKey, // keep track of form and its state
              child : Column (
                children: <Widget>[
                  Image.asset('assets/profilepicture.png', height: 300, width: 300),
                  SizedBox(height: 20),
                  TextFormField(
                    decoration: InputDecoration(
                      hintText: 'Name',
                      icon: Icon(Icons.person_outline, color: Colors.blue),
                      fillColor: Colors.white,
                      filled: true,
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey[300], width: 2),
                      ),
                        focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue, width: 2),
                    )
                    ),
                    validator: (val) => val.isEmpty ? 'Enter your name' : null,
                    onChanged: (val) {
                      setState(() => name = val);
                    },
                  ),
                  SizedBox(height: 20),
                  TextFormField(
                    decoration: InputDecoration(
                        hintText: 'Handle',
                        icon: Icon(Icons.alternate_email, color: Colors.blue),
                        fillColor: Colors.white,
                        filled: true,
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey[300], width: 2),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.blue, width: 2),
                        )
                    ),
                    obscureText: false,
                    validator: (val) => val[0] != '@' ? 'Handle starts with @!' : null,
                    onChanged: (val) {
                      setState(() => handle = val);
                    },
                  ),
                  SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget> [
                      RaisedButton(
                        color: Colors.blueAccent,
                        child: Text(
                          'Update',
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () async {
                          if(formKey.currentState.validate()) {
                            print(user.uid);
                            await databaseMethods.updateSpecificUserData(user.uid, name, handle);
                            setState(() {
                              error = 'Update successful!';
                            });
                          }
                        },
                      ),
                    ],
                  ),
                  SizedBox(height: 12),
                  Text(
                    error,
                    style: TextStyle(color: Colors.black, fontSize: 16),
                  )
                ],
              ),
            ),
          ),
      );
    }
}

我的代码可能真的很混乱(对此我深表歉意,因为我已经坚持了很长时间,并且一直在严格尝试各种方法来提取数据)。

最终,我的主要目标是从我存储在 firebase 中的数据中获取值(句柄),然后将其动态显示在我的应用栏上。

我的 firebase 数据库集合名为“users”,仅包含数据 { name: "...", handle: "..."}。

感谢您接受我的长篇文章。

Profile page

【问题讨论】:

  • 大家好,我已经尝试使用下面的方法添加并在我的build 方法中设置状态,例如databaseMethods.getSpecificUserData(user.uid).then((value) =&gt; { setState(() =&gt; handle = value) }); ,其中.getSpecificUserData(user.uid) 是一个返回所需字符串但不幸的是手柄未打印在应用栏上。虽然控制台多次打印句柄中的值(打印语句在我的getSpecificUserData方法中)。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

以下是从 Firebase 的 Firestore 获取数据的方法。我认为最好将您的“名称”重命名为“n”,以使存储在数据库中的数据大小更小。

await Firestore.instance
    .collection('users')
    .document(uid)
    .get()
    .then((DocumentSnapshot ds) {
  username = ds["name"];
});

【讨论】:

  • 感谢您的建议。但它返回一个Future&lt;String&gt;,那么我该如何提取呢?我对 Dart 不太熟悉,不像 Java 的异步编程,它有 join/get 方法来提取值
  • @Rishi 使用 await 关键字来提取字符串,就像我在上面的答案中所做的那样。该视频可能对您有所帮助:youtube.com/watch?v=g9Uk1Xou0m4&t=627s
猜你喜欢
  • 2014-01-30
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多