gpt4 book ai didi

android-studio - Flutter:如何将值从streamprovider/listview构建器传递到另一个类

转载 作者:行者123 更新时间:2023-12-03 04:37:40 24 4
gpt4 key购买 nike

背景:
我正在尝试生成图像的可滚动列表 View 。该屏幕将分为三个阶段:

  • 最初列出某种类型的图像(如元数据中的firestore字段中所定义)
  • 当用户选择这些小部件之一时,图像将更改为另一种图像
  • 最后,是可选的第三阶段,其中显示了不同类型的

  • 每按一次,所选的图像将建立到一个新的阵列中,最终形成另一种图像 View ,该图像 View 由要在底部显示的三个所选图像组成,并单击按钮,然后将读取其中的“句子”。 3张选定的图像。
    我目前所拥有的:
    我有一个初始ListView显示正确的过滤图像,通过StreamProvider提供,该StreamProvider调用包含ListView的类。目前,由于对查询进行了硬编码,因此已对其进行过滤。
    这是最终显示ListView的屏幕
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:showmeapp/Screens/Home/image_list.dart';
    import 'package:showmeapp/Services/database.dart';
    import 'package:showmeapp/models/new_image.dart';

    class Sentence extends StatelessWidget {
    @override
    Widget build(BuildContext context) {

    return StreamProvider<List<NewImage>>.value(
    value: FirestoreDatabaseService().firestoreImages,
    child: Scaffold(
    backgroundColor: Colors.blue[300],
    appBar: AppBar(
    title: Text('Make A Sentence'),
    backgroundColor: Colors.blue[700],
    elevation: 0.0,
    ),
    body: ImageList(),
    )
    );
    }
    }
    这是从该屏幕调用的ImageList类
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:showmeapp/Screens/Home/image_card.dart';
    import 'package:showmeapp/models/new_image.dart';

    class ImageList extends StatefulWidget {
    @override
    _ImageListState createState() => _ImageListState();

    }

    class _ImageListState extends State<ImageList> {
    @override
    Widget build(BuildContext context) {

    final images = Provider.of<List<NewImage>>(context) ?? [];
    final requestImages = images.where((element) => element.imageClass == 'request').toList();

    return ListView.builder(
    scrollDirection: Axis.horizontal,
    itemCount: requestImages.length,
    itemBuilder: (context, index) {
    return Container(
    padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 24.0),
    height: MediaQuery.of(context).size.height * 0.35,
    child: ImageCard(newImage: requestImages[index]),
    );
    },
    );
    }
    }
    这是从ImageList类调用的自定义ImageCard类
    import 'package:flutter/material.dart';
    import 'package:flutter/widgets.dart';
    import 'package:showmeapp/Screens/Home/image_list.dart';
    import 'package:showmeapp/models/new_image.dart';

    class ImageCard extends StatelessWidget {
    final NewImage newImage;

    ImageCard({this.newImage});

    @override
    Widget build(BuildContext context) {
    return Column(
    children: [
    Container(
    width: MediaQuery.of(context).size.width * 0.3,
    height: MediaQuery.of(context).size.height * 0.2,
    child: Card(
    elevation: 30.0,
    shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(5.0),
    side: BorderSide(width: 2.0, color: Colors.blueAccent),
    ),
    child: GestureDetector(
    child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: Image.asset(
    'assets/${newImage.imageLocation}',
    scale: 0.8,
    height: MediaQuery.of(context).size.height * 0.2,
    width: MediaQuery.of(context).size.width * 0.1,
    ),
    ),
    onTap: () {
    // String optionSelected = newImage.imageClass;

    },
    ),
    ),
    ),
    Container(
    width: MediaQuery.of(context).size.width * 0.3,
    child: Padding(
    padding: EdgeInsets.all(5.0),
    child: Center(
    child: Text(
    newImage.imageDescription,
    style: TextStyle(
    fontSize: 40.0,

    ),
    ),
    ),
    ),
    )
    ],
    );
    }
    }
    最后,为了完整起见,这是与Firebase相关的功能,并要求所有这些功能
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:showmeapp/models/new_image.dart';

    // A class for the Firestore Database Service

    class FirestoreDatabaseService {

    final String iid;

    // Constructor for Database Class
    FirestoreDatabaseService({ this.iid });

    // create a reference to the Firestore 'images' collection
    final CollectionReference firestoreImageCollection = FirebaseFirestore.instance.collection('images');

    // Add or update image data - This will be useful for initial creation of image meta data for the app
    Future updateFirestoreImageData(String description, String location, String type, String category) async {
    return await firestoreImageCollection.doc(iid).set({
    'image_category': category,
    'image_description': description,
    'image_location': location,
    'image_type': type
    });
    }

    // new image list from snapshot
    List<NewImage> _newImageFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
    return NewImage(
    imageClass: doc.data()['image_class'] ?? '',
    imageType: doc.data()['image_type'] ?? '',
    imageCategory: doc.data()['image_category'] ?? '',
    imageLocation: doc.data()['image_location'] ?? '',
    imageDescription: doc.data()['image_description'] ?? ''
    );
    }).toList();
    }

    // Get images from collection via stream
    Stream<List<NewImage>> get firestoreImages {
    return firestoreImageCollection.snapshots()
    .map(_newImageFromSnapshot);
    }
    }
    我正在努力的事情:
    当用户选择一个“请求”图像时,我想通过一个值,以便显示的下一组图像为“对象”类型。
    但是,如果我通过此操作,它将始终将Provider Of请求发送为Null,并且不返回任何内容。
    无效的代码:
    ImageList类
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:showmeapp/Screens/Home/image_card.dart';
    import 'package:showmeapp/models/new_image.dart';

    class ImageList extends StatefulWidget {
    @override
    _ImageListState createState() => _ImageListState();

    String searchClass;
    ImageList({ this.searchClass });
    }

    class _ImageListState extends State<ImageList> {
    @override
    Widget build(BuildContext context) {
    final String searchClass = ImageList().searchClass;
    final images = Provider.of<List<NewImage>>(context) ?? [];
    final requestImages = images.where((element) => element.imageClass == searchClass.toString()).toList();
    print('search class is: $searchClass');
    print('Class search class is: ${ImageList().searchClass}');

    return ListView.builder(
    scrollDirection: Axis.horizontal,
    itemCount: requestImages.length,
    itemBuilder: (context, index) {
    return Container(
    padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 24.0),
    height: MediaQuery.of(context).size.height * 0.35,
    child: ImageCard(newImage: requestImages[index]),
    );
    },
    );
    }
    }
    句子屏幕/小部件
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:showmeapp/Screens/Home/image_list.dart';
    import 'package:showmeapp/Services/database.dart';
    import 'package:showmeapp/models/new_image.dart';

    class Sentence extends StatelessWidget {
    @override
    Widget build(BuildContext context) {

    return StreamProvider<List<NewImage>>.value(
    value: FirestoreDatabaseService().firestoreImages,
    child: Scaffold(
    backgroundColor: Colors.blue[300],
    appBar: AppBar(
    title: Text('Make A Sentence'),
    backgroundColor: Colors.blue[700],
    elevation: 0.0,
    ),
    body: ImageList(searchClass: 'request',),
    )
    );
    }
    }
    因此,传递“request”字符串并将其包含在where子句中将导致Null。它仅在我在where子句中指定'request'时有效。上面的示例不是来自所选图像的操作,而是同一原理,我试图告诉它最初通过传递的值加载“请求”图像。一旦我可以通过初始值,那么我希望任何进一步的传递都可以插入:-)
    我已经尝试过对类,类和状态中的变量进行修改(现在是这样),但似乎无法使其携带值。
    我将如何实现?是否可以使用StreamProvider / ListView构建器?
    更新
    我的NewImage类如下:
    class NewImage {

    final String imageType; // Whether the image is a Category image or Object Image
    final String imageDescription; // Text to display with the image
    final String imageLocation; // The URL or Location of the image
    final String imageCategory; // The category that the image belongs to
    final String imageClass; // A tag to identify the stage for sentences, such as Request, Object, Ending

    NewImage({ this.imageType, this.imageDescription, this.imageLocation, this.imageCategory, this.imageClass });

    }
    谢谢
    安德鲁

    最佳答案

    我不确定我是否理解您的问题,但是我认为您的问题是由以下原因引起的:

    final images = Provider.of<List<NewImage>>(context) ?? [];
    我假设您的new_image.dart模型是这样的:
    class NewImage extends ChangeNotifier {
    List<Image> _imageList = [];
    List<Image> get imageList => _imageList;
    void fetchImages() {
    _imageList = fetchFunction();
    notifyListeners();
    }
    ....
    }
    如果是这种情况,您的代码应该是这样的:
    final images = Provider.of<NewImage>(context, listen: false).imageList;

    关于android-studio - Flutter:如何将值从streamprovider/listview构建器传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63850275/

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