Home > database >  The method 'call' isn't defined for the type 'BookListFoodMenuState'.Try co
The method 'call' isn't defined for the type 'BookListFoodMenuState'.Try co

Time:01-21

The method 'call' isn't defined for the type 'BookList FoodMenuState'.\Try correcting the name to the name of an existing method, or defining a method named 'call'
How to call function Call in my Food class on Column?
My Class

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';
part 'class_list_food.g.dart';

@JsonSerializable(explicitToJson: true)
class MyCard {
  final String name, desc, image, flav;
  final double price;

  MyCard(
      {required this.name,
      required this.desc,
      required this.image,
      required this.flav,
      required this.price});
  factory MyCard.fromJson(Map<String, dynamic> json) => _$MyCardFromJson(json);

  Map<String, dynamic> toJson() => _$MyCardToJson(this);
}

@JsonSerializable()
class Food extends MyCard {
  @override
  final String name, desc, image, flav;
  @override
  final double price;

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

  factory Food.fromJson(Map<String, dynamic> json) => _$FoodFromJson(json);

  Map<String, dynamic> foodtoJson() => _$FoodToJson(this);

  static var foodList = [];

  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.',
      price: 53,
      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) {
            foodList.add(Food(
              name: doc["name"],
              desc: doc["desc"],
              price: double.parse(doc["price"]),
              image: doc["image"],
              flav: doc["flav"],
            ));
          })
        });
    }
}

@JsonSerializable()
class Beverage extends MyCard {
  @override
  final String name, desc, image, flav;
  @override
  final double price;

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

  factory Beverage.fromJson(Map<String, dynamic> json) =>
      _$BeverageFromJson(json);

  Map<String, dynamic> foodtoJson() => _$BeverageToJson(this);
  static var beverageList = [
    Beverage(
      name: 'test',
      desc: 'We have test',
      image: 'assets/images/food1.png',
      price: 3.0,
      flav: 'Strawberry test',
    ),
  ];
}

Example widget to call Call() but it gives error
If I can call this part then I can fetch index data from database and insert data instead. Food.foodList.length but i can't call call() please help me or suggest a better way

class BookListFoodMenu extends StatefulWidget {
  final Widget categories;
  const BookListFoodMenu({Key? key, required this.categories})
      : super(key: key);

  @override
  State<BookListFoodMenu> createState() => _BookListFoodMenuState();
}

class _BookListFoodMenuState extends State<BookListFoodMenu> {
  
  String dropdownValue = 'TH';
  final user = FirebaseAuth.instance.currentUser!;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_none),
            onPressed: () {
              //Navigator.of(context).pushReplacement(MaterialPageRoute(
              //   builder: (BuildContext context) => MyApp()));
            },
          ),
          Align(
              alignment: Alignment.center,
              child: DropdownButton<String>(
                value: dropdownValue,
                onChanged: (String? newValue) {
                  setState(() {
                    dropdownValue = newValue!;
                  });
                },
                items: <String>['TH', 'EN', 'CN', 'TW']
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              )),
        ],
        title:
            const Text("อาหารภาคเหนือ", style: TextStyle(fontFamily: 'Mitr')),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: const EdgeInsets.all(20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: Center(
                        child: CircleAvatar(
                          radius: 72,
                          backgroundImage: NetworkImage(user.photoURL!),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text(user.displayName!,
                        style:
                            const TextStyle(fontSize: 16, fontFamily: 'Mitr')),
                  ],
                ),
              ),
              widget.categories,
              Container(
                padding: const EdgeInsets.all(20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      "Popular",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w600,
                        fontFamily: 'Mitr',
                      ),
                    ),
                    IconButton(
                        icon: Image.asset(
                          "assets/images/filter.png",
                          width: 22,
                        ),
                        onPressed: () {
                          /*Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) => const BookAllListPopular()));
                    */
                        }),
                        call(),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.only(left: 15),
                margin: const EdgeInsets.only(bottom: 10),
                height: 315,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: Food.foodList.length,
                  itemBuilder: (context, index) {
                    final food = Food.foodList[index];
                    return GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) {
                              return DetailFood(food: food);
                            },
                          ),
                        );
                      },
                      child: Container(
                        padding: const EdgeInsets.only(right: 15, left: 0),
                        width: 225,
                        child: Card(
                          elevation: 0,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          color: const Color(0xffFBCEDC),
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image.asset(
                                  food.image,
                                  width: 150,
                                  height: 130,
                                ),
                                const SizedBox(
                                  height: 20,
                                ),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      food.name,
                                      style: const TextStyle(
                                        fontFamily: 'Mitr',
                                        fontSize: 18,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    Text(
                                      food.flav,
                                      style: const TextStyle(
                                        fontFamily: 'Mitr',
                                        fontSize: 14,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 15,
                                    ),
                                    Text(
                                      "\$"   food.price.toString(),
                                      style: const TextStyle(
                                        fontFamily: 'Mitr',
                                        fontSize: 17,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),

CodePudding user response:

Your call() is a method of the class Food, so you need an instance of that class to call the method.

However, just like Food.foodList you could make is static and call it via the class name: Food.call();

You may also need to call setState() after you call completes to update the UI.

FWIW, you should try to use a proper state management technique to improve your program.

  • Related