'Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null' : Streambuilder

I'm applying CRUD operation on firebase's realtime database, it works fine until my list is empty.

Reference pointer(_passref) is pointing to start of the database so when a list is empty, pointer is passing null to streambuilder and error occurs.

Code Block:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase/firebase_options.dart';



Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform,);

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App',
      home: const MyHomePage(title: 'Food List'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final _formKey = GlobalKey<FormState>();
  final DatabaseReference _passref = FirebaseDatabase.instance.ref().child('passbook');

  late String name;
  late String email;
  late String passwd;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Center(
          child: Text(
            widget.title,
            style: TextStyle(color: Colors.deepOrange),
          ),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[_form(),
            StreamBuilder(stream: _passref.orderByKey().onValue,
                builder: (context, snapshot) {
                  final tilesList = <ListTile>[];
                  if (snapshot.hasData) {
                    final passwd = Map<dynamic, dynamic>.from(
                        (snapshot.data! as dynamic).snapshot.value);
                    passwd.forEach((key, value) {
                      final nextpass = Map<String, dynamic>.from(value);
                      final passtile = ListTile(
                        title: Text(nextpass['Domain']),
                        subtitle: Text(nextpass['Email']),
                      );
                      tilesList.add(passtile);
                    });
                  }
                  return Expanded(
                      child: ListView(
                        shrinkWrap: true,
                        padding: const EdgeInsets.all(8),
                        children: tilesList,
                      )
                  );
                })
          ],
        ),
      ),
    );
  }

  _form() =>
      Container(
        padding: EdgeInsets.symmetric(vertical: 35, horizontal: 30),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(labelText: 'Domain Name',
                ),
                validator: (val) =>
                (val?.length == 0 ? 'This field is mandatory' : null),
                onSaved: (val) => setState(() => name = val!),
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Email ID',
                ),
                validator: (val) =>
                val!.length == 0 ? 'This field is mandatory' : null,
                onSaved: (val) => setState(() => email = val!),
              ),
              TextFormField(
                obscureText: true,
                decoration: InputDecoration(labelText: 'Password',
                ),
                validator: (val) =>
                val!.length == 0 ? 'This field is mandatory' : null,
                onSaved: (val) => setState(() => passwd = val!),
              ),
              Container(
                margin: EdgeInsets.all(10.0),
                child: ElevatedButton(
                  onPressed: () => _onSubmit(),
                  child: Text("Save"),
                  style: ElevatedButton.styleFrom(
                    primary: Colors.deepOrange,),
                ),
              ),
            ],
          ),
        ),
      );


  _onSubmit() async {
    var form = _formKey.currentState;
    if (form!.validate()) {
      form.save();
      print(1111111);
      FocusManager.instance.primaryFocus?.unfocus();
      await _passref.push().set(
          {"Domain": name, "Email": email, 'Password': passwd});

      form.reset();
    }
  }
}

Error Block:

Performing hot restart...
Waiting for connection from debug service on Chrome...
Restarted application in 786ms.

======== Exception caught by widgets library =======================================================
The following TypeErrorImpl was thrown building StreamBuilder<DatabaseEvent>(dirty, state: _StreamBuilderBaseState<DatabaseEvent, AsyncSnapshot<DatabaseEvent>>#39d6c):
Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null'

The relevant error-causing widget was: 
  StreamBuilder<DatabaseEvent> StreamBuilder:file:///C:/Kunal_CSU/CSCI%20567%20Mobile%20Development/Projects/Assignment4/lib/main%20-%20Copy.dart:66:13
When the exception was thrown, this was the stack: 
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49      throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 84:3        castError
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 452:10  cast
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/classes.dart 635:14     as_C
packages/firebase/main%2520-%2520Copy.dart 72:36                                                                               <fn>
packages/flutter/src/widgets/async.dart 442:81                                                                                 build
packages/flutter/src/widgets/async.dart 124:48                                                                                 build
packages/flutter/src/widgets/framework.dart 4904:27                                                                            build
packages/flutter/src/widgets/framework.dart 4788:15                                                                            performRebuild
.
.
.
packages/flutter/src/widgets/framework.dart 3823:13                                                                            inflateWidget
packages/flutter/src/widgets/binding.dart 1198:16                                                                              [_rebuild]
packages/flutter/src/widgets/binding.dart 1167:5                                                                               mount
packages/flutter/src/widgets/binding.dart 1112:16                                                                              <fn>
packages/flutter/src/widgets/framework.dart 2654:19                                                                            buildScope
packages/flutter/src/widgets/binding.dart 1111:12                                                                              attachToRenderTree
packages/flutter/src/widgets/binding.dart 943:24                                                                               attachRootWidget
packages/flutter/src/widgets/binding.dart 924:7                                                                                <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19           internalCallback
====================================================================================================

======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 99757 pixels on the bottom.

The relevant error-causing widget was: 
  Column Column:file:///C:/Kunal_CSU/CSCI%20567%20Mobile%20Development/Projects/Assignment4/lib/main%20-%20Copy.dart:63:16
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.

Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.

The specific RenderFlex in question is: RenderFlex#2f40a relayoutBoundary=up2 OVERFLOWING
...  needs compositing
...  parentData: offset=Offset(0.0, 0.0) (can use size)
...  constraints: BoxConstraints(0.0<=w<=500.0, 0.0<=h<=514.4)
...  size: Size(500.0, 514.4)
...  direction: vertical
...  mainAxisAlignment: start
...  mainAxisSize: max
...  crossAxisAlignment: center
...  verticalDirection: down

====================================================================================================

======== Exception caught by widgets library =======================================================
The following TypeErrorImpl was thrown building StreamBuilder<DatabaseEvent>(dirty, state: _StreamBuilderBaseState<DatabaseEvent, AsyncSnapshot<DatabaseEvent>>#39d6c):
Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null'

The relevant error-causing widget was: 
  StreamBuilder<DatabaseEvent> StreamBuilder:file:///C:/Kunal_CSU/CSCI%20567%20Mobile%20Development/Projects/Assignment4/lib/main%20-%20Copy.dart:66:13
When the exception was thrown, this was the stack: 
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49      throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 84:3        castError
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 452:10  cast
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/classes.dart 635:14     as_C
packages/flutter/src/rendering/binding.dart 363:5                                                                              [_handlePersistentFrameCallback]
packages/flutter/src/scheduler/binding.dart 1144:15                                                                            [_invokeFrameCallback]
packages/flutter/src/scheduler/binding.dart 1081:9                                                                             handleDrawFrame
packages/flutter/src/scheduler/binding.dart 862:7                                                                              <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19           internalCallback
====================================================================================================

======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 99757 pixels on the bottom.

The relevant error-causing widget was: 
  Column Column:file:///C:/Kunal_CSU/CSCI%20567%20Mobile%20Development/Projects/Assignment4/lib/main%20-%20Copy.dart:63:16
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.

Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.

The specific RenderFlex in question is: RenderFlex#2f40a relayoutBoundary=up2 OVERFLOWING
...  needs compositing
...  parentData: offset=Offset(0.0, 0.0) (can use size)
...  constraints: BoxConstraints(0.0<=w<=500.0, 0.0<=h<=514.4)
...  size: Size(500.0, 514.4)
...  direction: vertical
...  mainAxisAlignment: start
...  mainAxisSize: max
...  crossAxisAlignment: center
...  verticalDirection: down

====================================================================================================

This is what show when list is empty

This when list has some data



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source