[英]Flutter package provider with templates
I'm trying to use provider with template, but Provider.of seems not working like that.我正在尝试将 provider 与模板一起使用,但 Provider.of 似乎无法那样工作。
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
==╡ 例外情况被小部件库捕获 ╞==================================== =================== 构建MyChildWidget(dirty)时抛出以下ProviderNotFoundError:错误:在此MyChildWidget Widget上方找不到正确的提供者
To fix, please:
要修复,请:
- Ensure the Provider is an ancestor to this MyChildWidget Widget
确保 Provider 是这个 MyChildWidget Widget 的祖先
- Provide types to Provider
向 Provider 提供类型
- Provide types to Consumer
为消费者提供类型
- Provide types to Provider.of()
向 Provider.of() 提供类型
- Always use package imports.
始终使用包导入。 Ex: `import 'package:my_app/my_code.dart';
例如:`import 'package:my_app/my_code.dart';
- Ensure the correct
context
is being used.确保使用正确的
context
。
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);
}
At a first glance over your code, I can see that you are passing MyChildState("Hello world !")
as the value, but later in MyParentWidget
class you are requesting a State
object final State state = Provider.of(context);
乍一看您的代码,我可以看到您正在传递
MyChildState("Hello world !")
作为值,但稍后在MyParentWidget
类中,您正在请求一个State
对象final State state = Provider.of(context);
. .
Try requesting MyChildState
instead of State
.尝试请求
MyChildState
而不是State
。
My first impression after reading your code is that you are coming from a different programming language and now you are trying Flutter.阅读您的代码后,我的第一印象是您来自不同的编程语言,现在您正在尝试 Flutter。 A friendly advice would be keep everything as simple as possible .
一个友好的建议是让一切尽可能简单。
All the abstraction and how the code is organized might confuse you later when you review the code you wrote instead of helping you.所有的抽象和代码的组织方式可能会在您稍后查看您编写的代码而不是帮助您时使您感到困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.