问:
Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true
I am back again with the issue related to the question already posted by me on stack overflow Error: '_elements.contains(element)': is not true

this issue has been plaguing me but i was unable to reproduce the same issue and now i have somehow tried to repro again and I have posted the code for everyone to figure out what is it that i am doing wrong that's throwing up this assertion error and crashing the app.

I am new to programming and any help would be greatly appreciated. I have trimmed down the code and I am aware of the some of the bugs. But, the only main concern is the Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true. and Failed assertion: line 1766 pos 12: '_elements.contains(element)': is not true.

Steps to reproduce.

main.dart

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;
  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);
  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;
  int noOfBranches = 0;
  int itemCount;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });
            print('no of branches = $noOfBranches');
            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                data.keys.forEach((k) {
                  BranchSetUpModelData x = new BranchSetUpModelData(
                    b.value['branchDetails']['branchName'],
                    b.value['branchDetails']['hostelType'],
                    b.value['branchDetails']['area'],
                    b.value['branchDetails']['city'],
                  );
                  print('details from for each loop');
                  ProjectModel projectModelData = new ProjectModel(x);

                  projectModel.add(projectModelData);
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });
            setState(() {
              noOfBranches = mapKeys.length;
              itemCount = noOfBranches;
            });
            print('no of branches = $noOfBranches');

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
    print('noOfBranches in init state= $noOfBranches');
  }

  @override
  Widget build(BuildContext context) {
    print('noof branches inside widget build = $noOfBranches');
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: new Container(
          child: new ListView.builder(
            padding: const EdgeInsets.only(
              left: 4.0,
              right: 4.0,
            ),
            itemCount: itemCount,
            itemBuilder: (BuildContext context, int index) {
              if (noOfBranches != 0) {
                // children: <Widget>[

                return new InkWell(
                  onTap: (() {
                    /*Navigate here to a different page*/
                  }),
                  child: new Card(
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          //margin: const EdgeInsets.only(top:16.0),
                          padding: const EdgeInsets.only(top: 16.0),
                          child: new Row(
                            children: <Widget>[
                              new Expanded(
                                child: new Row(
                                  children: <Widget>[
                                    new Container(
                                        margin: const EdgeInsets.only(
                                            left: 16.0,
                                            right: 8.0,
                                            top: 4.0,
                                            bottom: 4.0),
                                        child: new IconButton(
                                            icon: new Icon(Icons.call),
                                            onPressed: (() {}))),
                                    new Container(
                                      child: new Text(
                                        '80/125',
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              new Expanded(
                                child: new Row(
                                  textDirection: TextDirection.rtl,
                                  children: [
                                    new Container(
                                      margin:
                                          const EdgeInsets.only(right: 16.0),
                                      child: new Text(
                                        projectModel[index]
                                            .branchesModel
                                            .hostelType,
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        new Container(
                          margin:
                              const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 4.0),
                          child: new Row(children: <Widget>[
                            new Text(
                              projectModel[index].branchesModel.branchName,
                              style: new TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ]),
                        ),
                        new Container(
                          margin: const EdgeInsets.only(
                              left: 16.0, right: 16.0, bottom: 8.0),
                          child: new Row(
                            children: <Widget>[
                              new Text(projectModel[index].branchesModel.city),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ); // InkWell ends here so this has to go into ListView.builder
              } else {
                itemCount = 1;

                return new Center(
                  child: new Column(
//            mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,

                    children: <Widget>[
                      new Text(
                        'Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 24.0,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      new Text(
                        'Please click below + icon to Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 16.0,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ), // ListView.builder ends here.
        ),
      ),
    );
  }
}
</code>```

globals.dart

```<code>library my_app.globals;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

final FirebaseAuth auth = FirebaseAuth.instance;
final DatabaseReference databaseReference = FirebaseDatabase.instance.reference();
</code>```

addnewbranch.dart

```<code>import 'dart:async';
import 'package:meta/meta.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:untitled1/main.dart';
import './globals.dart' as gl;

class BranchSetupModel {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetupModel(this.branchName, this.hostelType, this.area, this.city);
}

BranchSetupModel branchSetupModel =
    new BranchSetupModel('', 'Hostel Type', '', '');

class AddNewBranch extends StatefulWidget {
  const AddNewBranch({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _AddNewBranchState();
  }
}

class _AddNewBranchState extends State<AddNewBranch> {
  String actionsString = 'Next';
  String userUid;

  TextEditingController _branchNameController = new TextEditingController();
  TextEditingController _areaController = new TextEditingController();
  TextEditingController _cityController = new TextEditingController();

  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool _formWasEdited = false;
  bool _autovalidate = false;
  String dropDownvalue = 'Hostel Type';

  //FocusNode _branchManagerNameFocusNode = new FocusNode();

  String _validateName(String value) {
    _formWasEdited = true;
    if (value.isEmpty) return 'Name is required.';
    final RegExp nameExp = new RegExp(r'^[A-Za-z ]+$');
    if (!nameExp.hasMatch(value))
      return 'Please enter only alphabetical characters and spaces.';
    return null;
  }

  Future<Null> getUserUid() async {
    try {
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      userUid = user.uid;
      print(userUid);
    } catch (Exception) {
      print(Exception.toString());
    }
  }

  @override
  void initState() {
    super.initState();
    getUserUid();
    _branchNameController =
        new TextEditingController(text: branchSetupModel.branchName);
    _areaController = new TextEditingController(text: branchSetupModel.area);
    _cityController = new TextEditingController(text: branchSetupModel.city);
    dropDownvalue = branchSetupModel.hostelType;
    branchSetupModel = new BranchSetupModel('', 'Hostel Type', '', '');
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      title: 'Branch Setup',
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Add New Branch'),
          backgroundColor: Colors.teal[300],
          leading: new IconButton(
            icon: new Icon(Icons.arrow_back),
            onPressed: (() {
              print('back button clicked');
              //to be removed and to include functionality here
              Navigator.push(
                context,
                new MaterialPageRoute(
                  builder: (_) => new Branches(),
                ),
              );
            }),
          ),
          actions: <Widget>[
            new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new FlatButton(
                    child: new Text(
                      actionsString,
                      style: new TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: () {
                      print('Save button clicked');

                      String pushKey = gl.databaseReference
                          .child('data')
                          .child('branches')
                          .push()
                          .key;
                      gl.databaseReference
                          .child('data')
                          .child('branches')
                          .child(pushKey)
                          .child('branchDetails')
                          .set({
                        "branchName": branchSetupModel.branchName,
                        "hostelType": branchSetupModel.hostelType,
                        "area": branchSetupModel.area,
                        "city": branchSetupModel.city,
                        "pushKey": pushKey
                      });
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (_) => new Branches(),
                        ),
                      );
                    },
                    splashColor: const Color(0xFF229E9C),
                  ),
                ],
              ),
            ),
          ],
        ),
        body: new Form(
          key: _formKey,
          child: new ListView(
            children: <Widget>[
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Text('Hostel Type'),
                  ],
                ),
              ),
              new Container(
                //height: 56.0,
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Column(
                  children: <Widget>[
                    new DropdownButton<String>(
                      //key: _dropDownKey,
                      hint: new Text(dropDownvalue),

                      items: <String>[
                        'Mens',
                        'Womens',
                      ].map(
                        (String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        },
                      ).toList(),
                      onChanged: (String value) {
                        setState(() {
                          dropDownvalue = value;
                          branchSetupModel.hostelType = value;
                          print(branchSetupModel.hostelType);
                        });
                      },
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        autocorrect: false,
                        decoration: new InputDecoration(
                          labelText: 'Branch Name',
                        ),
                        controller: _branchNameController,
                        onChanged: (String value) {
                          branchSetupModel.branchName =
                              _branchNameController.text;
                          print(branchSetupModel.branchName);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'Area/Location',
                        ),
                        controller: _areaController,
                        onChanged: (String value) {
                          branchSetupModel.area = value;
                          print(branchSetupModel.area);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                ),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'City',
                        ),
                        controller: _cityController,
                        onChanged: (String value) {
                          branchSetupModel.city = value;
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

pubspec.yaml

```<code>name: untitled1
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^1.0.1
  firebase_analytics: ^0.1.1
  firebase_auth: ^0.3.1
  firebase_database: ^0.1.2
  firebase_storage: ^0.0.7

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
</code>```

Please integrate the firebase app to run the code before trying to reproduce the error and make sure the read and write access set to 'true' as I have not added any authentication.

As far as I know the error only occurs in the main.dart file.It works fine for a few times and then the errors start coming in. First, it throws up the error RangeError (index): Invalid value: Valid value range is empty: 0 this error is for the ListView.builder() and then the other two assertion errors come up.

Please can someone tell me what I am doing wrong or is there a different way to achieve the same goal without these errors.

output from flutter doctor command.

```<code>    [√] Flutter (on Microsoft Windows [Version 10.0.15063], locale en-GB, channel alpha)
    • Flutter at C:\Users\Prayuta\flutter
    • Framework revision e8aa40eddd (3 weeks ago), 2017-10-17 15:42:40 -0700
    • Engine revision 7c4142808c
    • Tools Dart version 1.25.0-dev.11.0

[√] Android toolchain - develop for Android devices (Android SDK 27.0.0)
    • Android SDK at C:\Users\Prayuta\AppData\Local\Android\sdk
    • Platform android-27, build-tools 27.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] Android Studio (version 3.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] IntelliJ IDEA Community Edition (version 2017.2)
    • Flutter plugin version 18.4
    • Dart plugin version 172.4343.25

[√] Connected devices
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Process finished with exit code 0.
</code>```

答:
One of my colleague actually changed the way I've built my ListView.builder and I am not seeing the error now. I'll keep an eye on this and post any new ways to answer this question or any errors creeping up again.

I only changed the main.dart file which I have posted for reference.

main.dart

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;

  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;

  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);

  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });

            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                setState(() {
                  data.keys.forEach((k) {
                    BranchSetUpModelData x = new BranchSetUpModelData(
                      b.value['branchDetails']['branchName'],
                      b.value['branchDetails']['hostelType'],
                      b.value['branchDetails']['area'],
                      b.value['branchDetails']['city'],
                    );
                    print('details from for each loop');
                    ProjectModel projectModelData = new ProjectModel(x);

                    projectModel.add(projectModelData);
                  });
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
  }

  @override
  Widget build(BuildContext context) {
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: (projectModel.length == 0)
            ? new Center(
                child: new Column(
//            mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,

                  children: <Widget>[
                    new Text(
                      'Setup your Hostel',
                      style: new TextStyle(
                        fontSize: 24.0,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    new Text(
                      'Please click below + icon to Setup your Hostel',
                      style: new TextStyle(
                        fontSize: 16.0,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                ),
              )
            : new Container(
                child: new ListView.builder(
                  padding: const EdgeInsets.only(
                    left: 4.0,
                    right: 4.0,
                  ),
                  itemCount: projectModel.length,
                  itemBuilder: (BuildContext context, int index) {
                    // children: <Widget>[

                    return new InkWell(
                      onTap: (() {
                        /*Navigate here to a different page*/
                      }),
                      child: new Card(
                        child: new Column(
                          children: <Widget>[
                            new Container(
                              //margin: const EdgeInsets.only(top:16.0),
                              padding: const EdgeInsets.only(top: 16.0),
                              child: new Row(
                                children: <Widget>[
                                  new Expanded(
                                    child: new Row(
                                      children: <Widget>[
                                        new Container(
                                            margin: const EdgeInsets.only(
                                                left: 16.0,
                                                right: 8.0,
                                                top: 4.0,
                                                bottom: 4.0),
                                            child: new IconButton(
                                                icon: new Icon(Icons.call),
                                                onPressed: (() {}))),
                                        new Container(
                                          child: new Text(
                                            '80/125',
                                            style: new TextStyle(
                                              fontSize: 18.0,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  new Expanded(
                                    child: new Row(
                                      textDirection: TextDirection.rtl,
                                      children: [
                                        new Container(
                                          margin: const EdgeInsets.only(
                                              right: 16.0),
                                          child: new Text(
                                            projectModel[index]
                                                .branchesModel
                                                .hostelType,
                                            style: new TextStyle(
                                              fontSize: 18.0,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            new Container(
                              margin: const EdgeInsets.fromLTRB(
                                  16.0, 8.0, 16.0, 4.0),
                              child: new Row(children: <Widget>[
                                new Text(
                                  projectModel[index].branchesModel.branchName,
                                  style: new TextStyle(
                                    fontSize: 24.0,
                                  ),
                                ),
                              ]),
                            ),
                            new Container(
                              margin: const EdgeInsets.only(
                                  left: 16.0, right: 16.0, bottom: 8.0),
                              child: new Row(
                                children: <Widget>[
                                  new Text(
                                      projectModel[index].branchesModel.city),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ); // InkWell ends here so this has to go into ListView.builder
                  },
                ), // ListView.builder ends here.
              ),
      ),
    );
  }
}
</code>```

I hope this will help everyone who is struggling with the same use case to solve their problem,
Many Thanks.
Mahi.

Body:
I am back again with the issue related to the question already posted by me on stack overflow Error: '_elements.contains(element)': is not true

this issue has been plaguing me but i was unable to reproduce the same issue and now i have somehow tried to repro again and I have posted the code for everyone to figure out what is it that i am doing wrong that's throwing up this assertion error and crashing the app.

I am new to programming and any help would be greatly appreciated. I have trimmed down the code and I am aware of the some of the bugs. But, the only main concern is the Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true. and Failed assertion: line 1766 pos 12: '_elements.contains(element)': is not true.

Steps to reproduce.

main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;
  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);
  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;
  int noOfBranches = 0;
  int itemCount;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });
            print('no of branches = $noOfBranches');
            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                data.keys.forEach((k) {
                  BranchSetUpModelData x = new BranchSetUpModelData(
                    b.value['branchDetails']['branchName'],
                    b.value['branchDetails']['hostelType'],
                    b.value['branchDetails']['area'],
                    b.value['branchDetails']['city'],
                  );
                  print('details from for each loop');
                  ProjectModel projectModelData = new ProjectModel(x);

                  projectModel.add(projectModelData);
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });
            setState(() {
              noOfBranches = mapKeys.length;
              itemCount = noOfBranches;
            });
            print('no of branches = $noOfBranches');

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
    print('noOfBranches in init state= $noOfBranches');
  }

  @override
  Widget build(BuildContext context) {
    print('noof branches inside widget build = $noOfBranches');
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: new Container(
          child: new ListView.builder(
            padding: const EdgeInsets.only(
              left: 4.0,
              right: 4.0,
            ),
            itemCount: itemCount,
            itemBuilder: (BuildContext context, int index) {
              if (noOfBranches != 0) {
                // children: <Widget>[

                return new InkWell(
                  onTap: (() {
                    /*Navigate here to a different page*/
                  }),
                  child: new Card(
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          //margin: const EdgeInsets.only(top:16.0),
                          padding: const EdgeInsets.only(top: 16.0),
                          child: new Row(
                            children: <Widget>[
                              new Expanded(
                                child: new Row(
                                  children: <Widget>[
                                    new Container(
                                        margin: const EdgeInsets.only(
                                            left: 16.0,
                                            right: 8.0,
                                            top: 4.0,
                                            bottom: 4.0),
                                        child: new IconButton(
                                            icon: new Icon(Icons.call),
                                            onPressed: (() {}))),
                                    new Container(
                                      child: new Text(
                                        '80/125',
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              new Expanded(
                                child: new Row(
                                  textDirection: TextDirection.rtl,
                                  children: [
                                    new Container(
                                      margin:
                                          const EdgeInsets.only(right: 16.0),
                                      child: new Text(
                                        projectModel[index]
                                            .branchesModel
                                            .hostelType,
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        new Container(
                          margin:
                              const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 4.0),
                          child: new Row(children: <Widget>[
                            new Text(
                              projectModel[index].branchesModel.branchName,
                              style: new TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ]),
                        ),
                        new Container(
                          margin: const EdgeInsets.only(
                              left: 16.0, right: 16.0, bottom: 8.0),
                          child: new Row(
                            children: <Widget>[
                              new Text(projectModel[index].branchesModel.city),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ); // InkWell ends here so this has to go into ListView.builder
              } else {
                itemCount = 1;

                return new Center(
                  child: new Column(
//            mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,

                    children: <Widget>[
                      new Text(
                        'Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 24.0,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      new Text(
                        'Please click below + icon to Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 16.0,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ), // ListView.builder ends here.
        ),
      ),
    );
  }
}

globals.dart

library my_app.globals;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

final FirebaseAuth auth = FirebaseAuth.instance;
final DatabaseReference databaseReference = FirebaseDatabase.instance.reference();

addnewbranch.dart

import 'dart:async';
import 'package:meta/meta.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:untitled1/main.dart';
import './globals.dart' as gl;

class BranchSetupModel {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetupModel(this.branchName, this.hostelType, this.area, this.city);
}

BranchSetupModel branchSetupModel =
    new BranchSetupModel('', 'Hostel Type', '', '');

class AddNewBranch extends StatefulWidget {
  const AddNewBranch({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _AddNewBranchState();
  }
}

class _AddNewBranchState extends State<AddNewBranch> {
  String actionsString = 'Next';
  String userUid;

  TextEditingController _branchNameController = new TextEditingController();
  TextEditingController _areaController = new TextEditingController();
  TextEditingController _cityController = new TextEditingController();

  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool _formWasEdited = false;
  bool _autovalidate = false;
  String dropDownvalue = 'Hostel Type';

  //FocusNode _branchManagerNameFocusNode = new FocusNode();

  String _validateName(String value) {
    _formWasEdited = true;
    if (value.isEmpty) return 'Name is required.';
    final RegExp nameExp = new RegExp(r'^[A-Za-z ]+$');
    if (!nameExp.hasMatch(value))
      return 'Please enter only alphabetical characters and spaces.';
    return null;
  }

  Future<Null> getUserUid() async {
    try {
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      userUid = user.uid;
      print(userUid);
    } catch (Exception) {
      print(Exception.toString());
    }
  }

  @override
  void initState() {
    super.initState();
    getUserUid();
    _branchNameController =
        new TextEditingController(text: branchSetupModel.branchName);
    _areaController = new TextEditingController(text: branchSetupModel.area);
    _cityController = new TextEditingController(text: branchSetupModel.city);
    dropDownvalue = branchSetupModel.hostelType;
    branchSetupModel = new BranchSetupModel('', 'Hostel Type', '', '');
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      title: 'Branch Setup',
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Add New Branch'),
          backgroundColor: Colors.teal[300],
          leading: new IconButton(
            icon: new Icon(Icons.arrow_back),
            onPressed: (() {
              print('back button clicked');
              //to be removed and to include functionality here
              Navigator.push(
                context,
                new MaterialPageRoute(
                  builder: (_) => new Branches(),
                ),
              );
            }),
          ),
          actions: <Widget>[
            new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new FlatButton(
                    child: new Text(
                      actionsString,
                      style: new TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: () {
                      print('Save button clicked');

                      String pushKey = gl.databaseReference
                          .child('data')
                          .child('branches')
                          .push()
                          .key;
                      gl.databaseReference
                          .child('data')
                          .child('branches')
                          .child(pushKey)
                          .child('branchDetails')
                          .set({
                        "branchName": branchSetupModel.branchName,
                        "hostelType": branchSetupModel.hostelType,
                        "area": branchSetupModel.area,
                        "city": branchSetupModel.city,
                        "pushKey": pushKey
                      });
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (_) => new Branches(),
                        ),
                      );
                    },
                    splashColor: const Color(0xFF229E9C),
                  ),
                ],
              ),
            ),
          ],
        ),
        body: new Form(
          key: _formKey,
          child: new ListView(
            children: <Widget>[
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Text('Hostel Type'),
                  ],
                ),
              ),
              new Container(
                //height: 56.0,
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Column(
                  children: <Widget>[
                    new DropdownButton<String>(
                      //key: _dropDownKey,
                      hint: new Text(dropDownvalue),

                      items: <String>[
                        'Mens',
                        'Womens',
                      ].map(
                        (String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        },
                      ).toList(),
                      onChanged: (String value) {
                        setState(() {
                          dropDownvalue = value;
                          branchSetupModel.hostelType = value;
                          print(branchSetupModel.hostelType);
                        });
                      },
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        autocorrect: false,
                        decoration: new InputDecoration(
                          labelText: 'Branch Name',
                        ),
                        controller: _branchNameController,
                        onChanged: (String value) {
                          branchSetupModel.branchName =
                              _branchNameController.text;
                          print(branchSetupModel.branchName);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'Area/Location',
                        ),
                        controller: _areaController,
                        onChanged: (String value) {
                          branchSetupModel.area = value;
                          print(branchSetupModel.area);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                ),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'City',
                        ),
                        controller: _cityController,
                        onChanged: (String value) {
                          branchSetupModel.city = value;
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

pubspec.yaml

name: untitled1
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^1.0.1
  firebase_analytics: ^0.1.1
  firebase_auth: ^0.3.1
  firebase_database: ^0.1.2
  firebase_storage: ^0.0.7

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

Please integrate the firebase app to run the code before trying to reproduce the error and make sure the read and write access set to 'true' as I have not added any authentication.

As far as I know the error only occurs in the main.dart file.It works fine for a few times and then the errors start coming in. First, it throws up the error RangeError (index): Invalid value: Valid value range is empty: 0 this error is for the ListView.builder() and then the other two assertion errors come up.

Please can someone tell me what I am doing wrong or is there a different way to achieve the same goal without these errors.

output from flutter doctor command.

    [√] Flutter (on Microsoft Windows [Version 10.0.15063], locale en-GB, channel alpha)
    • Flutter at C:\Users\Prayuta\flutter
    • Framework revision e8aa40eddd (3 weeks ago), 2017-10-17 15:42:40 -0700
    • Engine revision 7c4142808c
    • Tools Dart version 1.25.0-dev.11.0

[√] Android toolchain - develop for Android devices (Android SDK 27.0.0)
    • Android SDK at C:\Users\Prayuta\AppData\Local\Android\sdk
    • Platform android-27, build-tools 27.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] Android Studio (version 3.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] IntelliJ IDEA Community Edition (version 2017.2)
    • Flutter plugin version 18.4
    • Dart plugin version 172.4343.25

[√] Connected devices
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Process finished with exit code 0.

Body:
One of my colleague actually changed the way I've built my ListView.builder and I am not seeing the error now. I'll keep an eye on this and post any new ways to answer this question or any errors creeping up again.

I only changed the main.dart file which I have posted for reference.

main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;

  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;

  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);

  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });

            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                setState(() {
                  data.keys.forEach((k) {
                    BranchSetUpModelData x = new BranchSetUpModelData(
                      b.value['branchDetails']['branchName'],
                      b.value['branchDetails']['hostelType'],
                      b.value['branchDetails']['area'],
                      b.value['branchDetails']['city'],
                    );
                    print('details from for each loop');
                    ProjectModel projectModelData = new ProjectModel(x);

                    projectModel.add(projectModelData);
                  });
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
  }

  @override
  Widget build(BuildContext context) {
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: (projectModel.length == 0)
            ? new Center(
                child: new Column(
//            mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,

                  children: <Widget>[
                    new Text(
                      'Setup your Hostel',
                      style: new TextStyle(
                        fontSize: 24.0,
                        color: Colors.grey[400],
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    new Text(
                      'Please click below + icon to Setup your Hostel',
                      style: new TextStyle(
                        fontSize: 16.0,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                ),
              )
            : new Container(
                child: new ListView.builder(
                  padding: const EdgeInsets.only(
                    left: 4.0,
                    right: 4.0,
                  ),
                  itemCount: projectModel.length,
                  itemBuilder: (BuildContext context, int index) {
                    // children: <Widget>[

                    return new InkWell(
                      onTap: (() {
                        /*Navigate here to a different page*/
                      }),
                      child: new Card(
                        child: new Column(
                          children: <Widget>[
                            new Container(
                              //margin: const EdgeInsets.only(top:16.0),
                              padding: const EdgeInsets.only(top: 16.0),
                              child: new Row(
                                children: <Widget>[
                                  new Expanded(
                                    child: new Row(
                                      children: <Widget>[
                                        new Container(
                                            margin: const EdgeInsets.only(
                                                left: 16.0,
                                                right: 8.0,
                                                top: 4.0,
                                                bottom: 4.0),
                                            child: new IconButton(
                                                icon: new Icon(Icons.call),
                                                onPressed: (() {}))),
                                        new Container(
                                          child: new Text(
                                            '80/125',
                                            style: new TextStyle(
                                              fontSize: 18.0,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  new Expanded(
                                    child: new Row(
                                      textDirection: TextDirection.rtl,
                                      children: [
                                        new Container(
                                          margin: const EdgeInsets.only(
                                              right: 16.0),
                                          child: new Text(
                                            projectModel[index]
                                                .branchesModel
                                                .hostelType,
                                            style: new TextStyle(
                                              fontSize: 18.0,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            new Container(
                              margin: const EdgeInsets.fromLTRB(
                                  16.0, 8.0, 16.0, 4.0),
                              child: new Row(children: <Widget>[
                                new Text(
                                  projectModel[index].branchesModel.branchName,
                                  style: new TextStyle(
                                    fontSize: 24.0,
                                  ),
                                ),
                              ]),
                            ),
                            new Container(
                              margin: const EdgeInsets.only(
                                  left: 16.0, right: 16.0, bottom: 8.0),
                              child: new Row(
                                children: <Widget>[
                                  new Text(
                                      projectModel[index].branchesModel.city),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ); // InkWell ends here so this has to go into ListView.builder
                  },
                ), // ListView.builder ends here.
              ),
      ),
    );
  }
}

I hope this will help everyone who is struggling with the same use case to solve their problem,
Many Thanks.
Mahi.


来源: stackexchange

问:
Angular2 how to know if an input is of type radio with reactive forms
I am building reactive forms form in angular. I have simple radio button with gender name:

```<code>this._form = this._formBuilder.group({
            gender: ['', Validators.required]
        });
</code>```

Template:

```<code>            <div class="form-group">
                <h4>What is your gender?</h4>
                <div class="form-group">
                    <label class="custom-control custom-radio">
                        <input value="male" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Male</span>
                    </label>
                    <label class="custom-control custom-radio">
                        <input value="female" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Female</span>
                    </label>
                    <app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'gender','required')" errorMsg="Field is required"></app-field-error-display>
                </div>
            </div>
</code>```

I can access the control field by name like this:

```<code>public GetControl(form: FormGroup, field: string){
        return form.get(field);
    }
</code>```

Based on this how do I access the attribute value of type="radio"? I want to know if input control is of type radio.

答:
EDIT: This can't be solved with Reactive forms, but you can with Dynamic forms: https://angular.io/guide/dynamic-form

The following is a dirty workarround (not recommended):

Using native JS with not a good practice in Angular, because you lose a lot of Angular features, but if you're just looking for a quick and dirty fix here it is:

```<code>public GetControl(form: FormGroup, field: string){
    let el = document.querySelector('input[name="'+field+'"]');
    if(el.getAttribute('type') == 'radio'){
        // This is a radio input
    }
    return form.get(field);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am building reactive forms form in angular. I have simple radio button with gender name:

this._form = this._formBuilder.group({
            gender: ['', Validators.required]
        });

Template:

What is your gender?

                        <input value="male" name="gender" type="radio" class="custom-control-input" formControlName="gender">

                        Male

                        <input value="female" name="gender" type="radio" class="custom-control-input" formControlName="gender">

                        Female

                    <app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'gender','required')" errorMsg="Field is required"></app-field-error-display>

I can access the control field by name like this:

public GetControl(form: FormGroup, field: string){
        return form.get(field);
    }

Based on this how do I access the attribute value of type="radio"? I want to know if input control is of type radio.

Body:
EDIT: This can't be solved with Reactive forms, but you can with Dynamic forms: https://angular.io/guide/dynamic-form

The following is a dirty workarround (not recommended):

Using native JS with not a good practice in Angular, because you lose a lot of Angular features, but if you're just looking for a quick and dirty fix here it is:

public GetControl(form: FormGroup, field: string){
    let el = document.querySelector('input[name="'+field+'"]');
    if(el.getAttribute('type') == 'radio'){
        // This is a radio input
    }
    return form.get(field);
}


问:
What does '@' at beginning of a variable mean?

Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

```<code>try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}
</code>```

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?

答:
Shameless rip of Michael Meadows answer to a duplicate question follows.

The @ symbol allows you to use reserved word. For example:

```<code>int @class = 15;
</code>```

The above works, when the below wouldn't:

```<code>int class = 15;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?

Body:
Shameless rip of Michael Meadows answer to a duplicate question follows.

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;


问:
Why did mysql data ownership change to systemd-journal-remote after running a docker container
I have the mysql database stored in /home/mysql instead of /var/lib/mysql. The directory used to be owned by mysql. However, when I run the command docker-compose up with this yml file:

```<code>version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"
</code>```

The docker container is able to run, but the entire folder and files in /home/mysql are owned by systemd-journal-remote, which causes the node server fails to connect to mariadb. I have to stop the docker instance, restore the mysql folder ownership and delete ib_logfile0 and ib_logfile1.

Why does mounting /home/mysql cause such a fatal problem?

Update:

My solution is to add user: "mysql":

```<code>version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"
</code>```

答: Most likely, uid of your user systemd-journal-remote is the same as uid of user mysqld in container. Check with ls -n. To avoid confusion, either use common uids, perhaps test as root:root with chmod o+rwx.

ContentLicense: CC BY-SA 3.0

Body:
I have the mysql database stored in /home/mysql instead of /var/lib/mysql. The directory used to be owned by mysql. However, when I run the command docker-compose up with this yml file:

version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"

The docker container is able to run, but the entire folder and files in /home/mysql are owned by systemd-journal-remote, which causes the node server fails to connect to mariadb. I have to stop the docker instance, restore the mysql folder ownership and delete ib_logfile0 and ib_logfile1.

Why does mounting /home/mysql cause such a fatal problem?

Update:

My solution is to add user: "mysql":

version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"


问:
Form checkbox field value is not getting passed to Laravel controller
In my registration form, I have a checkbox where a user can accept to receive newsletters.

In create function I want to display all passed data:

```<code>protected function create(array $data)
{
    dd($data);
}
</code>```

The name of my checkbox field is newsletter. When I do dd(), I don't get the value for the newsletter, only for: name, email and password.

If I add this newsletter to Validator then it is shown.

```<code>protected function validator(array $data)
{
    return Validator::make($data, [
        'name'       => 'required|max:255',
        'email'      => 'required|email|max:255|unique:users',
        'password'   => 'required|min:6|confirmed',
        'newsletter' => 'required',
    ]);
}
</code>```

Now, when I do dd() it is passed, but I don't want this checkbox to be required. It should be optional. Should I change something in Validator or?

答:
Your newsletter field is a checkbox. When a html form is submitted and the checkbox is not checked, this field will not be available in the posted data. If the checkbox is checked it will be available. This is default html behavior, nothing you can do about this.

To check if the checkbox has been checked in your code, you can use the following:

```<code>$checked = array_key_exists('newsletter', $data);
</code>```

Body:
In my registration form, I have a checkbox where a user can accept to receive newsletters.

In create function I want to display all passed data:

protected function create(array $data)
{
    dd($data);
}

The name of my checkbox field is newsletter. When I do dd(), I don't get the value for the newsletter, only for: name, email and password.

If I add this newsletter to Validator then it is shown.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name'       => 'required|max:255',
        'email'      => 'required|email|max:255|unique:users',
        'password'   => 'required|min:6|confirmed',
        'newsletter' => 'required',
    ]);
}

Now, when I do dd() it is passed, but I don't want this checkbox to be required. It should be optional. Should I change something in Validator or?

Body:
Your newsletter field is a checkbox. When a html form is submitted and the checkbox is not checked, this field will not be available in the posted data. If the checkbox is checked it will be available. This is default html behavior, nothing you can do about this.

To check if the checkbox has been checked in your code, you can use the following:

$checked = array_key_exists('newsletter', $data);


答:
Regardless of the backend, when a checkbox is not checked, its value won't be sent as part of the request to the server. That's how browsers work and that's why you won't be seeing a newsletter field when dumping the request.

However, when you use Laravel's validator and mention the field in the rules, Laravel does it for you and sets its value. To not to make it required, use the sometimes rule.

That would do it just for the purpose of dumping the data. But when implementing the real logic, instead of dumping data, you'll hopefully be utilizing the given request instance, facade or helper which will return a falsy value for non-existent parameters. So, you're just fine without adding the additional rule.

Or, you can set a default value for the newsletter field making sure if the data is not there, new registrations will happen with the desired default state.

By the way, you wanna make sure that your controller method is accepting a Request instance instead of an array.

Title: Form checkbox field value is not getting passed to Laravel controller


问:
Raycasting Layermask vs RaycastAll
Hi I have a small question on how the raycasting with layermasks work vs using RaycastAll.

I am trying to project my rays from inside my object and layermask the rays to collide with the same layer as the original object, therefore i need to ignore the "hit" on the original object  itself.

My question is: when Raycasting uses a layermask does it register a collision with other undesirable layers too and then simply ignore them, or does it not even register a collision with those layers in the first place? Would it be worse or equal on performance if I used RaycastAll to logically decide to respond to a layer or not vs somehow using strictly layermasks? Or is it not even an appreciable difference?

I know some posts say that "if you cast it from inside the object it wont collide with that object" but evidently it does.

Thanks

答:
You can take a look at official Unity's physics preformance tutorial. To start with, Raycast is rather cheap operation but it's performance really depends on how you actually do Raycasting. For example, for one of your questions - RaycastAll is more expensive than doing Raycast on a separate layer, it's also mentioned in the link above. It's based on how actually physics work. Unity doesn't implement physics itself, instead it uses existing solutions (like PhysiX for 3d, and earlier it was Box2d for 2d physics).

Also the length of your ray actually influences Raycast's performance. The shorter ray you cast the better performance you get. The worst case is Raycasting to infinity. Another case is that Collider.Raycast is cheaper than Physics.Raycast.

It's no secret, that there is nothing more that some bunch of math equations behind physics in game development so you may thing in such things - the simplier equation you have, the better performance and time to complete you get. So Raycast can be treated as system of equations where you have the equation of the line (actual Raycast) and some number of equations, which describe some 2d/3d object in plane/space and the task is two calculate the points of intersection between your line (Ray) and other objects.

If you don't have complex physics in your game you may not see the difference between RaycastAll and Raycast with layermask, or shorter ray's length, but performance really differs.

Title: Raycasting Layermask vs RaycastAll


问:
Visual Studio 2008 unit testing using the same file resource
I am using the built-in unit testing framework of Visual Studio 2008 to get my feet wet with TDD of a C# WinForms application. The application works with proprietary image data formats and I've broken up sample files into their component sections (header, metadata, single frames, all frames, etc) to allow for testing. Several of my test methods use the same data chunk and when I choose the 'Run All Tests in Solution' option, the tests using the same data chunk fail with "System.IO.IOException: The process cannot access the file 'datachunk.dat' because it is being used by another process." These tests pass when they are run individually. Is there a way I can tell Visual Studio not to try and run these tests at the same time or am I going about this the wrong way?</p>

答:
I can suggest several things:

Check if you can change the flags when the file is opened. Effectively you should open it as shared for reading.

Read the complete content of the file into a byte array and use that one as a source in your tests. That doesn't really change much.

Use shared resource and TestInitialize.


问:
itextpdf exception when closing document with JFreeChart added
I am trying to add a JFreeChart to my PDF file and am getting a exception deep in the bowels of itextpdf. I have no clue what I am doing wrong or what the exception is really telling me. Here is my code segment:

```<code>try {
            PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(filePath.getText()));
            document.open();
            document.add(setParagraph("Stoker Monitor Report",titleFont));
            document.add(setParagraph(name.getText(),subTitleFont));
            document.add(setParagraph(date.getText(),dateFont));
            PdfContentByte cb=writer.getDirectContent();
            Float height=7.f;
            Float width=11.69f;
            PdfTemplate tp=cb.createTemplate(width,height);
            Graphics2D g2D=new PdfGraphics2D(cb,width,height);
            Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
            Chart.getInstance().getChart().draw(g2D,r2D);
            tp.addTemplate(tp, 0, 0);
        } catch (FileNotFoundException | DocumentException e1) {
            System.err.println("Unable to open "+filePath.getText()+" for writing");
            e1.printStackTrace();
        }
        document.close();
</code>```

The exception is on the close. Here is the stacktrace:

```<code>Exception in thread "AWT-EventQueue-0" com.itextpdf.text.exceptions.IllegalPdfSyntaxException: Unbalanced save/restore state operators.
at com.itextpdf.text.pdf.PdfContentByte.sanityCheck(PdfContentByte.java:4193)
at com.itextpdf.text.pdf.PdfContentByte.reset(PdfContentByte.java:1813)
at com.itextpdf.text.pdf.PdfContentByte.reset(PdfContentByte.java:1801)
at com.itextpdf.text.pdf.PdfWriter.resetContent(PdfWriter.java:746)
at com.itextpdf.text.pdf.PdfDocument.endPage(PdfDocument.java:1061)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:882)
at com.itextpdf.text.Document.close(Document.java:415)
at stokerMonitor.CreateReport$CreateButtonListener.actionPerformed(CreateReport.java:152)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

I have no idea what this means since it involves none of my code. I assume that there is something in the parameters that I am passing that is causing this but I have no idea what to look at. Can some please interpret this exception for me and point me in the right direction? TIA.

答:
You forgot one line when you copied your code from who knows where:

```<code>PdfTemplate tp=cb.createTemplate(width,height);
Graphics2D g2D=new PdfGraphics2D(cb,width,height);
Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
Chart.getInstance().getChart().draw(g2D,r2D);
g2D.dispose();
cb.addTemplate(tp, 0, 0);
</code>```

Without the dispose(), you can get all kinds of weird errors.

Also tp.addTemplate(tp, 0, 0); should be cb.addTemplate(tp, 0, 0);

Body:
I am trying to add a JFreeChart to my PDF file and am getting a exception deep in the bowels of itextpdf. I have no clue what I am doing wrong or what the exception is really telling me. Here is my code segment:

try {
            PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(filePath.getText()));
            document.open();
            document.add(setParagraph("Stoker Monitor Report",titleFont));
            document.add(setParagraph(name.getText(),subTitleFont));
            document.add(setParagraph(date.getText(),dateFont));
            PdfContentByte cb=writer.getDirectContent();
            Float height=7.f;
            Float width=11.69f;
            PdfTemplate tp=cb.createTemplate(width,height);
            Graphics2D g2D=new PdfGraphics2D(cb,width,height);
            Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
            Chart.getInstance().getChart().draw(g2D,r2D);
            tp.addTemplate(tp, 0, 0);
        } catch (FileNotFoundException | DocumentException e1) {
            System.err.println("Unable to open "+filePath.getText()+" for writing");
            e1.printStackTrace();
        }
        document.close();

The exception is on the close. Here is the stacktrace:

Exception in thread "AWT-EventQueue-0" com.itextpdf.text.exceptions.IllegalPdfSyntaxException: Unbalanced save/restore state operators.
at com.itextpdf.text.pdf.PdfContentByte.sanityCheck(PdfContentByte.java:4193)
at com.itextpdf.text.pdf.PdfContentByte.reset(PdfContentByte.java:1813)
at com.itextpdf.text.pdf.PdfContentByte.reset(PdfContentByte.java:1801)
at com.itextpdf.text.pdf.PdfWriter.resetContent(PdfWriter.java:746)
at com.itextpdf.text.pdf.PdfDocument.endPage(PdfDocument.java:1061)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:882)
at com.itextpdf.text.Document.close(Document.java:415)
at stokerMonitor.CreateReport$CreateButtonListener.actionPerformed(CreateReport.java:152)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I have no idea what this means since it involves none of my code. I assume that there is something in the parameters that I am passing that is causing this but I have no idea what to look at. Can some please interpret this exception for me and point me in the right direction? TIA.

Body:
You forgot one line when you copied your code from who knows where:

PdfTemplate tp=cb.createTemplate(width,height);
Graphics2D g2D=new PdfGraphics2D(cb,width,height);
Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
Chart.getInstance().getChart().draw(g2D,r2D);
g2D.dispose();
cb.addTemplate(tp, 0, 0);

Without the dispose(), you can get all kinds of weird errors.

Also tp.addTemplate(tp, 0, 0); should be cb.addTemplate(tp, 0, 0);