Ошибка Flutetr whl ie ListView отображается в приложении - PullRequest
0 голосов
/ 05 апреля 2020

Я получаю ошибку в Listview под ListItems. Ошибка в терминале:

Метод 'toDouble' был вызван для нуля. Получатель: null Пробный вызов: toDouble ()

Но я не использую .toDouble в этом виджете. Код не получает ошибку. Ошибка просто появляется в приложении на эмуляторе. Поэтому я не знаю, как решить эту проблему.

Ошибка 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),
            )
          ],
        )
    );
  }
}

1 Ответ

0 голосов
/ 05 апреля 2020

Чтобы воспроизвести вашу ошибку, я создал классы Firestore Service и Book с информацией о вашем коде. Та же ошибка произошла, когда я не передал общее значение страниц в конструкторе Книги:

enter image description here

enter image description here

Чтобы предотвратить эту ошибку, используйте аннотацию @required в конструкторе класса Book:

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

...