Dart中List存储构造函数报错求助:Book is not a function
Hey there! Let's work through this common Dart issue step by step. The error usually pops up due to small mix-ups in how you reference the Book constructor or define your List. Here are the most likely fixes:
1. You're storing a Book instance instead of the constructor itself
If you added parentheses and arguments when putting Book into the List, you're saving a Book object (an instance) instead of the constructor function. This will throw an error if your List expects a function/constructor type.
Wrong:
class Book { String title; Book(this.title); } // Trying to store an instance (not the constructor) List<Book Function(String)> constructors = [Book("Dart Basics")]; // Error triggers here
Correct:
class Book { String title; Book(this.title); } // Store the constructor reference (no parentheses) List<Book Function(String)> constructors = [Book];
2. You've accidentally shadowed the Book class with a variable
If you created a variable named Book somewhere in your code (using var, final, etc.), it will override the class name. When you try to reference Book later, Dart will point to the instance variable instead of the constructor, causing the error.
Wrong:
class Book { String title; Book(this.title); } // Oops! This variable shadows the Book class final Book = Book("Shadowed Book"); // Now "Book" refers to the instance, not the constructor List<Book Function(String)> constructors = [Book]; // Error: Book is not a function
Correct:
Rename the variable to avoid conflict:
class Book { String title; Book(this.title); } // Use a unique name for the instance variable final myBook = Book("Shadowed Book"); // Now "Book" correctly refers to the class constructor List<Book Function(String)> constructors = [Book];
3. Mismatched function type in your List declaration
Make sure your List's generic type exactly matches the signature of your Book constructor. This is especially important if you're using named constructors with specific parameters.
Example with a named constructor:
class Book { String title; int pages; Book.detailed(this.title, this.pages); } // List type matches the named constructor's parameter signature List<Book Function(String, int)> constructors = [Book.detailed];
4. Factory constructor reference issues
If Book uses a factory constructor, the same rule applies—reference the constructor name without calling it (no parentheses).
class Book { String title; factory Book.fromTitle(String title) { return Book._internal(title); } Book._internal(this.title); } // Store the factory constructor reference List<Book Function(String)> constructors = [Book.fromTitle];
If you share a snippet of your actual Book class and List code, I can give an even more targeted fix!
内容的提问来源于stack exchange,提问作者HaSnen Tai

