2

I wish to seek your help in solving a synatx error. An error is shown on the "context" as shown below.

However, exacly the same code has no error when it is embedded in a class within another file.

Thank you in advance for your help.

Error in "context"

readfromFirebase.dart

Future readFromFirebase() async { Carpark thisCarpark; // await FirebaseFirestore.instance await FirebaseFirestore.instance .collection('carpark') .get() .then((QuerySnapshot snapshot) { snapshot.docs.forEach( (DocumentSnapshot cp) { thisCarpark = Carpark( cp.get('name'), cp.get('district'), ); Provider.of<CarparksProvider>(context, listen: false) .addCarpark(thisCarpark); }, ); }); var carparkList = Provider.of<CarparksProvider>(context, listen: false).carparks; return carparkList; } 

carparks_provider.dart

import 'package:flutter/material.dart'; import 'carpark.dart'; class CarparksProvider extends ChangeNotifier { List<Carpark> _carparks = []; List<Carpark> get carparks => _carparks; void addCarpark(Carpark carpark) { _carparks.add(carpark); notifyListeners(); } } 

parkingFee_screen.dart

import 'package:carpark_v012/services/carpark.dart'; .... class ParkingFeeScreen extends StatefulWidget { @override _ParkingFeeScreen createState() => _ParkingFeeScreen(); } class _ParkingFeeScreen extends State<ParkingFeeScreen> { List<Carpark> carparkList = []; //List for storing carparks void initState() { super.initState(); } Future readFromFirebase() async { Carpark thisCarpark; ...... } @override Widget build(BuildContext context) { return Scaffold( appBar: ......... body: FutureBuilder( future: readFromFirebase(context), builder: (BuildContext context, AsyncSnapshot snapshot) { print(snapshot.data); ......... 
2
  • where are you using it in widget. can you add that. Commented Aug 28, 2021 at 2:09
  • the parkingFee_screen.dart in which the readFromFirebase is called is added. Thanks. Commented Aug 28, 2021 at 16:18

1 Answer 1

4

Pass BuildContext to this method like

Future readFromFirebase(BuildContext context) async { 

And while calling this function, pass context there.

Does it solve in your case?

Sign up to request clarification or add additional context in comments.

2 Comments

Your suggestion works partially and the error goes away. The readfromFirebase is originally put inside the parkingFee_screen.dart as shown below. I want to put the readfromFirebase into a indepedent file so that it can be called by other module.
the parkingFee_screen.dart is just added above to show how the readfromFirebase is called. However, nothing is shown on the screen even though there is no error. It appears that there is some problem with the "context". Too many "context" in the code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.