颤振错误:在null上调用了吸气剂“长度”

时间:2020-05-30 17:58:23

标签: android mysql sqlite flutter flutter-layout

所以,这是我的学生列表的代码。.我正在使用sqlflite数据库存储学生集合。.但是当我运行它时..这显示了我的futurebuilder方法中的错误。我在snapshot.data.lenght行中遇到错误,错误显示该长度不应为null,这就是为什么我尝试了一些条件但仍然无法正常工作的原因

class StudentListPage extends StatefulWidget {
  @override
  _StudentListPageState createState() => _StudentListPageState();
}

class _StudentListPageState extends State<StudentListPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Student List'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add,color: Colors.white,),
            onPressed: (){
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context)=>AddStudentPage()
              ));
            },
          )
        ],
      ),
      body: FutureBuilder(
        future: DBHelpers.getAllStudent(),
        builder: (context,AsyncSnapshot<List<StudentModels>> snapshot)=>
        snapshot.connectionState==ConnectionState.waiting?
        Center(
          child: CircularProgressIndicator(),
        ):
        Padding(
          child:snapshot.data.length !=0? ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context,index)=>StudentItems(snapshot.data[index])):
          Center(

            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RaisedButton(
                  elevation: 5,
                  color: Theme.of(context).primaryColor,
                  child: Text("Click me To add Employee", style: TextStyle(color: Colors.white),),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  onPressed: (){

                  },
                )
              ],
            ),

          ),
        ),
      ),
    );
  }
}

那是我的数据库助手代码:

class DBHelpers{

  static final String CREATE_TABLE=''' create table $TABLE_STUDENT(
  $COL_STUDENT_ID integer primary key autoincrement,
  $COL_STUDENT_NAME text not null,
  $COL_STUDENT_PHONE integer not null,
  $COL_STUDENT_EMAIL text not null,
  $COL_STUDENT_FAVOURITE text )''';

  static Future<Database> open() async{
    final dbpath=await getDatabasesPath();
    final path=Path.join(dbpath,'student.db');
    return openDatabase(path,version: 1,onCreate: (db,version) async{
      db.execute(CREATE_TABLE);
    });
  }

  static Future<int> insertStudent(String table,Map<String,dynamic> map) async{
    final db=await open();
    return db.insert(table, map,conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<StudentModels>> getAllStudent() async{
      final db=await open();
      final List<Map<String,dynamic>> map=await db.query(TABLE_STUDENT,orderBy: COL_STUDENT_NAME);
      return List.generate(map.length, (index){
        return StudentModels.fromMap(map[index]);
      });
  }

}

这是我的学生模型:

final String TABLE_STUDENT='tbl_student';
final String COL_STUDENT_ID='col_id';
final String COL_STUDENT_NAME='col_name';
final String COL_STUDENT_EMAIL='col_email';
final String COL_STUDENT_PHONE='col_phone';
final String COL_STUDENT_FAVOURITE='col_fav';

class StudentModels{
  int id;
  String name;
  String email;
  int phoneNumber;
  bool isFavourite;

  StudentModels({
      this.id, this.name, this.email, this.phoneNumber, this.isFavourite=false
  });

  @override
  String toString() {
    return 'StudentModels{id: $id, name: $name, email: $email, phoneNumber: $phoneNumber, isFavourite: $isFavourite}';
  }

  Map<String,dynamic> toMap(){
    var map=<String,dynamic>{
      COL_STUDENT_NAME:name,
      COL_STUDENT_EMAIL:email,
      COL_STUDENT_PHONE:phoneNumber,
      COL_STUDENT_FAVOURITE:isFavourite,
    };
    if(id!=null){
      map[COL_STUDENT_ID]=id;
    }
    return map;
  }

  StudentModels.fromMap(Map<String,dynamic> map){
    name=map[COL_STUDENT_NAME];
    id=map[COL_STUDENT_ID];
    email=map[COL_STUDENT_EMAIL];
    phoneNumber=map[COL_STUDENT_PHONE];
    isFavourite=map[COL_STUDENT_FAVOURITE];
  }


}

这是我每次运行它时都会遇到的错误:

E/SQLiteLog(11830): (1) no such table: tbl_student
I/flutter (11830): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11830): The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state:
I/flutter (11830): _FutureBuilderState<List<StudentModels>>#1afc9):
I/flutter (11830): The getter 'length' was called on null.
I/flutter (11830): Receiver: null
I/flutter (11830): Tried calling: length
I/flutter (11830): 
I/flutter (11830): The relevant error-causing widget was:
I/flutter (11830):   FutureBuilder<List<StudentModels>>
I/flutter (11830):   file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
I/flutter (11830): 
I/flutter (11830): When the exception was thrown, this was the stack:
I/flutter (11830): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter (11830): #1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
I/flutter (11830): #2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
I/flutter (11830): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter (11830): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter (11830): #5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter (11830): #6      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter (11830): #7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
I/flutter (11830): #8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
I/flutter (11830): #9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter (11830): #10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter (11830): #11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter (11830): #12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter (11830): #16     _invoke (dart:ui/hooks.dart:261:10)
I/flutter (11830): #17     _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter (11830): (elided 3 frames from dart:async)
I/flutter (11830): 
I/flutter (11830): ════════════════════════════════════════════════════════════════════════════════════════════════════
E/SQLiteLog(11830): (1) no such table: tbl_student

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state: _FutureBuilderState<List<StudentModels>>#1afc9):
The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was: 
  FutureBuilder<List<StudentModels>> file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)

1 个答案:

答案 0 :(得分:2)

在快照接收器上尝试

builder: (context,AsyncSnapshot<List<StudentModels>> snapshot) {
   //progress UI 
  if (snapshot.connectionState != ConnectionState.done)
                return Center(child: Circular Progress Indicator());

  //load null data UI 
  if (!snapshot.hasData || snapshot.data == null)
                return Container();

  //load empty data UI 
  if (snapshot.data.isEmpty)
                return Container();

 //enter your code to show data
 //show the list of student model
...