うまく動作しなかったコード
Provider.ofでの取得がうまく動作しませんでした。
main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ChangeNotifierProvider(
create: (context) => TaskStore(),
child: TasksScreen(),
),
);
}
}
task_screen.dart
class TasksScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal,
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
context: context, builder: (context) => AddTaskScreen());
},
),
);
}
}
task_store
class TaskStore extends ChangeNotifier {
List<Task> tasks = [
Task(name: "buy milk."),
];
void addTask(String taskTitle) {
Task task = Task(name: taskTitle);
tasks.add(task);
notifyListeners();
}
}
add_task_screen.dart
class AddTaskScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
String textValue;
return Container(
child: Container(
child: RaisedButton(
child: Text("Add"),
onPressed: () {
Provider.of<TaskStore>(context, listen: false).addTask("test task");
Navigator.pop(context);
},
),
),
);
}
}
実行時のエラー
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown while handling a gesture:
Error: Could not find the correct Provider<TaskStore> above this AddTaskScreen Widget
To fix, please:
* Ensure the Provider<TaskStore> is an ancestor to this AddTaskScreen Widget
* Provide types to Provider<TaskStore>
* Provide types to Consumer<TaskStore>
* Provide types to Provider.of<TaskStore>()
* Ensure the correct `context` is being used.
Providerがみつからないと。
解決策
ChangeNotifierProvider のchild に MaterialApp を設定します。
main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => TaskStore(),
child: MaterialApp(
home: TasksScreen(),
),
);
}
}
ModalBottomSheet の階層的に、MaterialAppの下層という位置づけなのでしょうか。
何か間違ってたらご指摘いただけると助かります。