Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This problem is driving me crazy and I don't know what to do anymore I'm completely lost and it's ruining my life.
I'm trying to insert a list values which I retrieved from MySQL database into listView when the user pressed a button but the screen throws
type 'Null' is not a subtype of type 'String' 
instead

This is how the values list was added

bool _isFromLogin = false;
List<Uint8List?> _imageByteValues = <Uint8List>[];
List<String?> _fileValues = <String>[];
List<File?> _imageValues = <File>[];
List<Icon?> _nonImgValues = <Icon>[];
String _FileType = "";
String _getTable = "";

class cakeLogin extends StatefulWidget {
  @override
  cakeLoginPageMain createState() => cakeLoginPageMain(); 
}

class cakeLoginPageMain extends State<cakeLogin> {

  String? _CustEmailInit; 
  BuildContext? loginContext;

  List<String?> _fileNameStores = <String>[];
  List<Uint8List?> _imgByteStores = <Uint8List>[];
  List<String?> _dateRetrieveStores = <String>[];

  Future<void> removeOldData() async {
    setState(() {
      _fileNameStores.clear();
    });

    setState(() {
      _imgByteStores.clear();
    });

    setState(() {
      _fileValues.clear();
    });

    setState(() {
      _imageValues.clear();
    });

    setState(() {
      _nonImgValues.clear();    
    });

    setState(() {
      _imageByteValues.clear();
    });
  }

  Future<void> callData() async {

    await removeOldData();

    var custUsernameGet = await UsernameGetter().Connection(_CustEmailInit!);
    var nameValuesGet = await NameGetter().Connection(custUsernameGet);

    setState(() {
      _custUsername = custUsernameGet;
    });

    // ----- File name retrieval starts -----

    setState(() {
      _fileNameStores.addAll(nameValuesGet);
    });
    setState(() {
      _fileValues.addAll(_fileNameStores.toSet().toList());
    });

    // ----- File name retrieval end -----

    // Start retrieving leading image

    var retrieveCustFile = await LoginGetter().connectionFunc(custUsernameGet, "image_info");
    setState(() {
      _imgByteStores.addAll(retrieveCustFile);
    });

    setState(() {
      _imageByteValues.addAll(_imgByteStores.toSet());
    });

    // Retrieving leading image end
    
    var retrieveUploadDate = await DateGetter().connectionFunc(custUsernameGet,"image_info");
    setState(() {
      _dateStoresValues.addAll(retrieveUploadDate);
    });
}
}


NameGetter class (retrieve file names from database)

class NameGetter {

  Future<List<String>> Connection(String _custUsername) async {
    final conn = await MySQLConnection.createConnection(
      
    );
    await conn.connect();

    var _getFileNamesQue = await conn.execute("SELECT FILE_NAME FROM " + "image_info" + " WHERE CUST_USERNAME = :username",
      {
        "username": _custUsername
      });

    List<String>? _FileNameValues = <String>[]; 
    for(var _rowsOfFileNames in _getFileNamesQue.rows) {
      var _retrieveNames = await _rowsOfFileNames.assoc()['FILE_ANME']!;
      _FileNameValues.add(_retrieveNames);
    }

    return await _FileNameValues;
  }
}



UsernameGetter class (Retrieve user username from their entered email)

class UsernameGetter {
  Future<String> Connection(String _custEmail) async {
    final conn = await MySQLConnection.createConnection(

    );

    await conn.connect();

    var _getUsernameQue = await conn.execute("SELECT CUST_USERNAME, CUST_EMAIL FROM information WHERE CUST_EMAIL = :email", 
    {
      "email": _custEmail
    });

    String? _usernameDetected;
    for(final _rowsOfEmail in _getUsernameQue.rows) {
      _usernameDetected = _rowsOfEmail.assoc()['CUST_USERNAME']!;
    }
    return await _usernameDetected!;
  }
}


Initialize widget function for listView. And this is where the problem start, the list _fileValues supposed to have length of 2 but when I print the length from this Widget function the value returns 0 instead of 2.

