简体   繁体   English

如何在Flutter中删除GridView项目?

[英]How to delete GridView item in flutter?

I'm trying to dynamically delete simple grid item on long press; 我试图长按以动态删除简单的网格项;

I've tried the most obvious way: created a list of grid data, and called setState on addition or deletion of the item. 我尝试了最明显的方法:创建了一个网格数据列表,并在添加或删除该项目时调用了setState。

UPD: Items works properly in the list, since it's initialisation loop moved to initState() method (just as @jnblanchard said in his comment), and don't generate new items at every build() call, but deletion is still doesn't work. UPD:项目在列表中正常工作,因为它的初始化循环已移至initState()方法(就像@jnblanchard在其评论中所述),并且不会在每次build()调用时都生成新项目,但删除仍不会工作。
If it has more items, than can fit the screen, it deletes last row, (when enough items deleted), otherwise the following exception is thrown: 如果有更多项目(超出屏幕大小),它将删除最后一行(当删除了足够多的项目时),否则抛出以下异常:

I/flutter (28074): The following assertion was thrown during performLayout():
I/flutter (28074): SliverGeometry is not valid: The "maxPaintExtent" is less than the "paintExtent".
I/flutter (28074): The maxPaintExtent is 540.0, but the paintExtent is 599.3. By definition, a sliver can't paint more
I/flutter (28074): than the maximum that it can paint!

My test code now: 现在我的测试代码:

main class 主班

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/TestTile.dart';

class Prototype extends StatefulWidget{
  @override
  _PrototypeState createState() => _PrototypeState();
}

class _PrototypeState extends State<Prototype> {
  //list of grid data
  List<Widget> gridItemsList = [];

  @override
  void initState(){
    super.initState();
    //----filling the list----
    for(int i =0; i<10; i++){
      gridItemsList.add(
        TestTile(i, (){
          //adding callback for long tap
          delete(i);
        })
      );
    }
  } 

  @override
  Widget build(BuildContext context) {
  //----building the app----
  return Scaffold(
      appBar: AppBar(
        title: Text("Prototype"),
        actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                int index = gridItemsList.length+1;
                add(
                  new TestTile(index, (){
                    delete(index);
                  })
                );
              },
            ),
          ]
      ),
      body: GridView(
        gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        children: gridItemsList
      )
    ); 
  }

  ///method for adding the items
  void add(Widget toAdd){
    setState(() {
      TestTile tile = toAdd as TestTile; 
      gridItemsList.add(toAdd);
      print("tile number#${tile.index} added");
    });
  }

  ///method for deleting the items 
  void delete(int index){
    setState(() {
      gridItemsList.removeAt(index);
      print("tile number#$index is deleted");
    });
  }
}

and separate widget class for grid items 和网格项目的单独小部件类

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

class TestTile extends StatelessWidget{
  int _index;
  var _callback;

  TestTile(this._index, this._callback);

  get index => _index;

  @override
  Widget build(BuildContext context) {
    return GridTile(
      child: Card(
        child: InkResponse(
          onLongPress: _callback,
          child: Center(
            child:Text("data#$_index")
          )
        )
      ),
    );
  }
}

How can I delete an item from grid view? 如何从网格视图中删除项目?
ps the provided code is just my attempts of solving the problem - you can offer another way, if you want! ps提供的代码只是我解决问题的尝试-如果需要,您可以提供另一种方式!

I wrote this up from the example app, it has a few things that you may find useful. 我是从示例应用程序中写下来的,它具有一些您可能会发现有用的东西。 Notably I abstract the list data-structure by holding the length of the list inside a stateful widget. 值得注意的是,我通过在有状态的小部件内保存列表的长度来抽象列表数据结构。 I wrote this with a ListView but I think you could change that to a GridView without any hiccups. 我用ListView编写了此代码,但我认为您可以将其更改为GridView而不会出现任何打ic。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {

    return Scaffold(appBar: AppBar(
        title: Text("Owl"),
        actions: <Widget>[IconButton(icon: Icon(Icons.remove), onPressed: () => this.setState(() => _counter > 1 ? _counter-- : _counter = 0)), IconButton(icon: Icon(Icons.add), onPressed: () => this.setState(() => _counter++))],
      ),
      body: ListView.builder(itemExtent: 50, itemCount: _counter, itemBuilder: (context, index) => Text(index.toString(), textAlign: TextAlign.center, style: Theme.of(context).textTheme.title))
    );
  }
}

Finally I've got what I wanted. 终于我有了我想要的。
I'll leave it here for someone who might have the same problem :) 我将其留给可能有相同问题的人:)

Main class: 主班:

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/TestTile.dart';

class Prototype extends StatefulWidget{
  @override
  _PrototypeState createState() => _PrototypeState();
}

class _PrototypeState extends State<Prototype> {
  //list of some data
  List<Person> partyInviteList = [];

  _PrototypeState(){
    //filling the list
    for(int i=0; i<5; i++){ 
      partyInviteList.add(Person.generateRandomPerson());
    }
    print("Person ${partyInviteList.toString()}");
  }

  @override
  Widget build(BuildContext context) {
  //----building the app----
  return Scaffold(
      appBar: AppBar(
        title: Text("Prototype"),
        actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              //generating an item on tap
              onPressed: () {
                setState(() {
                  partyInviteList.add(Person.generateRandomPerson());
                });
              },
            ),
          ]
      ),
      body: GridView.count(
      crossAxisCount: 2,
      children: List.generate(partyInviteList.length, (index) {
        //generating tiles with people from list
        return TestTile(
          partyInviteList[index], (){
            setState(() {
              print("person ${partyInviteList[index]} is deleted");
              partyInviteList.remove(partyInviteList[index]);
            });
          }
        );
        })
      )
    ); 
  }
}

///person class
class Person{
  Person(this.firstName, this.lastName);
  static List<String> _aviableNames = ["Bob", "Alise", "Sasha"];
  static List<String> _aviableLastNames = ["Green", "Simpson", "Stain"];

  String firstName;
  String lastName;

  ///method that returns random person
  static Person generateRandomPerson(){
    Random rand = new Random();
    String randomFirstName = _aviableNames[rand.nextInt(3)];
    String randomLastName = _aviableLastNames[rand.nextInt(3)];
    return Person(randomFirstName, randomLastName);
  }

  @override
  String toString() {
    return "$firstName $lastName";
  }
}

Support class: 支持等级:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:options_x_ray_informer/prototyping/Prototype.dart';

class TestTile extends StatelessWidget{
  final Person person;
  var _callback;

  TestTile(this.person, this._callback);

  @override
  Widget build(BuildContext context) {
    return GridTile(
      child: Card(
        child: InkResponse(
          onLongPress: _callback,
          child: Center(
            child:Text("${person.toString()}")
          )
        )
      ),
    );
  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM