How to pass a list from one class to another in Flutter?

Viewed 3375

So i have a list which i add data to on one screen (every time a certain button is clicked). I then have a bottom naivgation bar which allows me to switch between the screens (there is no pop or push route due to this as well).

My issue is I have two screens. I want to access the list from the first state class inside the second state class.

Class with the list:

class Security extends StatefulWidget {
  @override
  _SecurityState createState() => _SecurityState();
}

class _SecurityState extends State<Security> {

  List<Log> my_logs = []; // i want data stored inside here

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

Class where i want to access the list from the previous class:

class History extends StatefulWidget {
  @override
  _HistoryState createState() => _HistoryState();
}

class _HistoryState extends State<History> {

  List<Log> items = [] // i want it here
  
  @override
  Widget build(BuildContext context) {
    return Scaffold();

  }
}

Is that possible?

Also atm, if i was to switch between the bottom navigatio buttons the list would lose the items that were in it. How would i avoid this also? Could i make a global list inside the main class or something?

Thanks.

1 Answers

Of course, that is possible. You can use app state provider to use a global list, and you can set and get the list from that provider. There is a very helpful blog here.

Your provider will look like this:


import 'package:flutter/material.dart';

class LogProvider extends ChangeNotifier{
  List<Log> _logList =
      List<Log>();

  List<Log> get logList =>
      this._logList;

  set logList(List<Log> value) {
    _logList = value;
    notifyListeners();
  }


}

Related