如何在< String>Flutter中从Firebase读取List

svdrlsy4  于 2023-05-23  发布在  Flutter
关注(0)|答案(2)|浏览(220)

我创建了一个简单的firebase,想在flutter中显示我的字符串列表,但它给出了一个快照错误,而正常的字符串(如果我删除列表,名称和大小)正常显示。如何显示列表?

class Pokemon {
  String id;
  final String name;
  final String size;
  final List<String> elements;

  Pokemon({this.id = '', required this.name, required this.size,required this.elements});

  Map<String, dynamic> toJson() => {'id': id, 'name': name, 'size': size,'elements':elements};

  static Pokemon fromJson(Map<String, dynamic> json) => Pokemon(
        id: json['id'],
        name: json['name'],
        size: json['size'],
        elements: json['elements']
      );
}

Widget buildPokemon(Pokemon pokemon, BuildContext context) => (InkWell(
onTap: () {
  Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => PokemonDetailPage(
            pokemon: pokemon,
          )));
},
child: Card(
  elevation: 10.0,
  child: Column(
    children: [
      ListTile(
          title: Text(pokemon.name),
          subtitle: Text(pokemon.size + pokemon.elements[0]),
          trailing: IconButton(
              onPressed: () {
                QuickAlert.show(
                    context: context,
                    type: QuickAlertType.confirm,
                    title: "Sure you want to remove ${pokemon.name}?",
                    onConfirmBtnTap: () {
                      DocumentReference documentReference =
                          FirebaseFirestore.instance
                              .collection('Pokemon')
                              .doc(pokemon.id);
                      documentReference.delete();
                      Navigator.pop(context);
                    });
              },
              icon: const Icon(
                Icons.delete,
                color: Colors.red,
              ))),
    ],
  ),
)));
u91tlkcl

u91tlkcl1#

elements是一个字符串列表。你有没有试过把List<String>转换成List<String>
如果不起作用,请尝试List<dynamic>

static Pokemon fromJson(Map<String, dynamic> json) => Pokemon(
        id: json['id'],
        name: json['name'],
        size: json['size'],
        elements: json['elements'] as List<String> //change this line
      );
f8rj6qna

f8rj6qna2#

这就是我如何在flutter应用程序中从firestore获取String[]的方法。

factory RecipeBookModel.fromFirestore(
 DocumentSnapshot<Map<String, dynamic>> snapshot,
 SnapshotOptions? options,
) {
 final data = snapshot.data();
 return RecipeBookModel(
  id: data?['iid'],
  name: data?['name'],
  category: data?['category'],
  recipes: data?['recipes'] is Iterable ? List<String>.from(data?['recipes']) : null, // THIS LINE
  createdBy: data?['createdBy'],
  likes: data?['likes'],
 );
}

例如在您的示例中:

...
elements: json['elmements'] is Iterable ? List<String>.from(json['elements']) : null
...

相关问题