I'm new at Flutter and still struggling with overall concept of widgets structure especially stateful ones. As far as I understand I should create all widgets stateless unless they can be changed. Then they should be stateful and hold their state. So I have a simple screen with a list of items that is dynamic and action button:
class WalletWidget extends StatelessWidget {
final GlobalKey<_WalletItemsState> _key = GlobalKey();
void _addWalletItem(BuildContext context) async {
var asset = await Navigator.pushNamed(context, '/add_wallet_item');
if (asset == null) {
return;
}
_key.currentState!._refresh();
}
@override
Widget build(BuildContext context) => Scaffold(
body: _WalletItems(),
floatingActionButton: FloatingActionButton(
onPressed: () => _addWalletItem(context),
child: const Icon(Icons.add)),
);
}
class _WalletItems extends StatefulWidget {
const _WalletItems();
@override
State<StatefulWidget> createState() => _WalletItemsState();
}
class _WalletItemsState extends State<_WalletItems> {
List<Asset> _walletAssets = [];
void _refresh() {
setState(() {});
}
@override
Widget build(BuildContext context) => ListView.builder(
itemCount: _walletAssets.length,
itemBuilder: (context, index) =>
Text(Asset.persistenceMgr.getAll().toList()[index].title),
);
}
in my understanding whole screen should be a stateless as it merely builds a UI structure. Hence class WalletWidget extends StatelessWidget. The list widget is stateful. Adding of new elements is done at separate screen when the action button is pressed. So when I'm back from adding screen the list is updated and I need to refresh the state of the list.
Only way I've found is using a GlobalKey, which points to the _WalletItemsState. But when it comes to line _key.currentState!._refresh(); the currentState is always null. So I assume the _key isn't properly associated with list's state. How do I do that?