A non-null String must be provided to a Text widget. Failed assertion: line 378 pos 10: 'data != null'

Viewed 47

I have a problem when I'm on the main page which brings up the error in the image

enter image description here

and see possible problems in the coding of the main page. this is the source code

import 'package:popkissofficial/widgets/custom_action_bar.dart';
import 'package:popkissofficial/widgets/product_card.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class HomeTab extends StatelessWidget {
  final CollectionReference _productsRef =
  FirebaseFirestore.instance.collection("Products");

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          FutureBuilder<QuerySnapshot>(
            future: _productsRef.get(),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return Scaffold(
                  body: Center(
                    child: Text("Error: ${snapshot.error}"),
                  ),
                );
              }

              if (snapshot.connectionState == ConnectionState.done) {
                return ListView(
                  padding: const EdgeInsets.only(
                    top: 108.0,
                    bottom: 12.0,
                  ),
                  children: snapshot.data.docs.map((document) {
                    return ProductCard(
                      title: document.data()['name'],
                      imageUrl: document.data()['images'][0],
                      price: "\Rp${document.data()['price']}",
                      productId: document.id,
                    );
                  }).toList(),
                );
              }

              // Loading State
              return Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            },
          ),
          CustomActionBar(
            title: "Home",
            hasBackArrrow: false,
          ),
        ],
      ),
    );
  }
}

did anyone can fix it?

enter image description here

3 Answers

you are assigning null value to Text widget.

Try this:

 ProductCard(
  title: document.data['name'],
  imageUrl: document.data['images'][0],
  price: "\Rp${document.data['price']}",
  productId: document.id,
);

You can try

children: snapshot.data?.docs.map((document) {
        return ProductCard(
          title: document.get("name") ?? "",
          imageUrl: document.get("images")[0] ?? "",
          price: document.get("price") ?? "",
          productId: document.id,
        );
      }) as List<Widget>? ??
      [],

Or like

children: snapshot.data?.docs.map((document) {
      final data = document.data() as Map?;
      return ProductCard(
         title: data?["name"] ?? "",

But It would be better accepting nullable data, I think.

Related