Home > Net >  Flutter: Why is this variable momentarily showing as null and causing an error?
Flutter: Why is this variable momentarily showing as null and causing an error?

Time:09-26

When my app reaches this screen, there is a moment where an error flashes on the screen and then disappears to show the screen like normal. Android Studio is pointing to the groupName variable. The goal here is to display the group name at the top of the screen when the user lands on this page. The group name is queried from Firestore by filtering on the groupID. Why might the app be initially showing an error that groupName is Null and then it disappears?

class _ChatScreenState extends State<ChatScreen> {
  final database = Database();
  var groupMembersList = [];
  var groupName;
  FirebaseFirestore firestore = FirebaseFirestore.instance;
  late final Stream<QuerySnapshot> groupMembersStream = firestore.collection('groups').doc(widget.groupID).collection('GroupMembers').snapshots();

  @override
  void initState() {
    super.initState();
    initialize();
    activateGroupMembersListener();
  }

  void initialize() async {
    var tempGroupName = await database.getGroupName(widget.groupID);

    setState(() {
      groupName = tempGroupName;
    });
  }
  
  
  @override
  Widget build(BuildContext context) {
    final container = StateContainer.of(context);

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          color: Colors.white,
          onPressed: () {
            container.stopMyApp();
            Navigator.pop(context);
          },
        ),
        title: Text(
          groupName, //ERROR IS HERE, THIS VARIABLE IS NULL
        ),
        
        //...rest of code//
        
        )
    )
    }
    
}

The error:

type 'Null' is not a subtype of type 'String'

CodePudding user response:

It happens because when the widget is built the groupName is null (it didn't receive the data yet) and after it receives the data you use setState so the widget is rebuilding and it already has the data.
If groupName is a String you can init groupName with an empty String: String groupName = '';
or check if groupName is null (title: Text(groupName == null ? '' : groupName),

Or you can use a FutureBuilder for your futures and when you are waiting for data just show loader (for ex. CircularProgressIndicator), since you can't display your finished page before receiving the data

CodePudding user response:

It happens because you don't have yet the value of the variable tempGroupName, but you are already trying to build the screen with it value. You can use a FutureBuider to note the screen to wait until receive the value. You can use the states pattern too, like Bloc Pattern or cubit, and show a CircularProgressIndicator when the state is Loading.

  • Related