如何从Cloud Firestore获取Flutter App的简单数据?

问题描述 投票:0回答:1

当我运行得到以下错误。这些是进入firebase的基本代码。

以下断言被抛出构建MyHomePage(dirty,state:MyHomePageState#b163a):'package:flutter / src / widgets / text.dart':断言失败:第235行pos 15:'data!= null':不是

请,任何人都可以帮助我如何解决这个问题?

import 'dart:async';

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

Future<void> main() async {
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'vscodefirebase',
    options: const FirebaseOptions(
      googleAppID: 'xxx',
      gcmSenderID: 'xxx',
      apiKey: 'xxxx',
      projectID: 'vscodefirebase',
    ),
  );
  final Firestore firestore = Firestore(app: app);
  await firestore.settings(timestampsInSnapshotsEnabled: true);

  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection('books').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) return new Text('Loading...');
          return new ListView(
            children: snapshot.data.documents.map((DocumentSnapshot document) {
              return new ListTile(
                title: new Text(document['title']),
                subtitle: new Text(document['author']),
              );
            }).toList(),
          );
        },
      ),
    );
  }
}
firebase flutter google-cloud-firestore flutter-dependencies
1个回答
1
投票

您有一个带有空文本的文本小部件。

在这里,您没有输入MyHomePage的title属性

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

因此,此Text小部件具有空文本值。

  appBar: AppBar(
    title: Text(widget.title),
  ),

要解决此问题,请像这样声明MyHomePage:

MyHomePage(title: "My Home Page")
© www.soinside.com 2019 - 2024. All rights reserved.