Listview 如何从函数内部检索Firestore数据?

Listview 如何从函数内部检索Firestore数据?,listview,flutter,dart,google-cloud-firestore,string-interpolation,Listview,Flutter,Dart,Google Cloud Firestore,String Interpolation,我试图从一个按钮调用函数中的firestore数据,集合的标题。当我刚在一个onPressed中使用它时,它就起作用了: Expanded( child: IconButton( icon: Icon( Icons.share, onPressed: () => Share.share( '${(snapshot.data.documents[index]['title'])}', //this displays th

我试图从一个按钮调用函数中的firestore数据,集合的标题。当我刚在一个onPressed中使用它时,它就起作用了:

Expanded(
   child: IconButton(
      icon: Icon(
        Icons.share,
         onPressed: () => Share.share(
         '${(snapshot.data.documents[index]['title'])}',  //this displays the 'title' 
fields of my firestore collections in ListView
         ))),
但是,当尝试从函数(在不同的共享插件中)调用时,无论我尝试什么,都只打印实际代码而不是内容,如何在下面的函数中检索firestore集合的“标题”,我认为字符串插值${像这样}是唯一的方法,但它不适用于此:

MaterialButton(
              child: Text('Share text'),
              onPressed: () async => await _shareText(),
            ),
功能:

Future<void> _shareText() async {
try {
  Share.text('my text title',
      'HERE => This is my text to share with other applications.', 'text/plain');  
// no variation of ${snapshot.data.documents[index]['title']} works here
} catch (e) {
  print('error: $e');
}}
还有别的办法叫这个吗

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'dart:ui';
import 'package:google_fonts/google_fonts.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:async';
import 'image.dart';


class Recipe extends StatefulWidget {
@override
_RecipeState createState() => _RecipeState();
}

class _RecipeState extends State<Recipe> {
 var firestoreDb = Firestore.instance.collection("recipes").snapshots();



  // THIS ${(snapshot.data.documents[index].data['title'])} does not work in 
  share plugin:
Future<void> _shareText() async {
try {
  Share.text('Share Text ',
      '${(snapshot.data.documents[index].data['title'])}', 'text/plain');
} catch (e) {
  print('error: $e');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Recipes',
                style: GoogleFonts.lato(
                  fontSize: 22.0,
                  color: Colors.amberAccent.shade50,
                ),
              )),
          IconButton(
            icon: Icon(MdiIcons.foodForkDrink, color: Color(0xffffe0b2), 
size: 32.0),
            onPressed: () {
             null;
            },
          ),
        ]),
    backgroundColor: Colors.lightBlue,
    elevation: 50.0,
  ), //AppBar

  body: Container(
    width: MediaQuery.of(context).size.width,
    child: StreamBuilder(
        stream: firestoreDb,
        builder: (context, snapshot) {
          if (!snapshot.hasData) Text('Loading...');
          return StaggeredGridView.countBuilder(
            crossAxisCount: 2,
            mainAxisSpacing: 1.0,
            crossAxisSpacing: 1.0,
            padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 6.0),
            shrinkWrap: true,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, int index) => Container(
              child: Column(
                children: <Widget>[
                  Card(
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.0),
                    ),

                    child: Column(children: <Widget>[
                      ListTile(
                        title: Text(
                          '${(snapshot.data.documents[index]['title'])}',
                          style: GoogleFonts.lato(
                            fontSize: 20.0,
                            height: 1.2,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),

                        subtitle: Row(
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[



                              MaterialButton(
                                child: Text('Share text'),
                                onPressed: () async => await _shareText(),
                              ),

                              SizedBox(height: 5.0),
                              ImageInput(),  //this displays image called 
from image_picker to share , it works for sharing an image. 


                              Expanded(
                                child: Text(
                                  '${(snapshot.data.documents[index] 
   ['subtitle'])}',
                                  textAlign: TextAlign.right,
                                  style: GoogleFonts.lato(
                                    fontSize: 13.0,
                                    fontWeight: FontWeight.w900,
                                    fontStyle: FontStyle.italic,
                                    color: Colors.blue,
                                  ),
                                ), //subtitle: Text
                              ),
                            ] //children
                        ), //Row
                      ), //listtile
                    ]),
                  ),
                ],
              ),
            ),
            staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
          );
        }),
  ),
);
} //build
} //class
import'包装:flift/cupertino.dart';
进口“包装:颤振/材料.省道”;
导入“包:cloud_firestore/cloud_firestore.dart”;
导入“包:颤振交错网格视图/颤振交错网格视图.省道”;
导入“dart:ui”;
导入“package:google_fonts/google_fonts.dart”;
导入“包装:材料\设计\图标\颤振/材料\设计\图标\颤振.dart”;
导入“包:esys_flatter_share/esys_flatter_share.dart”;
导入“dart:async”;
导入“image.dart”;
类Recipe扩展了StatefulWidget{
@凌驾
_RecipeState createState()=>\u RecipeState();
}
类_RecipeState扩展状态{
var firestoreDb=Firestore.instance.collection(“recipes”).snapshots();
//此${(snapshot.data.documents[index].data['title'])}在中不起作用
共享插件:
Future\u shareText()异步{
试一试{
Share.text('Share text',
“${(snapshot.data.documents[index.data['title'])}”,“text/plain”);
}捕获(e){
打印('error:$e');
}
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:世界其他地区(
mainAxisAlignment:mainAxisAlignment.space,
儿童:[
容器(
填充:常数边集全部(8.0),
子:文本(
“食谱”,
风格:GoogleFonts.lato(
字体大小:22.0,
颜色:Colors.amberAccent.shade50,
),
)),
图标按钮(
图标:图标(MDICONS.FoodWorkDrink,颜色:颜色(0xffffe0b2),
尺寸:32.0),
已按下:(){
无效的
},
),
]),
背景颜色:颜色。浅蓝色,
标高:50.0,
),//AppBar
主体:容器(
宽度:MediaQuery.of(context).size.width,
孩子:StreamBuilder(
流:firestoreDb,
生成器:(上下文,快照){
如果(!snapshot.hasData)文本('Loading…');
返回EdgridView.countBuilder(
交叉轴计数:2,
主轴间距:1.0,
交叉轴间距:1.0,
填充:边缘组。对称(水平:2.0,垂直:6.0),
收缩膜:对,
itemCount:snapshot.data.documents.length,
itemBuilder:(上下文,int索引)=>容器(
子:列(
儿童:[
卡片(
颜色:颜色,白色,
形状:圆形矩形边框(
边界半径:边界半径。圆形(12.0),
),
子项:列(子项:[
列表砖(
标题:正文(
“${(snapshot.data.documents[index]['title'])}”,
风格:GoogleFonts.lato(
字体大小:20.0,
身高:1.2,
fontWeight:fontWeight.w500,
),
textAlign:textAlign.center,
),
字幕:世界其他地区(
mainAxisSize:mainAxisSize.max,
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
材料按钮(
子项:文本(“共享文本”),
onPressed:()async=>wait _shareText(),
),
尺寸箱(高度:5.0),
ImageInput(),//显示调用的图像
从图像选择器到共享,它用于共享图像。
扩大(
子:文本(
'${(snapshot.data.documents[索引]
['subtitle'])},
textAlign:textAlign.right,
风格:GoogleFonts.lato(
字体大小:13.0,
fontWeight:fontWeight.w900,
fontStyle:fontStyle.italic,
颜色:颜色,蓝色,
),
),//副标题:文本
),
]//儿童
),//行
),//listtile
]),
),
],
),
),
交错文件生成器:(int索引)=>交错文件.fit(2),
);
}),
),
);
}//构建
}//类
我将ImageInput()类页面复制到主页中,因为我无法将图像和文本一起共享,我仍然在共享文本字段中看到文本和快照的“未定义”错误。同样的修正对文本不起作用,尽管它现在在同一页上。我做错了什么

