Home > Back-end >  How to display a list of map in firestore and shows them in flutter
How to display a list of map in firestore and shows them in flutter

Time:12-20

I have the below model:

class UserInfoModel {
  String? image;
  String? name;
  String? country;
  String? city;
  String? position;
  List<UserSkills>? userSkills;
  UserInfoModel(
      {this.image, this.name, this.country, this.position, this.userSkills});

  UserInfoModel.fromJson(dynamic json) {
    image = json['user_image'];
    name = json['name'];
    country = json['country'];
    city = json['city'];
    position = json['position'];
    userSkills = [
      for (final skill in json['skills'] ?? []) UserSkills.fromJson(skill),
    ];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['user_image'] = this.image;
    data['name'] = this.name;
    data['country'] = this.country;
    data['city'] = this.city;
    data['position'] = this.position;
    data['skills'] = [for (final skill in this.userSkills ?? []) skill.toJson()];
    return data;
  }
}

class UserSkills {
  String? skillName;
  String? skillPerc;

  UserSkills({this.skillName, this.skillPerc});

  UserSkills.fromJson(dynamic json) {
    skillName = json['skill_name'];
    skillPerc = json['skill_perc'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['skill_name'] = this.skillName;
    data['skill_perc'] = this.skillPerc;
    return data;
  }
}

which is related to below image fire store:

enter image description here

I tried to create two methods one reads the user Info and the other method supposed to read the user skills, so here's the below code I have:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:haroonpf/enums/screen_state.dart';
import 'package:haroonpf/presentation/screens/home/models/user_info.dart';
import 'package:haroonpf/utils/constants.dart';
import '../../base_view_model.dart';

class HomeViewModel extends BaseViewModel {
  UserInfoModel? userModel;
  List<UserSkills> userSkills = [];


  void getUserData() async {
    await FirebaseFirestore.instance
        .collection('users')
        .doc(uId)
        .get()
        .then((value) {
      // print("fbValues: "   value.data().toString());
      userModel = UserInfoModel.fromJson(value.data());
    }).catchError((error) {
      print(error.toString());
    });
    setState(ViewState.Idle);
  }

  Future<List<UserSkills>> getUserSkills() async {
    CollectionReference getSkills =
    FirebaseFirestore.instance.collection('users');
    await getSkills.get().then((snapshot) {
      if (userSkills.isNotEmpty) userSkills.clear();
      snapshot.docs.forEach((element) {
        userSkills.add(UserSkills.fromJson(element.data()));
        print("my skills:"   element.data().toString());
      });
    });
    setState(ViewState.Idle);
    return userSkills;
  }

}

so in my Skills widget class I tried to retrieve data as the below code:

import 'package:flutter/material.dart';
import 'package:haroonpf/presentation/screens/home/viewmodel/home_view_model.dart';
import 'package:haroonpf/utils/animation/animated_progress_indicator.dart';
import 'package:haroonpf/utils/constants.dart';

import '../../../../../base_screen.dart';

class Skills extends StatelessWidget {
  const Skills({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BaseScreen<HomeViewModel>(onModelReady: (homeViewModel) {
      homeViewModel.getUserSkills();
    }, builder: (context, homeViewModel, _) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Divider(),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: defaultPadding),
            child: Text(
              "Framework out skills",
              style: Theme.of(context).textTheme.subtitle2,
            ),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Row(
              children: [
                ...homeViewModel.userSkills.map(
                  (skills) => Expanded(
                    child: AnimatedCircularProgressIndicator(
                      percentage: double.parse(skills.skillPerc!),
                      label: skills.skillName.toString(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    });
  }
}

but I found the below error:

Unexpected null value.

So it seems that because I didn't refers tot the doc id, as I tried to add the doc id it doesn't work...

So how can I retrieve the skills data to the AnimatedCircularProgressIndicator correctly?

CodePudding user response:

Unexpected null value.

Do you know what line is causing this error?


I'm not sure I understand your approach to the HomeViewModel class. If you modify getUserData to return a Future<UserInfoModel> then you could just pass it to a FutureBuilder in your Skills widget:

class HomeViewModel extends BaseViewModel {
  UserInfoModel? userModel;

  Future<UserInfoModel> getUserData() async {
    // not sure what setState does here but it was in the function to begin with
    setState(ViewState.Idle); 
    
    // here I am returning a cached userModel.
    // remove the following line of code if you don't actually want caching.
    if (userModel != null) return userModel;

    final value =
        await FirebaseFirestore.instance.collection('users').doc(uId).get();
    userModel = UserInfoModel.fromJson(value.data());
    return userModel;
  }
}

And then in your Skills widget, create the FutureBuilder, and then loop over the List<UserSkills> within your UserInfoModel.

class Skills extends StatelessWidget {
  const Skills({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BaseScreen<HomeViewModel>(onModelReady: (homeViewModel) {
      // homeViewModel.getUserSkills();
    }, builder: (context, homeViewModel, _) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Divider(),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: defaultPadding),
            child: Text(
              "Framework out skills",
              style: Theme.of(context).textTheme.subtitle2,
            ),
          ),
          FutureBuilder<UserInfoModel>(
            future: homeViewModel.getUserData(),
            builder: (context, snapshot) => SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Row(
                children: [
                  // loop over the skills to display each one
                  for (final skill in snapshot.data?.userSkills ?? [])
                    Expanded(
                      child: AnimatedCircularProgressIndicator(
                        percentage: double.parse(skill.skillPerc!),
                        label: skill.skillName.toString(),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ],
      );
    });
  }
}
  • Related