Widget setupFileList(BuildContext context) {
  var  mainReturn;
  var _showList = SingleChildScrollView(
        child: Column(
          children: [
            ListView.separated(
              shrinkWrap: true,
              separatorBuilder: (BuildContext context, int index) => Divider(height: 1,color: Color.fromARGB(255,48, 48, 48)),
              itemBuilder: (BuildContext _context, int _index) {
              return GestureDetector(
                child: Container(              
                  color: setupMainTheme,
                  child: ListTile(
                    onTap: () {

                      FilePositon = _index;
                      var setTitle = _fileValues[FilePositon];
                      SelectedFileName = setTitle;
                      var setFileType = setTitle!.substring(setTitle.length-3);
                      _FileType = setFileType;

                    },

                    leading: SizedBox(
                      child: _isFromLogin == false ? Image.file(_imageValues[_index]!) : Image.memory(_imageByteValues[_index]!),scale: .8),
                      height: 48,
                      width: 48
                    ), 
                    trailing: Icon(Icons.arrow_right,color: Colors.grey),
                    title: Text(Text(_fileValues[_index]!.toString(),
                      style: TextStyle(
                        color: Color.fromARGB(213, 255, 255, 255),
                      )),
                    subtitle: Text(Text(_isFromLogin == false ? _dateToStr : _dateStoresValues[_index]!.toString(), 
                      style: TextStyle(
                        color: Color.fromARGB(197, 255, 255, 255),
                        fontSize: 12.8)),
                  )
                )
              );
              },

            itemCount: _fileValues.length,
            
            ),
          ],
        ),
    ); 

  print(_fileValues.length);
  if(_fileValues.length > 0) {
    mainReturn = _showList;
  } else {
    mainReturn = redundaneShow();
  }
  return mainReturn; // type null is not a subtype of string
}


Call and display the listView widget function (setupFileList) into the screen

class _cakeHomeWidgetState extends State<cakeWidget> { //State<cakeWidget>

  BuildContext? dialogContext;
      
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: setupMainTheme,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(58),
        child: AppBar(
          centerTitle: false,
          title: Column(
            children: <Widget>[
             Text("Welcome",
                style: 
                  TextStyle(
                    color: Color.fromARGB(255, 190, 190, 190),
                    fontWeight: FontWeight.w700,
                    fontSize: 20
                    )
                ),
            ], 
          ),
          automaticallyImplyLeading: false,
          backgroundColor: setupMainTheme,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(12)),
            ),
        ),
      ),

    body: setupFileList(context),


What I have tried:

I'm a bad programmer, I made a lot of mistakes and I don't know how to fix them. Reading documentations does not helps, google does not help, I just want to fix this bug and quit.
Posted
Comments
Richard MacCutchan 5-Mar-23 7:23am    
The message is telling you that you are trying to add a null value to the list. So use your debugger to find out why the request for an item is returning a null, rather than the requested data.
Dan Sep2022 5-Mar-23 7:43am    
@RichardMacCutchan The debugger isn't helping either, it does not show what data is being thrown it only tells in what class the problem occurs and that is cakeWidget. However when I printed the lists values from cakeLogin class (the class where I retrieved and added the values into list) it does returns the values I was expecting however when I printed it from the setupFileList function it does not return any value at all. So it looks like the list value is not updating from different function, how to fix this?
Richard MacCutchan 5-Mar-23 8:39am    
Null reference errors are quite common and tell you that some variable has not been initialise. This may be a simple program bug, or caused by some information not being found in the data you are processing. But the problem is that the only way to find where and why it happens is by using the debugger. So you need to catch the line where the error occurs and look at the variable that is causing it. What should it point to, and where should it have been set? Your understanding of the flow of the code should help you narrow it down.
Dan Sep2022 6-Mar-23 3:45am    
I just executed the program using a debugger and apparently a variable with null value was returned. I'm really really sorry for wasting your time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900