I am new to flutter and I am trying to build up a list from what I have saved in shared preferences. I was able to build the list with the future builder by calling async function getTitles() in the future builder widget directly, but because of the rebuilding issues of the future builder, I have changed my code as below.
But now my List is not getting populated can someone guide me where I am doing wrong.
import 'package:flutter/material.dart';
import 'my_shared_preferences.dart';
import 'editable_list_tile.dart';
class ModesScreen extends StatefulWidget {
ModesScreen({Key? key, required this.title}) : super(key: key);
@override
_ModesScreenState createState() => _ModesScreenState();
String title;
}
class _ModesScreenState extends State<ModesScreen> {
late Future<dynamic> _future;
List<ListModel> list = [];
List<String> _modetitlelist = [];
List<String> _modesubtitlelist = [];
_ModesScreenState() {
_modetitlelist.clear();
_modesubtitlelist.clear();
int ind = 0;
for (int i = 0; i < 6; i++) {
MySharedPreferences.instance
.getStringValue('modelname$i')
.then((value) => setState(() {
if (value.isNotEmpty) {
_modetitlelist.add(value);
} else {
ind = i + 1;
_modetitlelist.add('Mode $ind');
}
}));
MySharedPreferences.instance
.getStringValue("preset$i")
.then((value) => setState(() {
if (value.isNotEmpty) {
_modesubtitlelist.add(value);
} else {
_modesubtitlelist.add('0');
}
}));
}
}
@override
initState() {
super.initState();
_future = _getTitles();
}
Future<dynamic> _getTitles() async {
for (int i = 0; i < 6; i++) {
list.add(ListModel(title: _modetitlelist[i], subTitle: _modesubtitlelist[i]));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//title: Text(widget.title),
title: const Text('Modes & Preset'),
),
body: FutureBuilder(
future: _future,
builder: (context, snapshot) {
return ListView.separated(
separatorBuilder: (context, index) => const Divider(
color: Colors.black,
),
itemCount: list.length,
itemBuilder: (context, index) => EditableListTile(
model: list[index],
onChanged: (ListModel updatedModel) {
/// Gets called when the save Icon is tapped on the List Tile.
list[index] = updatedModel;
MySharedPreferences.instance
.setStringValue("modelname$index", list[index].title);
MySharedPreferences.instance
.setStringValue("preset$index", list[index].subTitle);
},
),
);
},
),
);
}
}