简体   繁体   English

如何将索引从 Listview.builder 传递到项目小部件?

[英]How to pass index from Listview.builder to item widget?

I want to pass the index of listview items within the Listview.builder to delete these items from it in the item widget.我想在 Listview.builder 中传递 listview 项目的索引,以便在项目小部件中从中删除这些项目。

In the class Timeline I'm having a Listview.builder embedded in a Streambuilder.Timeline类中,我将 Listview.builder 嵌入到 Streambuilder 中。

void removePost(index) {
    setState(() {
      posts.remove(index);
    });
  }

@override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
        body: StreamBuilder<QuerySnapshot>(
          stream: postRef.orderBy('timestamp', descending: false).snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return circularProgress();
            }
            List<Post> posts = snapshot.data.documents
                .map((doc) => Post.fromDocument(doc))
                .toList();
            if (posts.isEmpty) {
              return Text("No Posts");
            }
            return ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final item = posts[index];
                return Post/Item( //??
                  ????? //What comes here? How to pass the index?
                );
              },
            );
          },
        ));
  }

In my class Post the items are build.在我的班级Post中,项目是构建的。 I want to press the Iconbutton to delete the related post but don't know really how to pass the index.我想按图标按钮删除相关帖子,但不知道如何传递索引。

class Post extends StatefulWidget {
  final int index;
  final String title;
  final String imageUrl;
  final Function(Post) removePost;

  const Post({Key key, this.index, this.title, this.imageUrl, this.removePost})
      : super(key: key);

  factory Post.fromDocument(DocumentSnapshot doc) {
    return Post(
      title: doc['title'],
      imageUrl: doc['imageUrl'],
    );
  }

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

class _PostState extends State<Post> {
  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Container(
      height: SizeConfig.blockSizeHorizontal * (100 / 3 + 3),
      child: Column(
        children: <Widget>[
          Text(widget.title),
          Text(widget.imageUrl),
          IconButton(
            onPressed: () => widget.removePost(this.widget),
            icon: Icon(Icons.delete),
          )
        ],
      ),
    );
  }
}

Any help is appreciated.任何帮助表示赞赏。

@Juju, have you tried, @Juju,你试过了吗,

return ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final item = posts[index];
                return Post(index: index, title: 'Test', imageUrl: 'https://www.google.com',);
              },
            );

Test:测试:

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Container(
                child: ListView.builder(
                  itemCount: 3,
                  itemBuilder: (context, index) {
                    //final item = posts[index];
                    return Post(index: index, title: 'Test', imageUrl: 'https://www.google.com',);
                  },
                ),
            )
        )
    );
  }
}

class Post extends StatefulWidget {
  final int index;
  final String title;
  final String imageUrl;
  final Function(Post) removePost;

  const Post({Key key, this.index, this.title, this.imageUrl, this.removePost})
      : super(key: key);

//  factory Post.fromDocument(DocumentSnapshot doc) {
//    return Post(
//      title: doc['title'],
//      imageUrl: doc['imageUrl'],
//    );
//  }

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

class _PostState extends State<Post> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 150,
      child: Column(
        children: <Widget>[
          Text(widget.title + ' ' + widget.index.toString()),// Testing passed index here
          Text(widget.imageUrl),
          IconButton(
            onPressed: () => widget.removePost(this.widget),
            icon: Icon(Icons.delete),
          )
        ],
      ),
    );
  }
}

Screenshot:截屏: 截屏

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 listview.builder 中为索引中的每个项目添加变量 - How to add a variable for each item in the index in a listview.builder 使用 Positioned 小部件在 ListView.builder Item 小部件上添加小部件 - Add widget on ListView.builder Item widget using Positioned widget 从 ListView.builder Flutter 中删除项目 - removing item from ListView.builder Flutter 如何将数字(通过单击按钮“OnPressed 属性”)从 stful 小部件(应用程序的第一个屏幕)传递到第二页的 ListView.builder - How to pass a number (through clicking Button "OnPressed property) from a stful widget (First screen on the app) to ListView.builder at Second Page 在 ListView.builder 小部件中监听索引变量的变化 - Listening to index variable change in ListView.builder widget 如何在Flutter中将额外的参数传递给ListView.builder Widget的itemBuilder函数? - How to pass extra arguments to itemBuilder function of ListView.builder Widget in Flutter? Flutter - 使用 ListView.builder 索引和提供者 Package 从列表中删除项目 - Flutter - removing an item from a list using ListView.builder index and Provider Package 从父页面重新加载小部件内的 listview.builder - Reload listview.builder inside a widget from parent page Flutter 从 ListView.builder 中删除项目不起作用 - Flutter remove item from ListView.builder not working 从 ListView.Builder 输入字段获取输入? 并作为 json 传递 - Get the inputs from a ListView.Builder input fields? and pass as json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM