Error could not find the correct provider above this widget

Issue

OK, I’m stuck on this problem using FutureProvider.

I already create a FutureProvider above my MaterialApp, so it should be recognized right?

My widget tree is somewhat like this:

MyApp >> Home >> CardVehicle

Here’s my main.dart code where I create object Provider:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final Service service = Service();

  @override
  Widget build(BuildContext context) {
    return FutureProvider(
      create: (_) => service.fetchCarYear(),
      catchError: (_, error) => print(error),
      child: MaterialApp(
        title: 'KPM Demo',
        theme: ThemeData(
          primarySwatch: Colors.amber,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home(),
      ),
    );
  }
}

my dummy Service class:

class Service {
  Future<CarYear> fetchCarYear() async {
    CarYear carYear = CarYear();

    final response = await Future.delayed(
      Duration(milliseconds: 500),
      () => jsonEncode({
        "data": [
          {"year": "2020"},
          {"year": "2019"},
          {"year": "2018"}
        ]
      }),
    );

    carYear = CarYear.fromJson(jsonDecode(response));

    return carYear;
  }
}

Here’s where I put my Provider:

class CardVehicle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    CarYear carYear = Provider.of<CarYear>(context);

    return Container(
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Column(
        children: <Widget>[
          DropdownButton(
            isExpanded: true,
            icon: Icon(Icons.keyboard_arrow_down),
            items: carYear.data
                .map((item) => DropdownMenuItem(child: Text(item.year)))
                .toList() ?? null,
            onChanged: null,
          ),
        ],
      ),
    );
  }
}

Did I make a mistake somewhere? Please help!

Edit: here’s my CarYear class:

class CarYear {
  List<Data> data;

  CarYear({this.data});

  CarYear.fromJson(Map<String, dynamic> json) {
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Data {
  String year;

  Data({this.year});

  Data.fromJson(Map<String, dynamic> json) {
    year = json['year'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['year'] = this.year;
    return data;
  }
}

Solution

Comming from the other question you posted.

You need to change the catchError of your futureProvider to return a CarYear instead of void. Now the futureProvider is of type Dynamic and provider.of is searching not for a provider of dynamic, but a provider of CarYear.

To avoid this, make catchError return an empty CarYear or make it throw an exception.

I hope this helps!

Answered By – Francisco Javier Snchez

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.