【问题标题】:Flutetr Error whlie ListView displays in App在 App 中显示 ListView 时出现颤振错误
【发布时间】:2020-04-05 15:32:15
【问题描述】:

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

方法“toDouble”在 null 上被调用。接收方:空 调用: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),
            )
          ],
        )
    );
  }
}

【问题讨论】:

  • 它看起来像 book.readPagesbook.totalPages 可能我为空。也许试试(book.readPages ?? 0) *100/ (book.totalPages ?? 0)

标签: listview flutter dart error-handling


【解决方案1】:

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

为防止出现此错误,请在 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 2020-04-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多