Home > database >  How Should I Deal with Null Values in a StreamBuilder?
How Should I Deal with Null Values in a StreamBuilder?

Time:10-29

I'm trying to build a flutter view that loads a list of items ('cost codes' in the code snippet) from a database call. This code works elsewhere in my project where I already have data in the database, but it fails when it tries to read data from an empty node. I can provide dummy data or sample data for my users on first run, but they might delete the data before adding their own, which would cause the app to crash the next time this view loads.

What's the proper way to deal with a potentially empty list in a StreamBuilder?

    @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          stream: dbPathRef.onValue,
          builder: (context, snapshot) {
            final costCodes = <CostCode>[];
            if (!snapshot.hasData) {
              return Center(
                child: Column(
                  children: const [
                    Text(
                      'No Data',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    )
                  ],
                ),
              );
            } else {
              final costCodeData =
// code fails on the following line with the error
// 'type "Null" is not a subtype of type "Map<Object?, dynamic>" in type cast'
                  (snapshot.data!).snapshot.value as Map<Object?, dynamic>;
              costCodeData.forEach(
                (key, value) {
                  final dataLast = Map<String, dynamic>.from(value);
                  final account = CostCode(
                    id: dataLast['id'],
                    name: dataLast['name'],
                  );
                  costCodes.add(account);
                },
              );
              return ListView.builder(
                shrinkWrap: false,
                itemCount: costCodes.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(
                      costCodes[index].name,
                      style: const TextStyle(color: Colors.white),
                    ),
                    subtitle: Text(
                      costCodes[index].id,
                      style: const TextStyle(color: Colors.white),
                    ),
                  );
                },
              );
            }
          },
        );
      }

CodePudding user response:

Personally I tend to avoid handling raw data from a database in the UI code and handle all of this in a repository/bloc layer.

However, to solve your issue you can simply add a ? to the end of the cast like so:

final costCodeData = (snapshot.data!).snapshot.value as Map<Object?, dynamic>?;

You will no longer get the cast exception - however you still have to test costCodeData for null.

This block of code may help:

final data = snapshot.data;
final  Map<Object?, dynamic>? costCodeData
if (data == null) {
  costCodeData = null;
} else {
  costCodeData = (snapshot.data!).snapshot.value as Map<Object?, dynamic>?;
}
if (costCodeData == null){
  // Show noData
} else {
  // Show data
}

CodePudding user response:

              final dataLast = Map<String, dynamic>.from(value);
              final account = CostCode(
                id: dataLast['id'],
                name: dataLast['name'],
              );
              costCodes.add(account);
            },

you declaired dataLast with a Map having key as String, but inside the account variable the id and name are not in the string format, keep those inside "" || '' even after modiying these, if you still face other issue try putting question mark at the end of the line (snapshot.data!).snapshot.value as Map<Object, dynamic>?

  • Related