Home > Back-end >  Why does Late Initialization Error occur?
Why does Late Initialization Error occur?

Time:04-15

The application has the function of adding news to favorites. But when I go to the Favorites page, I get the error "Late Initialization Error: Field "article" has not been initialized. The problem is in the button "Details", in the line:

MaterialPageRoute(builder: (context) => ArticlePage(article: article,))

Please help me solve the problem.Below is the code for this page:

class FavScreen extends StatefulWidget {
  const FavScreen({Key? key}) : super(key: key);

  @override
  State<FavScreen> createState() => _FavScreenState();
}

class _FavScreenState extends State<FavScreen> {
  late final Article article;
  final _fireStore = FirebaseFirestore.instance.collection('favoriteItems');

  @override
  void initState() {
    article = Article(
      author: article.author,
      title: article.title,
      description: article.description,
      url: article.url,
      urlToImage: article.urlToImage,
      publishedAt: article.publishedAt,
      content: article.content,
      source: article.source,
    );
    super.initState();
  }
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Favorite News', style: TextStyle(color: Colors.white)),
        backgroundColor: Color(0xfff27935),
      ),
      body:
         StreamBuilder(
           stream: _fireStore.snapshots(),
           builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
             if(!snapshot.hasData) {
               return Text('No featured news');
             } else {
               return ListView.builder(
                   itemCount: snapshot.data?.docs.length,
                   itemBuilder: (BuildContext context, int index) {
                     return InkWell(
                       child: Container(
                         margin: EdgeInsets.all(12.0),
                         padding: EdgeInsets.all(8.0),
                         decoration: BoxDecoration(
                             color: Colors.white,
                             borderRadius: BorderRadius.circular(12.0),
                             boxShadow: [
                               BoxShadow(
                                 color: Colors.black12,
                                 blurRadius: 3.0,
                               ),
                             ]),
                         child: Column(
                           mainAxisAlignment: MainAxisAlignment.start,
                           crossAxisAlignment: CrossAxisAlignment.start,
                           children: [
                             Container(
                               height: 200.0,
                               width: double.infinity,
                               decoration: BoxDecoration(
                                 image: DecorationImage(
                                     image: NetworkImage(snapshot.data?.docs[index].get('image')), fit: BoxFit.cover),
                                 borderRadius: BorderRadius.circular(12.0),
                               ),
                             ),
                             SizedBox(
                               height: 8.0,
                             ),
                             Container(
                                 child: Row(
                                     textDirection: TextDirection.ltr,
                                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                     children: <Widget>[
                                       Container(
                                         padding: EdgeInsets.all(6.0),
                                         decoration: BoxDecoration(
                                           color: Color(0xfff27935),
                                           borderRadius: BorderRadius.circular(30.0),
                                         ),
                                         child: Text(
                                           snapshot.data?.docs[index].get('name'),
                                           style: TextStyle(
                                             color: Colors.white,
                                           ),
                                         ),
                                       ),
                                       IconButton(
                                           onPressed: () {
                                             _fireStore.doc(snapshot.data?.docs[index].id).delete();
                                           },
                                           icon: const Icon(Icons.bookmark_remove)),
                                     ]
                                 )
                             ),
                             SizedBox(
                               height: 8.0,
                             ),
                             Text(
                               snapshot.data?.docs[index].get('title'),
                               style: TextStyle(
                                 fontWeight: FontWeight.bold,
                                 fontSize: 16.0,
                               ),
                             ),
                             SizedBox(
                               height: 10.0,
                             ),
                             GestureDetector(
                               onTap: () {
                                 Navigator.push(
                                     context,
                                     MaterialPageRoute(
                                         builder: (context) =>
                                             ArticlePage(
                                               article: article,
                                             )));
                               },
                               child: new Text("DETAILS", style: TextStyle(
                                 fontSize: 12.0,
                                 ),
                               ),
                             )
                           ],
                         ),
                       ),
                     );
                   }
               );
             }
           },
         )
    );
  }
}

CodePudding user response:

    article = Article(
      author: article.author,
      title: article.title,
      description: article.description,
      url: article.url,
      urlToImage: article.urlToImage,
      publishedAt: article.publishedAt,
      content: article.content,
      source: article.source,
    );

You're trying to initialize article by creating a new Article with values from article. article is uninitialized however, so it fails to read these values and spits out an error.

I'm not quite sure what you want to achieve, but I guess you want to pass in an Article into the widget and initialize the article variable in your state class with that?

CodePudding user response:

try removing final keyword

  late final Article article; //remove final

and make sure you should not use initializer in init state

  • Related