Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 在Flatter应用程序中从firebase检索数据时_Flutter_Firebase Realtime Database_Dart - Fatal编程技术网

Flutter 在Flatter应用程序中从firebase检索数据时

Flutter 在Flatter应用程序中从firebase检索数据时,flutter,firebase-realtime-database,dart,Flutter,Firebase Realtime Database,Dart,这是密码 import 'package:flutter/material.dart'; import 'Authentication.dart'; import 'photoUpload.dart'; import 'Posts.dart'; import 'package:firebase_database/firebase_database.dart'; // import 'package:flutter_blogapp/Authentication.dart'; // import '

这是密码

import 'package:flutter/material.dart';
import 'Authentication.dart';
import 'photoUpload.dart';
import 'Posts.dart';
import 'package:firebase_database/firebase_database.dart';
// import 'package:flutter_blogapp/Authentication.dart';
// import 'package:flutter_blogapp/photoUpload.dart';


class HomePage extends StatefulWidget
{
  HomePage 
(
  {
    this.auth,
    this.onSignedOut,
  }
);
final AuthImplementation auth;
final VoidCallback onSignedOut;

  @override
  State<StatefulWidget> createState() 
  {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage>
{

  List<Posts> postsList = [];

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

    DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");

    postsRef.once().then((DataSnapshot snap)
    {
      var KEYS = snap.value.keys;
      var DATA = snap.value;

      postsList.clear();

      for(var individualKey in KEYS)
      {
        Posts posts = new Posts
        (
          DATA[individualKey]['image'],
          DATA[individualKey]['desctiption'],
          DATA[individualKey]['data'],
          DATA[individualKey]['time'], 
        );

        postsList.add(posts);
      }

      setState(() 
      {
        print('Length : $postsList.length');
      });
    });
  }

  void _logoutUser() async
  {
    try 
    {
      await widget.auth.signOut();
      widget.onSignedOut();
    } 
    catch (e) 
    {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) 
  {
    return new Scaffold
    (
      appBar:  new AppBar
      (
        title: new Text('Home'),
      ),
      
      
      body : new Container
      (
        child: postsList.length == 0 ? new Text(" No Post available ") : new ListView.builder
        (
          itemCount: postsList.length,
          itemBuilder: (_, index)
          //itemBuilder: (BuildContext _, int index ) //<-----
          {
            return PostsUI(postsList[index].image, postsList[index].description, postsList[index].date, postsList[index].time);
          }
        ),
      ),

      bottomNavigationBar: new BottomAppBar
      (
        color: Colors.pink,

        child: new Container
        (
          margin: const EdgeInsets.only(left: 70.0, right: 70.0),
          child: new Row
          (
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.max,

            children: <Widget>
            [
              new IconButton
              (
                icon: new Icon(Icons.local_car_wash),
                iconSize: 50,
                color: Colors.white, 

                onPressed: _logoutUser,

              ),

              new IconButton
              (
                icon: new Icon(Icons.add_a_photo),
                iconSize: 50,
                color: Colors.white,

                onPressed: ()
                {
                  Navigator.push
                  (
                    context, 
                    MaterialPageRoute(builder: (context)
                    {
                      return new UploadPhotoPage();
                    })
                  );
                },

              ),
            ],

          ),
        ),
      ),


    );
  }

                                                  // Designing Posts UI <remove from Text field><??'defaut value'>

  Widget PostsUI(String image, String description, String date, String time)
  {
    return new Card
    (
      elevation: 10.0,
      margin: EdgeInsets.all(15.0),


      child: new Container
      (
        padding: new EdgeInsets.all(14.0),

        child: new Column
        (
          crossAxisAlignment: CrossAxisAlignment.start,

          children: <Widget>
          [
            new Row
            (
              mainAxisAlignment: MainAxisAlignment.spaceBetween,

              children: <Widget>
              [
                new Text
                (
                  date,
                  style: Theme.of(context).textTheme.subtitle,
                  textAlign: TextAlign.center,
                ),

                new Text
                (
                  time,
                  style: Theme.of(context).textTheme.subtitle,
                  textAlign: TextAlign.center,
                ),                  //<----
              ],
            ),

            SizedBox(height: 10.0,),

            new Image.network(image, fit:BoxFit.cover),

            SizedBox(height: 10.0,),

            new Text
                (
                  description,  //= null ?  "true" : "False", //??'defaut value'
                  style: Theme.of(context).textTheme.subhead,
                  textAlign: TextAlign.center,
                ),


          ],

        )



      ) 

    );

  }
}
导入“包装:颤振/材料.省道”;
导入“Authentication.dart”;
导入“photoUpload.dart”;
导入“Posts.dart”;
导入“package:firebase_database/firebase_database.dart”;
//导入“package:flatter_blogapp/Authentication.dart”;
//导入“包:flatter_blogapp/photoUpload.dart”;
类主页扩展了StatefulWidget
{
主页
(
{
这个.auth,
这是我的名字,
}
);
最终授权执行授权;
最终作废回拨至已签出;
@凌驾
状态createState()
{
返回_HomePageState();
}
}
类_HomePageState扩展状态
{
列表postsList=[];
@凌驾
void initState()
{
super.initState();
DatabaseReference postsRef=FirebaseDatabase.instance.reference().child(“Posts”);
postsRef.one().then((DataSnapshot快照)
{
var KEYS=snap.value.KEYS;
var数据=snap.value;
postsList.clear();
for(var individualKey-in键)
{
员额=新员额
(
数据[individualKey]['image'],
数据[individualKey]['desctiption'],
数据[individualKey]['DATA'],
数据[individualKey][time'],
);
postsList.add(posts);
}
设置状态()
{
打印('Length:$postsList.Length');
});
});
}
void\u logoutUser()异步
{
尝试
{
等待widget.auth.signOut();
widget.onSignedOut();
} 
捕获(e)
{
打印(如toString());
}
}
@凌驾
小部件构建(构建上下文)
{
归还新脚手架
(
appBar:新的appBar
(
标题:新文本(“主页”),
),
主体:新容器
(
子项:postsList.length==0?新文本(“没有可用的Post”):new ListView.builder
(
itemCount:postsList.length,
itemBuilder:(\ux,索引)

//itemBuilder:(BuildContext,int index)//首先,将代码从initState中取出并放入另一个函数。这将保持initState干净。 我能看到的是你正在尝试更新firestore中的数据。 您可以做的是定义一个新函数,如下所示:

final databaseReference = Firestore.instance;

setPostsData() async {
  DocumentSnapshot snapshot = await databaseReference
      .collection("NAME_OF_COLLECTION")
      .document("NAME_OF_DOCUMENT")
      .get();
  // use this DocumentSnapshot snapshot to get the current data that is there in the document inside of your collection.
  var currentData = snapshot.data;
  print(currentData); // to check whats actually there and if its working...

  //lets assume newPostsList is the data that you want to put in this referenced document.
  //to update the data in firestore:
  await databaseReference
      .collection("NAME_OF_COLLECTION")
      .document("NAME_OF_DOCUMENT")
      .updateData({newPostsList});
}
然后可以将setPostsData置于initState


为此,您可能需要重新设计数据库结构,例如:它应该类似于用户-->帖子-->所有帖子的列表。如果这样做,则集合的名称将是用户,文档的名称将是帖子。

此日期和时间将出现在应用程序中,但描述和图像不会出现。