如何修复'RangeError(index):Invalid value:Valid value range is empty:0'in flutter

时间:2019-07-06 18:43:15

标签: flutter

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:async';
import 'note_details.dart';
import '../database_helper.dart';
import '../Note.dart';
import 'package:sqflite/sqflite.dart';

class NoteList extends StatefulWidget {
  @override
  _NoteListState createState() => _NoteListState();
}

class _NoteListState extends State<NoteList> {
  DatabaseHelper databaseHelper =  DatabaseHelper();
  List<Note> noteList;  
  int count=0;

  void navigateToDetail(Note note, String title) async{
    bool result = await Navigator.push(context, MaterialPageRoute(builder: (BuildContext context){
      return NoteDetails(note, title);
    }));
    if (result ==  true){
      updateListView();   
    }
  }

  //get the noteList view
  ListView getNoteListView(){
    return ListView.builder(
      itemCount: count,
      itemBuilder: (context,position){
        return Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
          color: Color(0xff1D1D1D),
          elevation: 4.0,
          child: ListTile(
            leading: CircleAvatar(
              backgroundImage: NetworkImage("http://learncodeonline.in/mascot.png") ,
            ),
            title: Text(this.noteList[position].title, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25.0),),
            subtitle: Text(this.noteList[position].date, style: TextStyle(color: Color(0xffBB86FC)) ,),
            trailing: GestureDetector(
              child: Icon(Icons.open_in_new, color: Color(0xffBB86FC)),
              onTap: (){
                navigateToDetail(this.noteList[position], "Edit Possible");
              }
            ),
          ),
        );
      }
    );
  }


  void updateListView(){
    final Future<Database> dbFuture = databaseHelper.initializeDatabase();
    dbFuture.then((database){
      Future<List<Note>> noteListFuture = databaseHelper.getNoteList();
      noteListFuture.then((noteList){
        setState(() {
          this.noteList = noteList;
          this.count = noteList.length;
        });
      });
    });
  } 


  @override
  Widget build(BuildContext context) {
    if(noteList!=null){
      noteList = List<Note>();
      updateListView();
    }
    return Scaffold(
      appBar: AppBar(
          title: Text('What TODO:',style: TextStyle(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic),),
          backgroundColor: Color(0xff1f1f1f),
          centerTitle: false,
        ),
      body: getNoteListView(),
      floatingActionButton: FloatingActionButton.extended(
        backgroundColor: Color(0xffBB86FC),
        icon: Icon(Icons.add_comment, color: Colors.black,),
        label: Text("TODO: ", style: TextStyle(color: Colors.black),),
        elevation: 5.0,
        // foregroundColor: Colors.white,
        onPressed: (){
          navigateToDetail(Note('','',2), 'Add Note');
        },
      ),  
    );`
  }
}

此应用中有两个页面。其中一个是列出所有TODO的视图,另一个是我们提到TODO的页面。在数据库中的输入可以成功完成,但是一旦添加,列表视图就会显示上述错误。

列表视图页面,该页面列出了数据库中所有待办事项。在详细信息页面中添加了一个TODO,并弹出该页面(查看页面)。但是它随后显示错误“ RangeError(索引):无效值:有效值范围为空:0”

1 个答案:

答案 0 :(得分:0)

检查之前的讨论,看起来 count 的值已更新。您仍然收到错误的原因是 getNoteListView() 仍然被调用,试图从空的 ListView 创建一个 noteList。如果 noteList 长度大于 0,您可以在这里做的是仅生成 ListView。否则,显示不同的 Widget(即 CircularProgressIndicator)

body: (noteList.length > 0) ? getNoteListView() : CircularProgressIndicator(),

并为 ListView.builder() itemCount 使用 noteList.length

ListView getNoteListView(){
  return ListView.builder(
    itemCount: noteList.length,
    ...
  );
}
  

尽管此处的最佳解决方案是在构建 FutureBuilder 小部件之前使用 StreamBuildernoteList 运行填充 ListView 的请求。