I am getting these two errors when building a listview.
The getter 'length' isn't defined for the type 'Future'. The operator '[]' isn't defined for the type 'Future'.
whats going wrong here and is there any fix to my code.
Thanks Alot!
This is my code :
import 'package:cache_manager/cache_manager.dart';
import 'package:flutter/material.dart';
class messageBoard extends StatefulWidget {
messageBoard({Key key}) : super(key: key);
@override
State<messageBoard> createState() => _messageBoardState();
}
class _messageBoardState extends State<messageBoard> {
@override
Widget build(BuildContext context) {
var message = ReadCache.getStringList(key: "cahce3");
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
Expanded(
child: FutureBuilder(
builder: (context , snapshot) {
return ListView.builder(
itemCount: message.length,
itemBuilder:(context,index){
return Text(message[index]);
}
);
},
),
)],
),
);
}
}
CodePudding user response:
Future builder takes a future. You can assign the future to Futurebuilder and check its data. Assuming ReadCache.getStringList is a future you can write it like this.
FutureBuilder(
future: ReadCache.getStringList(key: "cahce3"),
builder: (context , snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder:(context,index){
return Text(snapshot.data[index]);
}
);
}
else{
return Text("No Data");
}
},
),
CodePudding user response:
The ListView.builder still doesn't take a future. In your case it's probably built before the variable gets the values it's supposed to have.
Try putting var message = ReadCache.getStringList(key: "cahce3");
inside an initState()
method.
Also you don't write logic inside the build()
method. In a stateful widget build()
gets called whenever something changes in the UI, basically all the time.