MaterialButton(
      child: Text('Send it!'),
      onPressed: () async => await _shareImageAndText(snapshot, index),
    ),

---

Future<void> _shareImageAndText(snapshot, index) async {
try {
  List<int> imageBytes = await _imageFile.readAsBytes();
  var uint8List = Uint8List.fromList(imageBytes);
  await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
      text: (snapshot.data.documents[index].data['title']) );
      //text: 'My optional text.');
  // (snapshot.data.documents[index].data['title']), 'text/plain');
  } catch (e) {
  print('error: $e');
  }}
MaterialButton(
孩子:文本('Send it!'),
onPressed:()async=>wait _shareImageAndText(快照、索引),
),
---
Future\u shareImageAndText(快照、索引)异步{
试一试{
List imageBytes=wait_imageFile.readAsBytes();
var uint8List=uint8List.fromList(imageBytes);
等待Share.file('esys image','esys.jpg',uint8List',image/jpeg',
text:(snapshot.data.documents[index].data['title']);
//文本:“我的可选文本”。);
//(快照)
MaterialButton(
      child: Text('Send it!'),
      onPressed: () async => await _shareImageAndText(snapshot, index),
    ),

---

Future<void> _shareImageAndText(snapshot, index) async {
try {
  List<int> imageBytes = await _imageFile.readAsBytes();
  var uint8List = Uint8List.fromList(imageBytes);
  await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
      text: (snapshot.data.documents[index].data['title']) );
      //text: 'My optional text.');
  // (snapshot.data.documents[index].data['title']), 'text/plain');
  } catch (e) {
  print('error: $e');
  }}
class ImageInput extends StatefulWidget {
@override
_ImageInputState createState() => _ImageInputState();
}

class _ImageInputState extends State<ImageInput> {

 File _imageFile;

 void _getImage(BuildContext context, ImageSource source){
ImagePicker.pickImage(source: source, maxWidth: 200.0).then((File image){
  setState((){
    _imageFile = image;
  });
  Navigator.pop(context);

});
 }

  void _openImagePicker(BuildContext context) {
 showModalBottomSheet(context: context, builder: (BuildContext context) {
  return Container(
    height: 180.0,
    padding: EdgeInsets.all(10.0),
    child: Column(
        children: [
          Text('Choose photo',
            style:TextStyle(fontWeight: FontWeight.bold),),
          SizedBox(height: 10.0),
          FlatButton(
            textColor: Theme.of(context).primaryColor,
            child: Text('Use Camera'),
            onPressed: () {
              _getImage(context, ImageSource.camera);
            },),
          FlatButton(
            textColor: Theme.of(context).primaryColor,child:
          Text('Open Gallery'),
            onPressed: () {
              _getImage(context, ImageSource.gallery);
            },)

        ]
    ),);
});
}

  @override
  Widget build(BuildContext context) {
  return Column(
  children: <Widget>[
    OutlineButton(
      onPressed: () {
        _openImagePicker(context);
      },
      child:Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Icon(Icons.camera_alt),
            SizedBox(
              width:1.0,
            ),
            // Text('Add Image'),
          ]
      ),//Row
    ),//outline button

    SizedBox(height: 10.0),
    _imageFile == null ? Text('Add a Pic')  : Image.file(_imageFile,
      fit: BoxFit.cover,
      height: 200.0,
      width: 200.0,
      // width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
    ),

    MaterialButton(
      child: Text('Send it!'),
      onPressed: () async => await _shareImageAndText(),

    ),
  ],
);
}
}
Future<void> _shareText(snapshot, index) async {
try {
  Share.text('Share Text ',
      (snapshot.data.documents[index].data['title']), 'text/plain');
} catch (e) {
  print('error: $e');
}
}