Laurent Thomas
Laurent Thomas

Reputation: 282

Getting data from a document in FireBase and adding them into a map

I am trying to transfer my data from FireBase Collection to a map. Then, the map data will go into MultiSelectBottomSheetField.

Problems: I am getting "Instance of '_JsonQueryDocumentSnapshot'" instead of 'Home' for example.

enter image description here

I still not getting the list of context from collection into MultiSelectItem

Also, I have noticed that when I start the app, the MultiSelectionItem is empty. It is displaying "Instance of '_JsonQueryDocumentSnapshot'" when I display the main view a second time. I guess that a SetState is probably missing somewhere. But as I can not write set state in a constructor, I am puzzled.

This is driving me nuts as I do not find where the problem is coming from. Many thanks for your help.


import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:multi_select_flutter/bottom_sheet/multi_select_bottom_sheet_field.dart';
import 'package:multi_select_flutter/util/multi_select_item.dart';

String inboxTaskDisplayed='';
int nbRecord=0;
var taskSelectedID;
var taskDone;

//------TEST
class ContextExisting {
  final int id;
  final String name;

  ContextExisting({
    this.id,
    this.name,
  });
}

List<ContextExisting> _contexts = [];
List <ContextExisting>allMyContext=[];


TextEditingController passController = new TextEditingController();
//-----------------
var documentID;
var textController = TextEditingController();
var popUpTextController = TextEditingController();


//_-----------------
class Inbox_Test_For_Chip_Trial extends StatefulWidget {
  final String screenSelected;
  final String titlePage;
  Inbox_Test_For_Chip_Trial(Key key, {@required this.screenSelected, @required this.titlePage,}) : super(key: key);
  @override
  _Inbox_Test_For_Chip_TrialState createState() => _Inbox_Test_For_Chip_TrialState(screenSelected, titlePage);
}

class _Inbox_Test_For_Chip_TrialState extends State<Inbox_Test_For_Chip_Trial> {
  GlobalKey<FormState> _inboxFormKey = GlobalKey<FormState>();
  String screenSelected;
  String titlePage;

  _Inbox_Test_For_Chip_TrialState(this.screenSelected,  this.titlePage,);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
        title: new Text(titlePage + ' ('+nbRecord.toString()+')'),
    actions: <Widget>[

    ],
    ),

    backgroundColor: Colors.white,
      body: Container(
        height: 250,
        child: Column(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //FOR CONTEXT
            Flexible(child: StreamBuilder(
            stream: FirebaseFirestore.instance
          .collection('Users')
          .doc(FirebaseAuth.instance.currentUser.uid)
          .collection('contexts')
          .snapshots(),
                    builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) {
                      return Center(
                        child: CircularProgressIndicator(),
                        );
                        }
                    else {

                      var docs = snapshot.data.docs;
print('docs');
                      print (docs[2].id);

                      print(snapshot.data.docs.length);

                      int nbContext = snapshot.data.docs.length;

                      for (int i=0;i<nbContext; i++) {

                        _contexts.addAll([ContextExisting (id:i, name:snapshot.data.toString())]);
                        print(_contexts);
                      }

                return Container(
                height: MediaQuery.of(context).size.height * .78,
                width: MediaQuery.of(context).size.width,
                child: ListView(
                children: snapshot.data.docs.map((document) {
                return Wrap(
                children: [Card(
                child: SwipeActionCell(
                key: ObjectKey(document['context_Name']),
                trailingActions: <SwipeAction>[

          ],

          child: ListTile(
          trailing: IconButton(
          icon: Icon(Icons.keyboard_arrow_right),
          onPressed: () async {
          taskSelectedID = FirebaseFirestore
                .instance
                .collection('Users')
                .doc(
          FirebaseAuth.instance.currentUser
                .uid)
                .collection('contexts')
                .doc(document.id).toString();
        }
    ),

    leading: ConstrainedBox(
    constraints: BoxConstraints(
    minWidth: 30,
    minHeight: 35,
    maxWidth: 30,
    maxHeight: 35,
    ),

     //InkWell(child: Icon(Icons.check_box_outline_blank),
    ),
    title: Text(
    document['context_Name'],
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
    ),
    ),
    ),
    ),
    ]
    );
    }).toList(),
    ),
    );
    }
    }),),

            Column(children:[

              TestWidgetContext(),

            ]), //MyHomePage())
          ],
        ),
      ),
      //bottomNavigationBar:  MyBottomAppBar(),  //PersistentBottomNavBar(),
    );
  }


class TestWidgetContext extends StatefulWidget {

  TestWidgetContext({Key key})  : super(key: key);

  @override
  _TestWidgetContextState createState() => _TestWidgetContextState();
}

class _TestWidgetContextState extends State<TestWidgetContext> {
  List itemsContext;
  List<ContextExisting> _selectedContext5 = [];

  final _itemsContext = _contexts
      .map((context) => MultiSelectItem<ContextExisting>(context, context.name))
      .toList();

  @override
  void initState() {
    _selectedContext5 = _contexts;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Column(
      children: [
        MultiSelectBottomSheetField(
          buttonText: Text("Contexts"),
          onConfirm: (val2) {
            
          },

          items: _itemsContext,
         // initialValue:
         // _itemsContext,
        ),
      ],
    );
  }
}

Upvotes: 0

Views: 245

Answers (2)

Laurent Thomas
Laurent Thomas

Reputation: 282

Problem solved.

child: Column(
          //mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //FOR CONTEXT
            Flexible(child: StreamBuilder(
            stream:  FirebaseFirestore.instance
            .collection('Users')
            .doc(FirebaseAuth.instance.currentUser.uid)
            .collection('contexts')
            .snapshots(),
            builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> snapshot) {

              if (snapshot.hasError) {
              return Text('Something went wrong');
              } else if (snapshot.hasData) {
              // if connectionState is waiting
                  if (snapshot.connectionState == ConnectionState.waiting)
                  {
                  return Center(child: CircularProgressIndicator());
                  } else {

                for (int i=0;i<snapshot.data.docs.length;i++){
                 DocumentSnapshot snap = snapshot.data.docs[i];
                _contexts.add(snap['context_Name']);
                }
                }
              }

              // return widgets and use data
              return Column(children:[

                TestWidgetContext(),

              ]); //MyHomePage())

Upvotes: 1

Kaushik Chandru
Kaushik Chandru

Reputation: 17732

Since the code has a lot of errors, I am writing down my findings.

  1. allMyContext is a list and if you wish to add elements to it you should be wring it as

allMyContext.add(ContextExisting (id:i, name:doc.name));

instead of List<allMyContext> = ContextExisting (id:i, name:doc.name)

Insde the on pressed

  taskSelectedID = (document.id).toString();

since you already have taken a document you don't have to query it again

final doc = FirebaseFirestore.instance.collection('users').doc('contexts').get();

and

FirebaseFirestore.instance.collection('Users').doc(FirebaseAuth.instance.currentUser.uid).collection('contexts').snapshots(),

These two are contradictory. Is contexts a collection or a document?

Upvotes: 1

Related Questions