How should I add an item to a chest?

My plugin creates and places a chest, but I don’t seem to be able to get the chest’s inventory. I’m hoping to be able to put something in the chest as I leave it.

I’m using the setBlock method in Level, but I seem to need a BlockEntity rather than a Block, but if I do a getBlockEntity(position), on the position of the chest, it comes back null.

Any help much appreciated.
P

Hello!

To the Level.setBlock method does not create BlockEntity, you could call BlockChest.getOrCreateBlockEntity if you want it to have a single chest with contents in it but I recommend calling the BlockChest.place to let it place as if a placed it and connect to form double chests if necessary:

For example (note: I could not test in game)

@EventHandler
public void onInteract(PlayerInteractEvent event) {
    final Block target = event.getBlock();
    if (event.getAction() != PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK || !(target instanceof BlockStone)) {
        return;
    }
    
    Block chestPos = target.getSide(event.getFace());
    BlockChest chest = (BlockChest) BlockState.of(BlockID.CHEST).getBlock(chestPos);
    final Player player = event.getPlayer();
    if (!chest.place(chest.toItem(), chestPos, target, event.getFace(), 8, 8, 8, player)) {
        player.sendMessage(TextFormat.RED + "Oh no! The chest don't fit there!");
        return;
    }

    
    final ChestInventory inventory = chest.getOrCreateBlockEntity().getRealInventory();
    for (int i = 0; i < inventory.getSize(); i++) {
        inventory.setItem(i, Item.get(ItemID.ARROW));
    }
}

Thanks Jose I sort of see how that should work. I tried first to just do as you suggested and use BlockChest.getOrCreateBlockEntity but could not see how to do it.
Defining onInteract as you do made more sense, but changing it from using a mouse with a rhs button to a command was too complex because a command does not have an event from which to getFace etc.
And then I realised that I probably don’t want to place a filled chest, but rather place a chest and then fill it from my own inventory. Working on that now.
If anyone else is looking for a solution, the starting point is as jose says, but there is a prior example that might be of help over at GitHub - Tee7even/Presents: A Nukkit plugin to place chests, that players can open and get random items