Home > Back-end >  Firebase: How to fetch data from an array field and print it in console?
Firebase: How to fetch data from an array field and print it in console?

Time:12-17

Almost all tutorials and articles I have watched and read always lead to complex things like Streambuilder or Futurebuilder. I just want to print the data from an array field in the console. Nothing extraordinary.

I want to fetch this data right here.

enter image description here

CodePudding user response:

To get the data, do this:

final doc = await FirebaseFirestore.instance.doc('goals/7L3n...').get();
final data = (doc.data()) as Map<String, dynamic>;
for (final photo in data['photos'] as List<String>) {
  print(photo);
}
print(data['photos'][0]); // should print (https://www...)
print(data['photos'][1]);

Below is a cleaner (better) approach:

First define goal model (in a separate file).

// install json_serializable, json_annotation, equatable
import 'package:json_annotation/json_annotation.dart';
import 'package:equatable/equatable.dart';

@JsonSerializable(
  explicitToJson: true,
  fieldRename: FieldRename.snake,
  includeIfNull: false,
)
class Goal extends Equatable {
  final String goalName;
  final List<String> photos;
  final String someText;

  const Goal({
    required this.goalName,
    required this.photos,
    required this.someText,
  });

  Goal copyWith({
    String? goalName,
    List<String>? photos,
    String? someText,
  }) {
    return Goal(
      goalName: goalName ?? this.goalName,
      photos: photos ?? this.photos,
      someText: someText ?? this.someText,
    );
  }

  factory GoalModel.fromJson(Map<String, dynamic> json) =>
      _$GoalModelFromJson(json);
  Map<String, dynamic> toJson() => _$GoalModelToJson(this);

  factory GoalModel.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    _,
  ) {
    return _$GoalModelFromJson(snapshot.data()!);
  }

  @override
  List<Object?> get props => [goalName, photos, someText];
}

run flutter pub run build_runner watch --delete-conflicting-outputs; on your terminal.

Then fetch your photo like this:

// import goal model here.
final goalDoc = await FirebaseFirestore.instance
    .doc('goals/7L3n...')
    .withConverter<Goal>(
      fromFirestore: Goal.fromFirestore,
      toFirestore: (data, _) => data.toJson(),
    )
    .get();
final goal = goalDoc.data()!;
for (final photo in goal.photos) {
  print(photo);
}
  • Related