listview - 在App中显示ListView时出现Flutter错误

标签 listview flutter dart error-handling

我在Listview下的ListItems中收到错误。终端中的错误:

The method 'toDouble' was called on null. Receiver: null Tried calling: toDouble()



但我不在此小部件中使用.toDouble。代码没有错误。该错误仅显示在模拟器上的应用程序中。所以我不知道如何解决这个问题。

Error Modus
import 'package:flutter/material.dart';
import 'package:testapp/models/Book.dart';
import 'package:testapp/screens/home/Library/Book_Form.dart';
import 'package:testapp/services/Services.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:testapp/shared/loading.dart';

class LibraryPage extends StatefulWidget {
  @override
  _LibraryPageState createState() => _LibraryPageState();
}

class _LibraryPageState extends State<LibraryPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(35),
        child: AppBar(
          title: Align(
            alignment: Alignment.center,
            child: Text('Library', style: TextStyle(
              fontWeight: FontWeight.w500,
              color: Colors.grey[900],
              fontSize: 25,
              decoration: TextDecoration.underline,
              decorationColor: Color(0XFF1954A1),
              decorationThickness: 1.5,
            ),),
          ),
          backgroundColor: Colors.white,
          actions: <Widget>[
            Align(
              alignment: Alignment.topRight,
              child: Padding(
                padding: const EdgeInsets.only(right: 30),
                child: SizedBox(
                  width: 40,
                  height: 40,
                  child: FlatButton(
                        onPressed: (){
                          Navigator.of(context).push(
                          MaterialPageRoute(builder: (BuildContext context){
                            return AddBook();
                            }),
                          );
                        },
                    child: Icon(Icons.add,size: 35, color: Color(0XFF1954A1),),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      body: StreamBuilder(
          stream: FirestoreService().getBooks(),
          builder: (BuildContext context, AsyncSnapshot<List<Book>> snapshot) {
            if (snapshot.hasError || !snapshot.hasData)
              return Center(child: CircularProgressIndicator(
                backgroundColor: Color(0XFF1954A1),
              ));
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index){
                Book book = snapshot.data[index];
                return Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(7.0)),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey[400],
                          offset: const Offset(0.4, 0.8),
                          blurRadius: 2.0,
                          spreadRadius: 0.1,
                        ),
                      ]),
                  margin: EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      child: ListTile(
                        leading: Container(height: 60, width: 45, color: Colors.grey[200],
                          child: Image.network(
                           book.image != null? book.image : 'error'
                            ),
                          ),
                          title: Text(book.name),
                          subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text('${book.author}'),
                            Text('${book.readPages *100/ book.totalPages}%'),
                          ],
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            IconButton(
                                color: Colors.grey[400],
                                icon: Icon(Icons.edit),
                                onPressed: () => Navigator.push(context, MaterialPageRoute(
                                  builder: (_) => AddBook(book: book),
                                ))),
                            IconButton(
                              color: Colors.grey[400],
                              icon: Icon(Icons.delete),
                              onPressed: () => _deleteBook(context, book.id),),
                          ],
                        ),
                      ),
                    ),
                );
              },
            );
          }
      )
    );
  }

  void _deleteBook(BuildContext context,String id) async {
    if(await _showConformationDialog(context)){
      try{
        FirestoreService().deleteBook(id);
      }catch(e){
        print(e);
      }
    }
  }

  Future<bool> _showConformationDialog(BuildContext context) async {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) => AlertDialog(
          content: Text("Are you sure you want to delete this Note?"),
          actions: <Widget>[
            FlatButton(
              textColor: Color(0XFF1954A1),
              child: Text("delete"),
              onPressed: () => Navigator.pop(context, true),
            ),
            FlatButton(
              textColor: Color(0XFF1954A1),
              child: Text("cancel"),
              onPressed: () => Navigator.pop(context, false),
            )
          ],
        )
    );
  }
}

最佳答案

为了重现您的错误,我使用您的代码信息创建了Firestore Service和Book类。
当我没有在Book的构造函数中传递total pages值时,发生了相同的错误:

enter image description here

enter image description here

为防止此错误,请在Book类的构造函数中使用@required批注:

class Book {
  Book({
    @required this.name,
    @required this.author,
    @required this.id,
    @required this.image,
    @required this.readPages,
    @required this.totalPages,
  });

  String id;
  String image;
  String name;
  String author;
  int readPages;
  int totalPages;
}

这样,如果您忘记传递一个参数,则会出现一条黄线,提醒您需要传递一些东西:

enter image description here

关于listview - 在App中显示ListView时出现Flutter错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61045040/

相关文章:

Android: ListView 闪烁效果。关于如何摆脱这个的任何提示?

flutter - 如何在Flutter中从父窗口小部件调用子窗口小部件的initState()方法

dart - 底部被 Infinity 像素溢出的 RenderFlex

dart - 格式错误的类型:…在这种情况下使用 'some-object'无效

android - 我如何使用StreamBuilder而不出现这个轻微的null错误

java - ListView 控件(如 ComBox 控件)中 setConverter 的等效项在哪里?

c# - 如何在 c#net 中单击按钮将所选项目从一个 ListView 复制到另一个 ListView ?

android - RecyclerView 中的 ListView

flutter - 相等运算符 `==` 在使用 data_connection_checker 包时调用无关类型的引用

dart - 为什么我会使用 StatelessWidget 而不是 StatefulWidget?