TransWikia.com

Error in fluttter: type 'AsyncSnapshot' is not a subtype of type 'List'

Stack Overflow en español Asked by LizzP on December 23, 2020

I’m making an app in flutter, but I have a problem when want to do the providers, the erros is in the class CategoryProvider, I guees. Can any one help? please, My teacher said that programming was not for girls, but I want to show that it is not. About the error, i’m calling category "alarm" in my ecommerce app, and when i push the button it error appears

    import 'package:flutter/material.dart';
import 'package:motorsuchiha/model/products.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class CategoryProvider with ChangeNotifier {
  Product alarmasData;

  List<Product> alarmas = [];
  // ignore: missing_return
  Future<void> getAlarmasData() async {
    List<Product> newList = [];
    // ignore: deprecated_member_use
    QuerySnapshot alarmasSnapShot = await Firestore.instance
        .collection("category")
        // ignore: deprecated_member_use
        .document("4ton5n1tQBHMnJ5jmJ4l")
        .collection("alarmas")
        // ignore: deprecated_member_use
        .getDocuments();

    alarmasSnapShot.docs.forEach(
      (element) {
        alarmasData = Product(
            image: element.data()["image"],
            name: element.data()["name"],
            precio: element.data()["precio"]);
        newList.add(alarmasData);
      },
    );
    alarmas = newList;
  }

  List<Product> get getAlarmasList {
    return alarmas;
  }
}

the error is this: type ‘AsyncSnapshot’ is not a subtype of type ‘List’

Main

 import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:motorsuchiha/Paginas/inicioPag.dart';
import 'package:motorsuchiha/Rutas.dart';
import 'package:motorsuchiha/provider/category_provider.dart';
import 'package:motorsuchiha/provider/product_provider.dart';
import 'package:provider/provider.dart';

import 'Login.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Widget rootPage = Login(); //Pagina de inicio
  Future<Widget> estadoDelUsuario() async =>
      await FirebaseAuth.instance.currentUser == null ? Login() : inicioPag();
  // se pregunta si se esta loggeado y dependiendo de eso se muestra la pagina de inicio correspondiente

  @override
  void initState() {
    //de los primeros metodos que se inician
    // TODO: implement initState
    super.initState();
    estadoDelUsuario().then((Widget page) {
      setState(() {
        rootPage = page; //se muestra la pagina obtenida de la pregunta
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<CategoryProvider>(
          create: (context) => CategoryProvider(),
        ),
        ChangeNotifierProvider<ProductProvider>(
          create: (context) => ProductProvider(),
        ),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: rootPage,
        //Pagina inicio
        routes: buildAppRoutes(), //Rutas
      ),
    );
    // ignore: unused_label
  }
}

cuando se especifica el error me suelta esto: The relevant error-causing widget was MaterialApp

Esta es la parte donde llama a las categorias desde la pagina de inicio

return FutureBuilder(
                  future: Firestore.instance
                      .collection("category")
                      .document("4ton5n1tQBHMnJ5jmJ4l")
                      .collection("alarmas")
                      .getDocuments(),
                  builder:
                      (context, AsyncSnapshot<QuerySnapshot> alarmasSnapshot) {
                    if (alarmasSnapshot.connectionState ==
                        ConnectionState.waiting) {
                      return Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                    // ignore: unused_local_variable
                    List<DocumentSnapshot> docs = snapshot.data.docs;
                    alarmas = alarmasSnapshot;

One Answer

Recomendaría usar un StreamBuilder en vez de un FutureBuilder, algo así:

StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('tucoleccion')
          .doc(FirebaseAuth.instance.currentUser.uid)
          .collection('tuotracoleccion')
          .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(
                child: Column(
              children: [
                CircularProgressIndicator(),
                Text('Cargando...'),
              ],
            ));

            break;
          default:
            return ListView(
              children: snapshot.data.docs.map((DocumentSnapshot document) {
                return Column(
                    children: <Widget>[
                      RaisedButton(
                          child: Text(document['Campos del Documento'],
                          onPressed: () async {
                          }),
                    ],
                  );
              
              }).toList(),
            );
        }
      },
    );

También deberías comprobar las versiones de los plugins que estás usando, los nuevos cambiaron su nomenclatura, el código que te envié se aplica a las nuevas versiones.

Answered by elreyes on December 23, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP