Невозможно получить данные из облачного хранилища в listview — Flutter

#java #android #flutter #google-cloud-firestore #cloud

#java #Android #флаттер #google-cloud-firestore #облако

Вопрос:

Я хочу получить данные из базы данных (CloudFirestore) и отобразить их в listview. Доступ к базе данных работает нормально, поскольку я могу войти в систему. Однако после входа в систему данные не отображаются в listview. Я добавил сообщение об ошибке и коды для listview. Благодарен, если кто-то может помочь.

Ошибка при запуске приложения

 Launching libmain.dart on sdk gphone x86 in debug mode...
Running Gradle task 'assembleDebug'...
 Built buildappoutputsflutter-apkapp-debug.apk.
Debug service listening on ws://127.0.0.1:64363/KVv5OZ9vh50=/ws
Syncing files to device sdk gphone x86...
D/skia    ( 9851): Errors:
D/skia    ( 9851): 
D/skia    ( 9851): Shader compilation error
D/skia    ( 9851): ------------------------
D/skia    ( 9851): Errors:
D/skia    ( 9851): 
W/IInputConnectionWrapper( 9851): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper( 9851): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper( 9851): getTextAfterCursor on inactive InputConnection
I/flutter ( 9851): Building login screen
I/flutter ( 9851): Building login screen
I/flutter ( 9851): Building login screen
W/System  ( 9851): Ignoring header X-Firebase-Locale because its value was null.
W/System  ( 9851): Ignoring header X-Firebase-Locale because its value was null.
D/FirebaseAuth( 9851): Notifying id token listeners about user ( zENUTXicQqOe4wPARJFTXO99kG63 ).
D/FirebaseAuth( 9851): Notifying auth state listeners about user ( zENUTXicQqOe4wPARJFTXO99kG63 ).
I/flutter ( 9851): Log In: FirebaseUser(Instance of 'PlatformUser')
I/flutter ( 9851): building Feed
W/DynamiteModule( 9851): Local module descriptor class for providerinstaller not found.
I/TetheringManager( 9851): registerTetheringEventCallback:com.example.pricelistapp
I/DynamiteModule( 9851): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 9851): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/le.pricelistap( 9851): The ClassLoaderContext is a special shared library.
I/le.pricelistap( 9851): The ClassLoaderContext is a special shared library.
V/NativeCrypto( 9851): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 286 native methods...
W/le.pricelistap( 9851): Accessing hidden method Ljava/security/spec/ECParameterSpec;->getCurveName()Ljava/lang/String; (greylist, reflection, allowed)
I/ProviderInstaller( 9851): Installed default security provider GmsCore_OpenSSL
W/le.pricelistap( 9851): Accessing hidden field Ljava/net/Socket;->impl:Ljava/net/SocketImpl; (greylist, reflection, allowed)
W/le.pricelistap( 9851): Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (greylist,core-platform-api, linking, allowed)
W/le.pricelistap( 9851): Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (greylist,core-platform-api, linking, allowed)
W/le.pricelistap( 9851): Accessing hidden field Ljava/io/FileDescriptor;->descriptor:I (greylist, JNI, allowed)
W/le.pricelistap( 9851): Accessing hidden method Ljava/security/spec/ECParameterSpec;->setCurveName(Ljava/lang/String;)V (greylist, reflection, allowed)
W/le.pricelistap( 9851): Accessing hidden method Ldalvik/system/BlockGuard;->getThreadPolicy()Ldalvik/system/BlockGuard$Policy; (greylist,core-platform-api, linking, allowed)
W/le.pricelistap( 9851): Accessing hidden method Ldalvik/system/BlockGuard$Policy;->onNetwork()V (greylist, linking, allowed)
I/flutter ( 9851): building Feed
W/le.pricelistap( 9851): Accessing hidden method Ldalvik/system/CloseGuard;->close()V (greylist,core-platform-api, linking, allowed)
 

Зависимости

  dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test:runner:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
        //implementation 'com.google.firebase:firebase-database : 19.2.0'
        implementation platform('com.google.firebase:firebase-bom:26.3.0')
        implementation 'com.google.firebase:firebase-auth'
        //implementation "androidx.multidex:multidex:2.0.0"
        implementation 'com.google.firebase:firebase-dynamic-links'
        implementation 'com.google.firebase:firebase-analytics'

    }
 

Listview:

 getFoods(FoodNotifier foodNotifier) async {
QuerySnapshot snapshot = await Firestore.instance
.collection('Foods')
.orderBy("createdAt", descending: true)
.getDocuments();
List<Food> _foodList = [];

  snapshot.documents.forEach((document) {
    Food food = Food.fromMap(document.data);
    _foodList.add(food);
  });

  foodNotifier.foodList = _foodList;
}
 

Не могли бы вы помочь?
Спасибо,
Решми

Комментарии:

1. это не способ, которым ChangeNotifier работает со списками. Вам необходимо получить доступ к значению списка и использовать функцию addAll или с помощью функции .value . Вы пытаетесь заменить экземпляр списка другим, и это не работает.

2. @MarianoZorrilla у вас есть пример?

Ответ №1:

Это пример использования ValueNotifier, но он работает аналогично другим уведомителям:

 import 'package:flutter/material.dart';
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ListExample(),
    );
  }
}

class ListExample extends StatefulWidget {
  @override
  _ListExampleState createState() => _ListExampleState();
}

class _ListExampleState extends State<ListExample> {
  ValueNotifier<List<Example>> _list = ValueNotifier(<Example>[]);

  @override
  void initState() {
    super.initState();
    _fetchList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ValueListenableBuilder<List<Example>>(
          valueListenable: _list,
          builder: (context, list, child) {
            return list.isEmpty
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemBuilder: (context, index) {
                      final item = list[index];
                      return Card(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 15, vertical: 8),
                          child:
                              Text(item.name, style: TextStyle(fontSize: 30)),
                        ),
                      );
                    },
                    itemCount: _list.value.length,
                  );
          }),
    );
  }

  _fetchList() {
    Future.delayed(const Duration(seconds: 2), () {
      final serverJson =
          '[{"name": "one", "text": "hello, guys!"}, {"name": "two", "text": "decode json"}]';
      final json = jsonDecode(serverJson) as List;
      _list.value = json.map((item) => Example.fromJson(item)).toList();
    });
  }
}

class Example {
  final String name;
  final String text;

  Example(this.name, this.text);

  factory Example.fromJson(Map<String, dynamic> json) =>
      Example(json['name'], json['text']);
}
 

Это вывод:

Будущий список

Комментарии:

1. у вас есть пример, в котором он подключается к базе данных cloud firestore?