Home > Software engineering >  I am trying to fetch data from real-time database firebase in flutter for app. So, I have tried coup
I am trying to fetch data from real-time database firebase in flutter for app. So, I have tried coup

Time:07-22

I am trying to fetch data from real-time database firebase in flutter for app. So, i have tried couple ways but couldn't make it work.

These are my current codes for retrieving data from realtime database :

return Scaffold(
  body: SafeArea(
    child: FirebaseAnimatedList(
      shrinkWrap: true,
      query: databaseRef,
      itemBuilder: (BuildContext context, DataSnapshot snapshot,
          Animation<double> animation, int index) {
        var x = snapshot.value;
        if (snapshot != null) {
          return ListTile(
            title: Text(x['name']),
            subtitle: Text(x['city']),
            trailing: IconButton(
              icon: const Icon(Icons.male),
              onPressed: () {
                var keyFinder = snapshot.key;
                Fluttertoast.showToast(msg: keyFinder!);
              },
            ),
          );
        } else {
          return const Center(child: Text("Empty data found"));
        }
      },
    ),
  ),
);

image showing the error

it show error here title: Text(x['name']), saying:

The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').

CodePudding user response:

You need to map snapshot.value to model class before access email id.

User user = snapshot.value(User.class);

CodePudding user response:

A snapshot can have no value, so when you do this:

var x = snapshot.value;

Your x variable can either be null or hold the value of the node. When you try to access a subvalue from x, the compiler warns you can x may be null.

One way to tell it that it isn't by adding an !:

title: Text(x!['name']),

I actually don't like that all that much, and typically prefer ensuring the correct type earlier, like this:

var x = snapshot.value! as Map;

So this confirms that snapshot.value isn't null with an ! again, and then also ensures you get back a Map, which your later code assumes.


You also have a blue hint under

if (snapshot != null) {

That probably tells you that snapshot can never be null. You'll want to instead check snapshot.value in there, and then swap the condition and the assignment to:

if (snapshot.value != null) {
  var x = snapshot.value! as Map;
  • Related