簡體   English   中英

在 flutter 應用程序開發中,類型“Null”不是“String”類型的子類型

[英]type 'Null' is not a subtype of type 'String' in the flutter app development

我正在開發一個管理詞匯表食品的應用程序。 我不知道我犯了什么錯誤。 這是我的代碼...

首先,我創建了一個名為“產品”的 class,其中包含所有必填字段,如產品名稱、產品圖像、項目類型和數量等

model:

class Product {
  String id;
  final String productName;
  final String itemType;
  final String productImage;
  final String purchasedDate;
  final String expiryDate;
  final String quantity;

  Product({
    this.id = '',
    required this.productName,
    required this.productImage,
    required this.itemType,
    required this.purchasedDate,
    required this.expiryDate,
    required this.quantity,
  });

  Map<String, dynamic> toJson() => {
        'id': id,
        'ProductImage': productImage,
        'ProductName': productName,
        'PurchasedDate': purchasedDate,
        'ExpiryDate': expiryDate,
        'ItemType': itemType,
        'Quantity': quantity,
      };

  static Product fromJson(Map<String, dynamic> json) => Product(
      productName: json['ProductName'],
      productImage: json['productImage'],
      itemType: json['ItemType'],
      purchasedDate: json['purchasedDate'],
      expiryDate: json['ExpiryDate'],
      quantity: json['Quantity']);
}

實現代碼:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:expire_x/utils/product.dart';
import 'package:flutter/material.dart';

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

  @override
  State<HomePageTwo> createState() => _HomePageTwoState();
}

class _HomePageTwoState extends State<HomePageTwo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("home page"),
      ),
      body: StreamBuilder<List<Product>>(
        stream: readProduct(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text("Something went wrong> ${snapshot.error}");
          } else if (snapshot.hasData) {
            final product = snapshot.data!;
            return ListView(
              children: product.map(buildProduct).toList(),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  Widget buildProduct(Product product) => ListTile(
        title: Text(product.productName),
      );

  Stream<List<Product>> readProduct() => FirebaseFirestore.instance
      .collection('Products')
      .snapshots()
      .map((snapshot) =>
          snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList());

  Future CreateProduct() async {
    final docProduct = FirebaseFirestore.instance.collection('Products').doc();

    final product = Product(
      id: docProduct.id,
      productImage: 'ddd',
      productName: "productName",
      purchasedDate: "purchasedDate",
      expiryDate: "expiryDate",
      itemType: "itemType",
      quantity: "quantity",
    );
    final json = product.toJson();
    await docProduct.set(json);
  }
}

我想要的來自 firebase 的 json 響應: json 響應

和錯誤:

“Null”類型不是“String”類型的子類型

在模擬器中

我是 flutter 的新手。 誰能幫幫我嗎?

model class 中的拼寫錯誤

static Product fromJson(Map<String, dynamic> json) => Product(
  productName: json['ProductName'],
  productImage: json['ProductImage'],       // It should be 'ProductImage'
  itemType: json['ItemType'],
  purchasedDate: json['PurchasedDate'],    // and this should be 'PurchasedDate'
  expiryDate: json['ExpiryDate'],
  quantity: json['Quantity']);

在構造函數中添加required關鍵字時會發生此錯誤。 其中一個值似乎是 null。

為了克服這個

  • 確保填寫所有文檔中的所有字段。

或者

  • 避免使用required的使用 null 運算符來代替? 如果您不確定每次要填寫的文件。

喜歡:

class Product {
  String? id;
  String? productName;
  String? itemType;
  String? productImage;
  String? purchasedDate;
  String? expiryDate;
  String? quantity;

  Product({
    this.id = '',
    this.productName,
    this.productImage,
    this.itemType,
    this.purchasedDate,
    this.expiryDate,
    this.quantity,
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM