title: I would like to delete the last item on list view
body: <p>I want to remove the last item and delete from database table.
  However, I got the error from when I remove the last item. It's the error code below the message.</p>
  
  <p>'''
  RangeError (index): Invalid value: Not in range 0..6, inclusive: 7
  '''</p>
  
  <p>Here is the code by Dart.</p>
  
  <pre><code>import 'package:flutter/material.dart';
  import 'package:technewsapp/saved_newsdata.dart';
  import 'package:technewsapp/dbhealper.dart';
  import 'webview_screen.dart';
  import 'package:flutter_slidable/flutter_slidable.dart';
  
  final dbHelper = DatabaseHelper.instance;
  
  class Favorite extends StatefulWidget {
    @override
    _Favorite createState() =&gt; _Favorite();
  }
  class _Favorite extends State&lt;Favorite&gt; {
  
    SlidableController slidableController;
    List&lt;SavedNews&gt; savedNews = [];
  
    @override
    void initState() {
      // TODO: implement initState
      super.initState();
      _queryAll();
    }
  
    Animation&lt;double&gt; _rotationAnimation;
    Color _fabColor = Colors.blue;
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text("Favorite"),
        ),
        body: Center(
          child: OrientationBuilder(
            builder: (context, orientation) =&gt; _listViewWidget(
                context,
                orientation == Orientation.portrait
                    ? Axis.vertical
                    : Axis.horizontal),
          ),
        ),
      );
    }
  
    void _queryAll() async {
      final allRows = await dbHelper.queryAllRows();
      allRows.forEach((row) =&gt; savedNews.add(SavedNews.fromMap(row)));
      print('Query done.');
      setState(() {});
    }
  
    Widget _listViewWidget(BuildContext context, Axis direction) {
      return ListView.builder(
        scrollDirection: direction,
        itemCount: savedNews.length,
        itemBuilder: (context, index) {
          final Axis slideDirection = direction == Axis.horizontal ? Axis.vertical : Axis.horizontal;
          return _getSlideWithLists(context, index, slideDirection);
        },
      );
    }
  
    Widget _getSlideWithLists(BuildContext context, int index, Axis direction){
      return Slidable.builder(
        key: Key(savedNews[index].id),
        controller: slidableController,
        direction: direction,
  
        dismissal: SlidableDismissal(
          child: SlidableDrawerDismissal(),
          onDismissed: (actionType) {
            setState(() {
              print("index is $index");
              print("length is ${savedNews.length}");
              savedNews.removeAt(index);
              if(index + 1 == savedNews.length){
                _delete(savedNews[savedNews.length].id);
              } else {
                _delete(savedNews[index].id);
              }
            });
          },
        ),
        child: CardListItems(savedNews: savedNews, index: index),
        secondaryActionDelegate: SlideActionBuilderDelegate(
            actionCount: 1,
            builder: (context, index, animation, renderingMode) {
              return IconSlideAction(
                caption: 'Delete',
                color: renderingMode == SlidableRenderingMode.slide
                    ? Colors.red.withOpacity(animation.value)
                    : Colors.red,
                icon: Icons.delete,
                onTap: ((){
                  _delete(savedNews[index].id);
                  savedNews.removeAt(index);
                }),
              );
            }
        ), actionPane: SlidableScrollActionPane(),
      );
    }
    void _delete(id) async {
      // Assuming that the number of rows is the id for the last row.
      final rowsDeleted = await dbHelper.delete(id);
    }
  }
  
  class CardListItems extends StatelessWidget {
  
    final int index;
    final List&lt;SavedNews&gt; savedNews;
  
    const CardListItems({
      Key key,
      @required this.savedNews,
      @required this.index,
    }) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      return Card(
        child: ListTile(
          title: Text(
            '${savedNews[index].title}',
            style: TextStyle(
                fontSize: 18.0,
                color: Colors.black,
                fontWeight: FontWeight.bold),
          ),
          leading: Padding(
            padding: const EdgeInsets.all(8.0),
            child: SizedBox(
              child: savedNews[index].urlToImage == null
                  ? Image(
                image: AssetImage('assets/image/noImage.png'),
              )
                  : Image.network('${savedNews[index].urlToImage}'),
              height: 100.0,
              width: 100.0,
            ),
          ),
          onTap: () {
            print(savedNews[index].url);
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =&gt;
                      WebViewScreen(url: savedNews[index].url)),
            );
          },
        ),
  
      );
    }
  }
  </code></pre>
  
  <p>Here is the DB controller.</p>
  
  <pre><code>import 'package:path/path.dart';
  import 'package:sqflite/sqflite.dart';
  import 'package:technewsapp/saved_newsdata.dart';
  
  class DatabaseHelper {
  
    static final _databaseName = "savednews.db";
    static final _databaseVersion = 1;
  
    static final table = 'savednews_table';
  
    static final columnId = 'id';
    static final columnTitle = 'title';
    static final columnUrl = 'url';
    static final columnUrlToImage = 'urlToImage';
  
    // make this a singleton class
    DatabaseHelper._privateConstructor();
    static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
  
    // only have a single app-wide reference to the database
    static Database _database;
    Future&lt;Database&gt; get database async {
      if (_database != null) return _database;
      // lazily instantiate the db the first time it is accessed
      _database = await _initDatabase();
      return _database;
    }
  
    // this opens the database (and creates it if it doesn't exist)
    _initDatabase() async {
      String path = join(await getDatabasesPath(), _databaseName);
      return await openDatabase(path,
          version: _databaseVersion,
          onCreate: _onCreate);
    }
  
    // SQL code to create the database table
    Future _onCreate(Database db, int version) async {
      await db.execute('''
            CREATE TABLE $table (
              $columnId TEXT NOT NULL PRIMARY KEY,
              $columnTitle TEXT NOT NULL,
              $columnUrl TEXT NOT NULL,
              $columnUrlToImage TEXT NOT NULL
            )
            ''');
    }
  
    // Helper methods
  
    // Inserts a row in the database where each key in the Map is a column name
    // and the value is the column value. The return value is the id of the
    // inserted row.
    Future&lt;int&gt; insert(SavedNews savedNews) async {
      Database db = await instance.database;
      return await db.insert(table, {'id': savedNews.id, 'title': savedNews.title, 'url': savedNews.url, 'urlToImage': savedNews.urlToImage});
    }
  
    // All of the rows are returned as a list of maps, where each map is
    // a key-value list of columns.
    Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; queryAllRows() async {
      Database db = await instance.database;
      return await db.query(table);
    }
  
    Future&lt;int&gt; delete(String id) async {
      Database db = await instance.database;
      return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
    }
  
  
  }
  </code></pre>
  
  <p>Environment</p>
  
  <p>Flutter 1.17.0 • channel beta • <a href="https://github.com/flutter/flutter.git" rel="nofollow noreferrer">https://github.com/flutter/flutter.git</a>
  Framework • revision e6b34c2b5c (2 weeks ago) • 2020-05-02 11:39:18 -0700
  Engine • revision 540786dd51
  Tools • Dart 2.8.1</p>
  
  <p>V/r</p>