Home > Software engineering >  JSON and serialization : lnvalid reference to this expression. fetch data form firebase as firestore
JSON and serialization : lnvalid reference to this expression. fetch data form firebase as firestore

Time:01-17

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class MyCard {
  String name;
  String desc;
  String image;
  String flav;
  double price;

  MyCard(this.name, this.desc, this.image, this.flav, this.price);
  factory MyCard.Food(name, desc, image, flav, price) =>
      MyCard(name, desc, image, flav, price);
  MyCard.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        desc = json['desc'],
        image = json['image'],
        flav = json['flav'],
        price = json['price'];
}
@JsonSerializable()
class Food extends MyCard {
  @override
  String name;
  @override
  String desc;
  @override
  String image;
  @override
  String flav;
  @override
  double price;

  
  Food(
      {required this.name,
      required this.desc,
      required this.image,
      required this.flav,
      required this.price})
      : super(name, desc, image, flav, price);

 

  static Food _$FoodFromJson(Map<String, dynamic> json) => Food(
  name: json['name'] as String,
  desc: json['desc'] as String,
  image: json['image'] as String,
  flav: json['flav'] as String,
  price: json['price'] as double,
);

 static Map<String, dynamic> _$FoodToJson(Food instance) => <String, dynamic>{
      'name': instance.name,
      'desc': instance.desc,
      'image': instance.image,
      'flav': instance.flav,
      'price': instance.price,
    };  
      
  factory Food.fromJson(Map<String, dynamic> json)=> _$FoodFromJson(json);
  static Map<String, dynamic> toJson() => _$FoodToJson(this);

  final FoodRef = FirebaseFirestore.instance.collection('listfood').withConverter<Food>(
      fromFirestore: (snapshot, _) => Food.fromJson(snapshot.data()!),
      toFirestore: (food, _) => Food.toJson(),
    );
 
  static var foodList = [
    Food(
      name: 'Fraise Cream',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control to these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 2.50,
      image: 'assets/images/food1.png',
      flav: 'Strawberry Flovour Sweet Ice Cream',
    ),
    Food(
      name: 'Mandarine',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control to these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 3.50,
      image: 'assets/images/food2.png',
      flav: 'Caramel Flovour Sweet Ice Cream',
    )
  ];
}

class Beverage extends MyCard {
  @override
  String name;
  @override
  String desc;
  @override
  String image;
  @override
  String flav;
  @override
  double price;

  Beverage(
      {required this.name,
      required this.desc,
      required this.image,
      required this.flav,
      required this.price})
      : super(name, desc, image, flav, price);

  static var beverageList = [
    Beverage(
      name: 'test',
      desc: 'We have test',
      image: 'assets/images/food1.png',
      price: 3.0,
      flav: 'Strawberry test',
    ),
  ];
}

Error straight error _$FoodToJson(this); static Map<String, dynamic> toJson() => _$FoodToJson(this); Which I myself do not know where I went wrong. And can the code fetch data from the database? I'm a newbie. Because someone said that it can fetch data from database like doc[index]["name"] to replace name in foodlist.

If solve the error of line static Map<String, dynamic> toJson() => _$FoodToJson(this); Is it possible to use Food.toJson().name like the code below?

static var foodList = [
    Food(
      name: Food.toJson().name,
      desc: Food.toJson().desc,          
      price: Food.toJson().price
      image: Food.toJson().image,
      flav: Food.toJson().flav,
    ),
]

enter image description here

CodePudding user response:

Firstly you have configured @JsonSerializable incorrectly I will recommend you to go through this video which explains how to configure @JsonSerializable with build_runner. Run flutter pub run build_runner build every time when you make changes in the models file.

I have recreated the issue in my setup and found that to use @JsonSerializable() on inherited classes we have to use @JsonSerializable(explicitToJson: true) refer this answer from similar thread.

I have updated your code and posted in this gist: models.dart. Run flutter pub run build_runner build then import this file wherever you want and use firebase withConvertor as following:

import './models.dart';
void call() async {
    final foodRef =
        FirebaseFirestore.instance.collection('listfood').withConverter<Food>(
              fromFirestore: (snapshot, _) => Food.fromJson(snapshot.data()!),
              toFirestore: (food, _) => food.foodtoJson(),
            );
    await foodRef.add(Food(
      name: 'Mandarine',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control over these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 3.50,
      image: 'assets/images/food2.png',
      flav: 'Caramel Flavour Sweet Ice Cream',
    )); //adding a sample document for testing

    await foodRef.get().then((QuerySnapshot snapshot) => {
          snapshot.docs.forEach((doc) {
            print(doc["name"]);
            print(doc["desc"]);
            print(doc["price"]);
            print(doc["image"]);
            print(doc["flav"]);
          })
        });
  }

You may need to make changes in the above according to your requirement. For more information follow the official flutterfire documentation and for @JsonSerializable go through this thread

  • Related