Сбой выполнения для задачи ‘: app: compileFlutterBuildDebug’.> Процесс ‘команда’C:srcflutterbinflutter.bat » завершено с ненулевым значением выхода 1

#android #flutter #dart #firebase-realtime-database

#Android #flutter #dart #firebase-realtime-database

Вопрос:

На этой странице отображается синтаксическая ошибка

В документе QueryDocumentSnapshot Тип аргумента ‘Map<String, dynamic> Function()’ не может быть присвоен типу параметра ‘Map<String, dynamic>’.dartargument_type_not_assignable

lib/ services/firestore_service.dart

  import 'package:firestoreD/cloud_firestore.dart';
 import 'package:firestoreD/models/product.dart';

 class FirestoreService {
 // ignore: deprecated_member_use
 Firestore _db = Firestore.instance;

 Future<void> saveProduct(Product product){
  // ignore: deprecated_member_use
   return _db.collection('products').document(product.productId).setData(product.toMap());
 }

 // ignore: missing_return
 Stream<List<Product>> getProducts(){
 // ignore: deprecated_member_use
 return _db.collection('products').snapshots().map((snapshot) => snapshot.documents.map((document) 
   =>Product.fromFirestore(document.data)).toList());
 }

Future<void> removeProduct(String productId){
// ignore: deprecated_member_use
 return _db.collection('products').document(productId).delete();
    }


  }
  

На этой странице отображается синтаксическая ошибка

Продукт Product.fromFirestore (Карта<Строка, динамический> firestore) пакет:firestore_crud /модели / продукт.dart

‘fromFirestore’ не может использоваться для именования конструктора и статического поля в этом классе. Попробуйте переименовать либо конструктор, либо поле.dart(конфликтующий_конструктор_и_статическое_поле)

lib/models /product.dart

   class Product{
  final String productId;
  final String name;
  final double price;

  static var fromFirestore;

  Product({this.productId,this.price, this.name});

  Map<String,dynamic> toMap(){
  return {
    'productId' : productId, 
    'name' : name,
    'price' : price
   };
  }

  Product.fromFirestore(Map<String,dynamic> firestore)
  : productId = firestore['productId'],
    name = firestore['name'],
    price = firestore['price'];
  }
  

lib /main.dart

   import 'package:firestoreD/providers/product_provider.dart';
  import 'package:firestoreD/screens/products.dart';
  import 'package:firestoreD/services/firestore_service.dart';
  import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';

  void main() => runApp(MyApp());

  class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
  final firestoreService = FirestoreService();

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => ProductProvider()),
        StreamProvider(create: (context)=> firestoreService.getProducts()),
        ],
      child: MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Products(),
    ),
   );
   }
   }
  

pubspec.yaml

   name: firestoreD
  description: A new Flutter project.

  # The following defines the version and build number for your application.
  # A version number is three numbers separated by dots, like 1.2.43
  # followed by an optional build number separated by a  .
  # Both the version and the builder number may be overridden in flutter
  # build by specifying --build-name and --build-number, respectively.
  # In Android, build-name is used as versionName while build-number used as versionCode.
  # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
  # In iOS, build-name is used as CFBundleShortVersionString while build-number used as 
  CFBundleVersion.
  # Read more about iOS versioning at
    
 version: 1.0.0 1

 environment:
 sdk: ">=2.7.0 <3.0.0"

 dependencies:
   flutter:
     sdk: flutter

   # The following adds the Cupertino Icons font to your application.
   # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3
    firebase_core: ^0.5.0
    cloud_firestore: ^0.14.0 2
    provider: ^4.3.2 1
    uuid: ^2.2.0

     dev_dependencies:
       flutter_test:
        sdk: flutter


   # For information on the generic Dart part of this file, see the
   # following page: https://dart.dev/tools/pub/pubspec

   # The following section is specific to Flutter.
   flutter:

   # The following line ensures that the Material Icons font is
   # included with your application, so that you can use the icons in
   # the material Icons class.
   uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
  

При запуске отображается ошибка такого типа

lib/models /product.dart:18:3: Ошибка: конфликты с участником ‘из firestore’. Product.fromFirestore (Map<String,dynamic> firestore) ^ lib/models/product.dart:6:14: Ошибка: конфликты с конструктором ‘Product.fromFirestore’. статическая переменная из Firestore; ^

СБОЙ: сбой сборки с исключением.

  • Где: Script ‘C:srcflutterpackagesflutter_toolsgradleflutter.gradle ‘ строки: 896

  • Что пошло не так: сбой выполнения для задачи ‘: app: compileFlutterBuildDebug’.

Процесс ‘команда’C:srcflutterbinflutter.bat » завершено с ненулевым значением выхода 1

  • Попробуйте: запустите с параметром —stacktrace, чтобы получить трассировку стека. Запустите с параметром —info или —debug, чтобы получить больше выходных данных журнала. Запустите с помощью —scan, чтобы получить полную информацию.

  • Получите дополнительную помощь поhttps://help.gradle.org

Ответ №1:

Используйте factory в вашей модели класса.

Удалите эту строку -> «статическая переменная из Firestore;«

Обновите свой класс, чтобы он был таким :

 class Product{
  final String productId;
  final String name;
  final double price;
 
  Product({this.productId,this.price, this.name});

  Map<String,dynamic> toMap(){
  return {
    'productId' : productId, 
    'name' : name,
    'price' : price
   };
  }


  //FACTORY parse from snapshot
  factory Product.fromSnapshot(DocumentSnapshot snapshot) {
    //Todo set values from snapshot
  }

  //FACTORY parse from  Map
  factory Product.fromFirestore(Map<String,dynamic> firestore){
    //Todo set values from map
    return {
        'productId' : firestore['productId'],
        'name' : firestore['name'],
        'price' : firestore['price'],
    };
  }
}