Home > Software design >  NoSuchMethodError: The method '[]' was called on null. [Flutter]
NoSuchMethodError: The method '[]' was called on null. [Flutter]

Time:09-23

class MessageScreen extends StatefulWidget {
  @override
  _MessageScreenState createState() => _MessageScreenState();
}

class _MessageScreenState extends State<MessageScreen> {
  var fanMessage = '';
  var userDocument;
  var userId;

  @override
  void initState() {
    super.initState();
    _getId();
  }

  TextEditingController messageController = TextEditingController();
  void _messageSubmit() {
    Firestore.instance
        .collection('messages/ne6MUaXi2wup9WOcZq85/alerts')
        .add({'text': messageController.text});
  }

  Future _getId() async {
    var test = await FirebaseAuth.instance.currentUser();
    setState(() {
      userId = test.uid;
      print(userId);
      Firestore.instance
          .collection('users')
          .document(userId)
          .get()
          .then((DocumentSnapshot documentSnapshot) {
        userDocument = documentSnapshot.data['role'];
      });
    });
  }

  // Widget _getId() {
  //   return FutureBuilder(future: Firestore.instance.collection('users'),child: Text());
  // }

  @override
  Widget build(BuildContext context) {
    print('User ID: ${userId}');

    print('User Role: ${userDocument}');
    return Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(60.0),
          child: AppBar(
            title: Text('Fan Page'),
            actions: [
              DropdownButton(
                icon: Icon(
                  Icons.more_vert,
                  color: Theme.of(context).primaryIconTheme.color,
                ),
                items: [
                  DropdownMenuItem(
                      child: Container(
                        child: Row(
                          children: <Widget>[
                            Icon(Icons.exit_to_app),
                            SizedBox(
                              width: 8,
                            ),
                            Text('Logout')
                          ],
                        ),
                      ),
                      value: 'logout')
                ],
                onChanged: (itemIdentifier) {
                  if (itemIdentifier == 'logout') {
                    FirebaseAuth.instance.signOut();
                  }
                },
              )
            ],
          ),
        ),
        body: StreamBuilder(
          stream: Firestore.instance
              .collection('messages/ne6MUaXi2wup9WOcZq85/alerts')
              .snapshots(),
          builder: (ctx, streamSnapshot) {
            if (streamSnapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            final documents = streamSnapshot.data.documents;
            return ListView.builder(
              itemCount: documents.length,
              itemBuilder: (ctx, index) => Container(
                padding: EdgeInsets.all(10),
                child: Card(
                  elevation: 10,

                  // decoration:
                  // BoxDecoration(border: Border.all(color: Colors.black)),
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(5.0, 20.0, 5.0, 20.0),
                    child: Container(
                      child: Text(
                        documents[index]['text'],
                      ),
                    ),
                  ),
                ),
              ),
            );
          },
        ),
        floatingActionButton: Visibility(
          visible: checkIfAdmin(),
          child: Center(
            child: Container(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.fromLTRB(20, 0, 0, 70),
                child: FloatingActionButton(
                  child: Icon(Icons.add),
                  onPressed: () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) =>
                          _buildPopupDialog(context),
                    );
                  },
                ),
              ),
            ),
          ),
        ));
  }

  bool checkIfAdmin() {
    // getData();
    // print(userDocument['role']);
    if (userDocument == 'admin') {
      return true;
    } else {
      return false;
    }
  }

Okay so what I want to do is, show that floatingActionButton for 'admin' user role only. The logic seems to be working as this happens when I hot reload once after launching th app. When I launch the app and login then I get a red window with an error saying "Invalid argument(s)" and when I hot reload without changing anything, I get my screen and then it works fine. Why is this happening? I have not totally understood state concept yet. So please help!

EDIT: I have stopped getting red screen error messages. Instead the app starts. But from what I have checked.

My problem is that my app works fine only after hot reload. Only after hot reload admin sees the floatingActionButton.

In debug console before hot reload, I get this error:

Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.

CodePudding user response:

in your case ,just wrap the fab with a visibility widget and set its visible property to true/false. so u got:

floatingActionButton: Visibility(
 visible: checkIfAdmin(),
 child: FloatingActionButton(
 child: Icon(Icons.add),
 onPressed: () {},
 ),
 ),

and a method:

bool checkIfAdmin(){
if(admin){
return true;}
else{
return false;
}   
}

CodePudding user response:

reviewed ure code a bit ,it seems ure setState method is not causing a rebuild , caz u call setState for userid which has no role in the state of ure application. also consider moving

Firestore.instance
.collection('users')
.document(userId)
.get()
.then((DocumentSnapshot documentSnapshot) {
userDocument = documentSnapshot.data['role'];
// print(userDocument);
});

out of build method.

  • Related