如何在flutter中删除GridView项?

问题描述 投票:0回答:2

我想在长按时动态删除简单的网格项;

我尝试过最明显的方法:创建一个网格数据列表,并在添加或删除项目时调用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")
          )
        )
      ),
    );
  }
}

如何从网格视图中删除项目? 附:提供的代码只是我解决问题的尝试 - 如果你愿意,你可以提供另一种方式!

dart flutter
2个回答
1
投票

我从示例应用程序中写了这个,它有一些你可能会觉得有用的东西。值得注意的是,我通过在有状态小部件中保持列表的长度来抽象列表数据结构。我用ListView写了这个,但我想你可以把它改成GridView而不会有任何打嗝。

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
投票

最后我得到了我想要的东西。 我会留在这里为可能有同样问题的人:)

主要课程:

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()}")
          )
        )
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.