Search code examples
flutterdartdart-null-safety

How to set null safety to parent variable so we do not need to loop for the children vars


I have problem with putting null safety into child vars since there are many. I just want to set it to the parent. I already did it but is there any shortcut where we can just put into parent variable then we do not need to loop for the children vars

return ListView.separated(
                itemBuilder: (context, index){
                  final DataAd object = snapshot.data![index]; => Here is the parent
                  final images = object.images!['images']; => I dont want to repeat here
                  if(object!=null) {
                    return Card(
                      child: Column(
                        children: [
                          Text(object.title!), => this one
                          Image(image: NetworkImage('${globals.domain}${object.dir}/${images![0]}')), => and this one for example
                        ],
                      ),
                    );
                  }
                  else{
                    return CallLoading();
                  }
                },
                separatorBuilder: (context,index) => Divider(),
                itemCount: snapshot.data!.length,
            );

I am new into flutter, I really appreciate any given answer. Thank you.


Solution

  • Just add a guard to your function and Dart compiler will see that value can't be null.

    Example:

    void foo(String? data) {
      String _data; 
      if (data == null) return; // The guard.
      _data = data; // Will not ask for null check because it cannot be null.
      print(_data);
    }
    
    // Without guard:
    void foo(String? data) {
      String _data; 
      //if (data == null) return; 
      _data = data; // Error: A value of type ‘String?’ can’t be assigned to a variable of type ‘String’.
      print(_data);
    }
    
    // With default value.
    void foo(String? data) {
      String _data = data ?? 'Empty'; // <- Convert to non nullable.
      // Do what you want with _data
      print(_data);
    }