gpt4 book ai didi

flutter - 在 flutter 中使用 StreamBuilder 时将数据传递到下一个屏幕

转载 作者:行者123 更新时间:2023-12-04 13:15:11 24 4
gpt4 key购买 nike

我能够从 Card 小部件内的 firestore 获取数据,但无法进入细节 - 我的意思是将快照从第一个屏幕传递到第二个屏幕(从 BodySectionStream 页面到 DetailPage)。我尝试了很多但都失败了。请查看我的代码并帮助我解决问题。提前致谢

class BodySectionStream extends StatefulWidget {

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

class _BodySectionStreamState extends State<BodySectionStream> {

final firestore = Firestore.instance;



navigateToDetail( AsyncSnapshot post) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(
news: post,
)));
}


@override
Widget build(BuildContext context) {


return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Container(child:
Text('Prefernces', textAlign: TextAlign.left, style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 22.0, color: Colors.black),)),
),

const SizedBox(height:10.0),

StreamBuilder <QuerySnapshot>(
stream: firestore.collection('news').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center (child: CircularProgressIndicator());
}
else {
final posts = snapshot.data.documents;
List<Container> postWidgets = [];
for (var post in posts ){
final postText = post.data['title'];
final postList = Container(
child: GestureDetector(
onTap: () => navigateToDetail( post.data[index]),
child: Card(

child: Column(children: <Widget>[
Image.network(post.data['images'],),
Text(postText),
],)
),
)
);


postWidgets.add(postList);

}
return Expanded(
child: ListView(
children: postWidgets,
));
}
}),

],
),
),
);
}
}

DetailPage - 我想传递数据的地方

class DetailPage extends StatefulWidget {
final AsyncSnapshot news;

DetailPage({this.news});

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

class _DetailPageState extends State<DetailPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: <Widget>[
Text(widget.news.data['title'])
],
),
),
);
}
}

最佳答案

final posts = snapshot.data.documents;

documents getter 返回类型为 DocumentSnapshotList,您正在将 DetailPage 传递给此处的文档字段:

onTap: () => navigateToDetail( post.data[index]),

但是你想传递一个DocumentSnapshot来访问DetailPage中的title字段,所以只需传递post:

onTap: () => navigateToDetail(post),

并在 DetailPage 类中将 news 数据类型从 AsyncSnapshot 更改为 DocumentSnapshot

关于flutter - 在 flutter 中使用 StreamBuilder 时将数据传递到下一个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61192955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com