【问题标题】:Flutter: How to display a text from Firebase?Flutter:如何显示来自 Firebase 的文本?
【发布时间】:2021-10-29 02:13:58
【问题描述】:

我进行了很多搜索,但找不到针对此特定问题的解决方案: 所以我想在我的颤振应用程序中显示一个文本。但是这个文本应该是可变的,所以我将 Firebase 集成到我的项目中。一切都运行良好,所以我已经设法显示来自 Firebase 的图像,但我真的不知道如何显示文本。

你能告诉我怎么做吗?也许有人可以告诉我我需要用来完成这项工作的代码?

这是我目前的代码,我没有集成具体的代码来与我的 Firebase 后端通信,因为我不知道该怎么做。

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

class MapsPage extends StatefulWidget {
  MapsPage({Key key}) : super(key: key);
  @override
  _MapsPageState createState() => _MapsPageState();
}

class _MapsPageState extends State<MapsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase'),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0xffFBD23E), Color(0xffF6BE03)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
        ),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Color(0xffFEFDFD), Color(0xffBDBDB2)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight),
        ),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: RichText(
                text: TextSpan(
                  style: TextStyle(color: Colors.black),
                  text: 'Some text',
                  children: [
                    TextSpan(
                      text:
                          'I want this TextSpan to be variable. So if I change the data in my Firestore Database this text shall also change.',
                    ),
                    TextSpan(
                      text: 'And some more text.',
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

你能帮帮我吗?非常感谢!!

下面是我的firestore的截图。

.

【问题讨论】:

  • 所以获取文本然后使用setState(() {});。如果你有图片,文字应该不会更难。

标签: ios firebase flutter dart google-cloud-firestore


【解决方案1】:

// This below returns the text
Future<Map<String, dynamic>> getData() async {
  DocumentReference<Map<String, dynamic>> document =
      FirebaseFirestore.instance.doc('KBADatum/6j5Fnvj0gNkSCRIx7ecH'); // path to doc
  DocumentSnapshot<Map<String, dynamic>> query = await document.get();
  print(query.data());
  return query.data();
}

// and this is how you consume it.
FutureBuilder<Map<String, dynamic>>(
  future: getData(),
  builder: (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
    if (snapshot.hasError) return CircularProgressIndicator();
    if (snapshot.connectionState == ConnectionState.waiting)
      return CircularProgressIndicator();

    return RichText(
      text: TextSpan(
        style: TextStyle(color: Colors.black),
        text: 'Some text',
        children: [
          TextSpan(
            text: snapshot.data['DatumJahr'], // first text
          ),
          TextSpan(
            text: 'And some more text.',
          ),
        ],
      ),
    );
  },
)

【讨论】:

  • 非常感谢!我已经尝试过了,但它显示了一个邀请并且永无止境的 CircularProgressIndicator。我到底需要用什么替换 ['variable holding text']?
  • 永无止境的 CircularProgressIndicator?将第一个 CircularProgressIndicator 替换为:Text('an error occurred')。现在如果发生错误,你会知道的。 ['variable holding text'] 应替换为您想要在 firestore 上使用的变量的名称。
  • 我已经添加了一个截图,所以现在我希望它更容易理解。我刚刚添加了文本('发生错误'),这就是它向我展示的内容。至于我使用 DatumMonat 的变量。那正确吗?因为它仍然不起作用。
  • 您应该将屏幕截图添加到您的问题中,而不是我的答案中。不过,我已经更新了我的答案(使用您的文档路径 - KBADatum/6j5Fnvj0gNkSCRIx7ecH - 和您的第一个文本 - DatumJahr)。您应该能够在不更改任何内容的情况下使用答案。
【解决方案2】:

snapshots() 方法提供了一个流,您可以订阅该流以获取最新的文档更改。要使用流更新您的 ui,您可以使用 StreamBuilder,它基于最新的交互快照构建自己。

最后一件事是您不能将 StreamBuilder 用作 TextSpan 的子项。因此,您将重建 RichText 小部件或使用 WidgetSpan 仅在您的流中有事件时重建跨度。

这是一个例子:

RichText(
  text: TextSpan(
    style: TextStyle(color: Colors.black),
    text: 'Some text',
    children: [
      // Use WidgetSpan instead of TextSpan, which allows you to have a child widget
      WidgetSpan(
        // Use StreamBuilder to listen on the changes of your Firestore document.
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: FirebaseFirestore.instance
          .collection('my_collection')
          .doc('my_document')
          .snapshots(),
          builder: (context, snapshot) {
            final document = snapshot.data; // Get the document snapshot
            final text = document?.data()?['my_text']; // Get the data in the text field 

            return Text(text ?? 'Loading...'); // Show loading if text is null
          },
        ),
      ),
      TextSpan(
        text: 'And some more text.',
      ),
    ],
  ),
)

注意:我尽量保持示例简单,但您可以了解有关 StreamBuilder 处理错误/数据和连接状态的更多信息。

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2012-01-23
    • 2018-10-30
    • 2021-01-05
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多