在此ModalBottomSheet小部件上方找不到正确的Provider <X>

时间:2020-07-26 06:45:28

标签: flutter dart flutter-provider

我是新手,我试图了解如何在应用程序中使用提供者状态管理,该应用程序让用户Moor将某些数据保存到sqlite表中。我的应用程序是一个任务记录应用程序。打开底页添加任务时,我的小部件树中出现上述错误。我正在使用provider: ^4.3.1

class TaskView extends StatelessWidget {
  DateTime selectedDate = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Provider<TaskViewModel>(
        create: (_) => TaskViewModel(),
        child: Scaffold(
            appBar: AppBar(
              title: Text('Tasks'),
            ),
            body: Text("Temporary body!"),
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                showMaterialModalBottomSheet(
                  context: context,
                  builder: (context, scrollController) => Container(
                    child: bottomSheet(context),
                  ),
                );
              },
              child: Icon(
                Icons.add,
                color: Colors.white,
              ),
              backgroundColor: Colors.blueAccent,
            )
        )
    );
  }

  Widget bottomSheet(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
          left: 16.0,
          top: 16.0,
          right: 16.0,
          bottom: 16.0 + MediaQuery.of(context).viewInsets.bottom),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Task',
            ),
          ),
          SizedBox(height: 8),
          TextField(
            readOnly: true,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              suffixIcon: IconButton(
                icon: Icon(Icons.date_range, color: Colors.grey),
                onPressed: () => _selectDate(context),
              ),
              labelText: 'Date',
            ),
          ),
          SizedBox(height: 8),
          Align(
              alignment: Alignment.topRight,
              child: context.watch<TaskViewModel>().state == ViewState.IDLE
                  ? FlatButton(
                      child: Text("Save"),
                      color: Colors.blueAccent,
                      textColor: Colors.white,
                      onPressed: () => _onClickInsertTask(context))
                  : _loadingButtonChild(context))
        ],
      ),
    );
  }

  Widget _loadingButtonChild(BuildContext context) {
    return Container(
      height: 20,
      width: 20,
      margin: EdgeInsets.all(5),
      child: CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white)),
    );
  }

  /// This function is responsible for displaying the date picker when user click
  /// on task due date inputFiled
  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));

    if (picked != null && picked != selectedDate) {
      print("Date selected ${selectedDate.toString()}");
    }
  }

  /// This function is responsible for triggering insert task block event
  void _onClickInsertTask(BuildContext context) {

    var insertTask = TaskData(task: "task", dueDate: selectedDate);
    context.read<TaskViewModel>().insertTask(insertTask);
  }
}

建议检查错误。

-您尝试阅读的提供者的路径不同。

我没有给提供者s路由,而是作为直接父视图。

-您使用的BuildContext是您尝试读取的提供者的祖先。

我不明白这意味着什么,但是我对错误进行了建议的修复。像下面一样

@override
  Widget build(BuildContext context) {
    return Provider<TaskViewModel>(
        create: (_) => TaskViewModel(),
        builder: (context, child) => Scaffold(
            appBar: AppBar(
              title: Text('Tasks'),
            ),
            body: Text("Temporary body!"),
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                showMaterialModalBottomSheet(
                  context: context,
                  builder: (context, scrollController) => Container(
                    child: bottomSheet(context),
                  ),
                );
              },
              child: Icon(
                Icons.add,
                color: Colors.white,
              ),
              backgroundColor: Colors.blueAccent,
            )));
  }

仍然出现相同的错误。这里要注意的另一件事是以下错误提示。

Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context) {
        // No longer throws
        return Text(context.watch<Example>()),
      }
    ),
  }

但是我找不到builder: (context),所以我使用了builder: (context, child)。请让我知道我应该进行哪些更改才能使此工作正常进行。谢谢。

编辑:

BaseModel

class BaseViewModel extends ChangeNotifier {

  ViewState _state = ViewState.IDLE;

  ViewState get state => _state;

  void setState(ViewState viewState) {
    _state = viewState;
    notifyListeners();
  }
}

TaskViewModel

class TaskViewModel extends BaseViewModel{

  final TaskRepository _repository = TaskRepository();

  Resource<int> insertTaskStatus;

  Future<void> insertTask(TaskData task) async {

    setState(ViewState.PROCESSING);
    var tasksCompanion = TasksCompanion(task: Value(task.task),dueDate: Value(task.dueDate));
    insertTaskStatus  = await  _repository.insertTask(tasksCompanion);
    setState(ViewState.COMPLETED);

  }

}

1 个答案:

答案 0 :(得分:1)

尽管您在由showMaterialModalBottomSheet包裹的Scaffold中调用provider,但是provider不在TaskView的{​​{1}}和{ Scaffold。为什么?

您尝试读取的提供者位于另一条路由中。

因此,看来modalBottomSheet在另一个modalBottomSheet之上,而上面没有route。如果看一下showModalBottomSheet的实现,您会看到:

provider

很明显,这是一个新的return Navigator.of(context, rootNavigator: useRootNavigator).push(_ModalBottomSheetRoute<T>(....);。因此,要访问route,它应该同时位于provider之上。由于routes modalBottomSheetroute管理,因此您必须将MaterialApp放在provider上方。

MaterialApp默认使用Provider。因此,对象是在需要时创建的,而不是在应用启动时创建的。但是,如果您不希望出现这种情况,则可以单独设置lazy loading。有关更多信息,请检查offical docs