如何在Flutter中删除GridView项目?

时间:2019-04-25 14:59:44

标签: dart flutter

我正试图长按动态删除简单的网格项;

我尝试了最明显的方法:创建一个网格数据列表,并在添加或删除该项目时调用setState。

UPD:项目在列表中正常工作,因为它的初始化循环已移至initState()方法(就像@jnblanchard在其评论中所述),并且不会在以下位置生成新项目每个build()调用,但删除仍然无法进行。
如果它有更多的项目(超出了屏幕大小),它将删除最后一行(当删除了足够的项目时),否则抛出以下异常:

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!

现在我的测试代码:

主类

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");
    });
  }
}
网格项的

单独的窗口小部件类

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")
          )
        )
      ),
    );
  }
}

如何从网格视图中删除项目?
ps。提供的代码只是我解决问题的尝试-如果需要,您可以提供另一种方式!

2 个答案:

答案 0 :(得分:1)

我是从示例应用程序中编写的,它有一些可能对您有用的东西。值得注意的是,我通过在有状态的小部件内保存列表的长度来抽象列表数据结构。我用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))
    );
  }
}

答案 1 :(得分:0)

最后我有了我想要的。
我将其留给可能有相同问题的人:)

主类:

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";
  }
}

支持类别:

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()}")
          )
        )
      ),
    );
  }
}