将数据从 Flutter Stream 传递到小部件

Posted

技术标签:

【中文标题】将数据从 Flutter Stream 传递到小部件【英文标题】:Pass data from Flutter Stream to widget 【发布时间】:2021-10-12 01:59:21 【问题描述】:

我正在尝试研究如何将数据从流传递到小部件以显示元素

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

class BrowseTasks extends StatefulWidget 
  static final String id = 'feed_screen';
  final String currentUserId;

  BrowseTasks(this.currentUserId);

  @override
  _BrowseTasksState createState() => _BrowseTasksState();


class _BrowseTasksState extends State<BrowseTasks> 
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('tasks').snapshots();

  Widget _buildTask(data) 
    return GestureDetector(
        onTap: () ,
        child: Card(
          clipBehavior: Clip.antiAlias,
          child: Column(
            children: [
              ListTile(
                leading: CircleAvatar(
                  backgroundColor: Color.fromRGBO(108, 212, 196, 1),
                  // backgroundImage: _displayProfileImage(),
                  child: Text(
                    'P',
                    style: TextStyle(
                      fontSize: 25.0,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  foregroundColor: Colors.white,
                ),
                title: Text(
                    data.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis),
                trailing:
                    Text(data.budget, style: Theme.of(context).textTheme.headline5),

              ),
              Divider(),
              ListTile(
                leading: Text(data.owner),
                trailing: Icon(Icons.location_on_outlined),
              ),

              ButtonBar(
                alignment: MainAxisAlignment.start,
                children: [
                  TextButton(
                    // textColor: const Color(0xFF6200EE),
                    onPressed: () 
                      // Perform some action
                    ,
                    child: const Text('ACTION 1'),
                  ),
                  TextButton(
                    // textColor: const Color(0xFF6200EE
                    // ),
                    onPressed: () 
                      // Perform some action
                    ,
                    child: const Text('ACTION 2'),
                  ),
                ],
              ),
              // Image.asset('assets/card-sample-image.jpg'),
            ],
          ),
        ));
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text('Browse task'),
          bottom: PreferredSize(
              child: Container(
                color: Theme.of(context).primaryColor,
                height: 3.0,
              ),
              preferredSize: Size.fromHeight(4.0)),
          elevation: 0,
        ),
        body: StreamBuilder<QuerySnapshot>(
            stream: _usersStream,
            builder: (context, snapshot) 
              print('Has error: $snapshot.hasError');
              print('Has data: $snapshot.hasData');
              print('Snapshot Data $snapshot.data.docs');
              print('Connection State $snapshot.connectionState');
              if (snapshot.hasError) print(snapshot.error);

              if (snapshot.connectionState == ConnectionState.waiting) 
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircularProgressIndicator(
                          valueColor:
                              new AlwaysStoppedAnimation<Color>(Colors.blue)),
                      // Loader Animation Widget
                      Padding(padding: const EdgeInsets.only(top: 20.0)),
                      Text('Finding tasks'),
                    ],
                  ),
                );
              

              if (snapshot.hasData) 
                final documents = snapshot.data.docs;
                return ListView(
                    children: documents
                        .map(
                          (doc) => _buildTask(doc),
                        )
                        .toList());
               else if (snapshot.hasError) 
                return Text('It\'s Error!');
              
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('Unable to  find any tasks'),
                  ],
                ),
              );
            ));
  

【问题讨论】:

您好,您还没有这样做吗?您的代码中是否有错误? 【参考方案1】:

如果您在任务集合中有名为“name”的字段名称,请尝试此操作

class BrowseTasks extends StatefulWidget 
static final String id = 'feed_screen';
final String currentUserId;

BrowseTasks(this.currentUserId);

@override
_BrowseTasksState createState() => _BrowseTasksState();


class _BrowseTasksState extends State<BrowseTasks> 
final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('tasks').get();

Widget _buildTask(data) 
    return GestureDetector(
    onTap: () ,
    child: Card(
      clipBehavior: Clip.antiAlias,
      child: Column(
        children: [
          ListTile(
            leading: CircleAvatar(
              backgroundColor: Color.fromRGBO(108, 212, 196, 1),
              // backgroundImage: _displayProfileImage(),
              child: Text(
                'P',
                style: TextStyle(
                  fontSize: 25.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
              foregroundColor: Colors.white,
            ),
            title: Text(
                data.title,
                maxLines: 2,
                overflow: TextOverflow.ellipsis),
            trailing:
                Text(data.budget, style:         Theme.of(context).textTheme.headline5),

          ),
          Divider(),
          ListTile(
            leading: Text(data.owner),
            trailing: Icon(Icons.location_on_outlined),
          ),

          ButtonBar(
            alignment: MainAxisAlignment.start,
            children: [
              TextButton(
                // textColor: const Color(0xFF6200EE),
                onPressed: () 
                  // Perform some action
                ,
                child: const Text('ACTION 1'),
              ),
              TextButton(
                // textColor: const Color(0xFF6200EE
                // ),
                onPressed: () 
                  // Perform some action
                ,
                child: const Text('ACTION 2'),
              ),
            ],
          ),
          // Image.asset('assets/card-sample-image.jpg'),
        ],
      ),
    ));


@override
Widget build(BuildContext context) 
return Scaffold(
    appBar: AppBar(
      title: Text('Browse task'),
      bottom: PreferredSize(
          child: Container(
            color: Theme.of(context).primaryColor,
            height: 3.0,
          ),
          preferredSize: Size.fromHeight(4.0)),
      elevation: 0,
    ),
    body: StreamBuilder<QuerySnapshot>(
        stream: _usersStream,
        builder: (context, snapshot) 
          print('Has error: $snapshot.hasError');
          print('Has data: $snapshot.hasData');
          print('Snapshot Data $snapshot.data.docs');
          print('Connection State $snapshot.connectionState');
          if (snapshot.hasError) print(snapshot.error);

          if (snapshot.connectionState == ConnectionState.waiting) 
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  CircularProgressIndicator(
                      valueColor:
                          new AlwaysStoppedAnimation<Color>(Colors.blue)),
                  // Loader Animation Widget
                  Padding(padding: const EdgeInsets.only(top: 20.0)),
                  Text('Finding tasks'),
                ],
              ),
            );
          

          if (snapshot.hasData) 
           
            return ListView(
                children: snapshot.data.docs.map((document)
          Map<String, dynamic> data = document.data() as Map<String,   dynamic>;
                    ListTile(title:Text(data['name'])

                    ).toList());
           else if (snapshot.hasError) 
            return Text('It\'s Error!');
          
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Unable to  find any tasks'),
              ],
            ),
          );
        ));
     
  

【讨论】:

这让我成功了。我做了一些改变,但这对我帮助很大

以上是关于将数据从 Flutter Stream 传递到小部件的主要内容,如果未能解决你的问题,请参考以下文章

Flutter - 从 Stream 接收然后修改数据

使用 Stream 从 FireStore 获取数据并将其映射到 Flutter 类

如何将数据从 showmodalbottomsheet 传递到 Flutter 中的上一页

将数据从另一个类传递到另一个类 onPressed Flutter

如何在 FLutter 中使用 pushNamed 将数据从一个屏幕传递到另一个屏幕?

从 Stream (Flutter) 控制轮播滑块