2021年5月2日星期日

Trouble accessing FutureProvider in another screen

I'm following a basic FutureProvider example that as of March 2020 was working. I'm wondering if something changed with the Provider package as I can't get my Home screen to access the Provider object despite the Provider appearing to be in the same route.

My main.dart:

void main() => runApp(MyApp());    class MyApp extends StatelessWidget {  final EmployeeService employeeService = EmployeeService();  @override  Widget build(BuildContext context) {  return FutureProvider(    initialData: null,    create: (context) => employeeService.fetchEmployees(),    catchError: (context, error) {      print(error.toString());    },    child: MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(        primarySwatch: Colors.blue,      ),      home: Home(),    ),  );  

My home.dart:

class Home extends StatelessWidget{    @override     Widget build(BuildContext context) {      List<Employee> employees = Provider.of<List<Employee>>(context);      return Scaffold(    appBar: AppBar(title: Text('Employees')),    body: (employees == null)? Center(child: CircularProgressIndicator(),) :        ListView.builder(itemCount: employees.length,        itemBuilder: (context, index){          return ListTile(            subtitle: Text(employees[index].email),            title: Text(employees[index].name),          );        },)  );  

}

My super basic EmployeeService class...

 class EmployeeService {     Future<List<Employee>> fetchEmployees() async{   var uri = Uri.parse('https://jsonplaceholder.typicode.com/users');   var response = await http.get(uri);   var jsonResponse = convert.jsonDecode(response.body) as List;    return jsonResponse.map((e) => Employee.fromJson(e)).toList();  

I've checked the Flutter Inspector and the widgets seem to line up correctly. Yet, I continue to get the error:

The following ProviderNotFoundException was thrown building Home(dirty): Error: Could not find the correct Provider<List> above this Home Widget

This happens because you used a BuildContext that does not include the provider of your choice.

This would be a convenient method for the model I am envisioning with the API I am calling so I was just wondering if something might have changed with FutureProvider.

https://stackoverflow.com/questions/67363070/trouble-accessing-futureprovider-in-another-screen May 03, 2021 at 11:07AM

没有评论:

发表评论