I’m currently writting a code to fetch a firebase data in initState.
But no matter what I do it does’t return or does’t store data so I get following error.
I’m getting error at code Text(userName["username"].toString())
Exception has occurred. NoSuchMethodError (NoSuchMethodError: The
method ‘[]’ was called on null. Receiver: null Tried calling:
)
Please teach me how to make it work.
Since I’m using setState inside of by code I would not like to use futurebuilder nor streambuilder to perform it.
class _reviewWriteHomeState extends State<reviewWriteHome> {
var user = FirebaseAuth.instance.currentUser;
var userName;
String? userIcon;
@override
void initState() {
// TODO: implement initState
super.initState();
Future(() async {
fetchData();
await Future.delayed(Duration(seconds: 5));
});
}
Future fetchData() async {
final userSnap = await FirebaseFirestore.instance.collection("user").doc("user").get();
final pos = (userSnap.data() as Map<String, dynamic>);
setState(() {
userName = pos;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
const SizedBox(height: 30),
Text(userName["username"].toString()),
const SizedBox(height: 10),
GestureDetector(
child: Image.asset('assets/image.png'),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => const newPage()));
},
)
],
),
)),
);
}
}
3
Answers
It is not advised to use
future
ininitState
instead use theFutureBuilder
Update:
using
future
ininitState()
is not a best idea, you can useaddPostFrameCallback
insideinitState
, or use it before returning widget tree to thebuild
methodand you don’t really have to use the future builder.
here is an example
or You can use
FutureBuilder
. refer BouncyBits answer for that.You declared
userName
as:Since you don’t specify a default value, that means that its initial value is
null
. Since you only set the vale ofuserName
when you get data from Firestore (many seconds later), the UI will be rendered whileuserName
is stillnull
. And in thebuild
method you then do:Since
username
isnull
initially, you’re trying to call["username"]
on it, which isn’t valid. And that’s exactly what the error message tells you.A simple way to solve this is to show a loading indicator while the user name is being loaded: