I am retrieving a document from Firebase and try to display this data in my application. The user clicked on an item and is forwarded to this page here. At the same time the information about the selected item is forwarded with the following code:
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SearchResult(item.abc)));
The result of the following code is OK and the correct name is displayed. But while loading this error appears briefly:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building SearchResult(dirty, state:
_SearchResultState#9a2f6):
The method '[]' was called on null.
Receiver: null
Tried calling: []("Name")
A short moment later the name is displayed in my application. I think this is a problem with loading the data from Firebase. How can I solve this? This is my code:
class SearchResult extends StatefulWidget {
final String data;
SearchResult(this.data);
@override
_SearchResultState createState() => _SearchResultState();
}
class _SearchResultState extends State<SearchResult> {
dynamic data_snap;
Future<dynamic> getData() async{
print(widget.data);
final DocumentReference document = Firestore.instance.collection("Players").document(widget.data);
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
setState(() {
data_snap =snapshot.data;
});
});
}
@override
void initState() {
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Player'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.black)
),
child: ListTile(
title: Text(data_snap['Name']),
),
)
]
)
),
);
}
}
This might be happening because when the build method runs the application might still be fetching the data you should control this and add a progress indicator in that case
Try something like this:
class _SearchResultState extends State<SearchResult> {
dynamic data_snap;
bool _loading = false;
Future<dynamic> getData() async{
print(widget.data);
final DocumentReference document =
Firestore.instance.collection("Players").document(widget.data);
_loading = true;
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
setState(() {
data_snap =snapshot.data;
_loading = false;
});
});
}
And then in your build method do the following:
child: _loading ? CircularProgressIndicator() :
ListTile(
title: Text(data_snap['Name']),
),