Home > database >  flutter add firebase key as String to list
flutter add firebase key as String to list

Time:10-18

I want to add the key to a list, but it is added as object instead of String.

 var myList  = [];

    await database.ref().child("team").orderByChild(uid).equalTo("test").once().then((DatabaseEvent databaseEvent){
      if (databaseEvent.snapshot.value != null) {
        Map<dynamic, dynamic>values = databaseEvent.snapshot.value as Map<dynamic, dynamic>;
        myList.add(values.keys.toString());
        print(myList);
      }
    });

output: [(-NE0pl0456878VCsb8)]

output I want: [-NE0pl0456878VCsb8]

Database structure

 team
  -NE0pl0456878VCsb8
  -irthjdhs46jfj43gh

CodePudding user response:

You should get keys by index, you are adding all keys to your list

instead of myList.add(values.kays.toString()); use this one myList.add(values.keys[0].toString());

CodePudding user response:

I tried to simulate here see if it works for you:

import 'package:flutter/material.dart';

class ScreenOne extends StatefulWidget {
  ScreenOne({Key? key}) : super(key: key);

  @override
  State<ScreenOne> createState() => _ScreenOneState();
}

class _ScreenOneState extends State<ScreenOne> {
  //Map<dynamic, dynamic>
  final values = {'keyOne': 'abc', 1: 'dfg', 'keyT': 46};

  var myList = ['keyFour', 'keySix'];

  void addAll() {
    setState(() {
      myList.addAll(values.keys.map((e) => e.toString()));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ScreenOne'),
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                addAll();
              },
              child: const Text('Add')),
          Expanded(
            child: ListView.builder(
              itemCount: myList.length,
              itemBuilder: (_, index) {
                return Card(
                  child: Text(myList[index]),
                );
              },
            ),
          )
        ],
      ),
    );
  }
}
  • Related