I'm trying to use provider with template, but Provider.of seems not working like that.
Logs:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following ProviderNotFoundError was thrown building MyChildWidget(dirty): Error: Could not find the correct Provider above this MyChildWidget Widget
To fix, please:
- Ensure the Provider is an ancestor to this MyChildWidget Widget
- Provide types to Provider
- Provide types to Consumer
- Provide types to Provider.of()
- Always use package imports. Ex: `import 'package:my_app/my_code.dart';
- Ensure the correct
context
is being used.
Do you know any solution ?
Sample to show the problem:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Provider<MyChildState>.value(
value: MyChildState("Hello world !"),
child: MaterialApp(
home: MyChildWidget(),
)),
);
}
}
abstract class MyParentWidget<State extends MyParentState> extends StatelessWidget {
@override
Widget build(BuildContext context) {
final State state = Provider.of(context);
return Text(state.text);
}
}
abstract class MyParentState {
final String text;
MyParentState(this.text);
}
class MyChildWidget<MyChildState> extends MyParentWidget{
}
class MyChildState extends MyParentState {
MyChildState(String text) : super(text);
}