0

I retrieve data from sharedpreference using _animal = (prefs.getString('animals') ?? ''); to get a result like "Dog", "Cat", "Rabbit".

When I tried assigning it to a list, I get the error message "The instance member '_animal' can't be accessed In an initializer....

Thank you jamesdlin and Julian for your suggestions. I am new to flutter and this is tripping me up. Here's what I am trying to achieve.

I used the code below to retrieve saved data which returns "Dog", "Cat", "Rabbit" as results.

//Loading animals list 
   void _loadanimals() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
     _animal = (prefs.getString('animals') ?? '');
   });
  }

I want to use the results to populate the list "nList" in the code below to display buttons of the animals

Column(
              children: nList
                  .map((data) => RadioListTile(
                        title: Text("${data.number}"),
                        groupValue: id,
                        value: data.number,
                        onChanged: (val) {
                          setState(() {
                            radioItemHolder = data.number;
                            services = data.number;
                            id = data.number;
                          });
                        },
                      ))
                  .toList(),
            ),
  • https://stackoverflow.com/a/64548861/ might clarify things for you. If you're trying to use a member variable a constructor's initializer list, you will need to move that initialization to the constructor body instead. – jamesdlin Feb 21 '22 at 16:30

1 Answers1

0

You can try using a getter if possible:

get _animal{
  return prefs.getString('animals') ?? '';
}