Flutter:无法从定义到另一个文件的函数调用Provider 。of(context)。 ProviderNotFoundException

问题描述 投票:0回答:1

我是新手,我希望整理我的文件夹以编写简洁的代码。我试图将页面分为三个部分:

  1. login_view.dart(此视图将呈现为登录视图,并将调用在login_builder.dart中定义的函数以构建其每个小部件)]]
  2. login_builder.dart
  3. (包含由login_view.dart调用以构建窗口小部件的函数定义)
  4. login_state.dart
  5. (用于状态管理)

    但是当我在login_builder.dart(在login_view.dart小部件树中)定义的函数中调用Provider.of(context)

时,它总是抛出ProviderNotFoundException

// login_view.dart

import 'package:discover/ui/views/login/login_builder.dart';
import 'package:discover/ui/views/login/login_state.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<LoginState>(
      create: (context) => LoginState(),
      child: buildLoginForm(context), 
    );
  }
}

// login_builder.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:discover/ui/views/login/login_state.dart';

Widget buildLoginForm(BuildContext context) {
  var loginState = Provider.of<LoginState>(context);
  return Form(
    child: Column(
      children: <Widget>[
        TextFormField(
          onChanged: (value) => loginState.userName = value,
        )
      ],
    ),
  );
}

// login_state.dart

import 'package:flutter/material.dart';

class LoginState extends ChangeNotifier {
  String _userName = "";

  String get userName => _userName;

  set userName(String userName) {
    _userName = userName;
  }
}

//调试控制台

════════ Exception caught by widgets library ═══════════════════════════════════
The following ProviderNotFoundException was thrown building Login(dirty):
Error: Could not find the correct Provider<LoginState> above this Login Widget

To fix, please:

  * Ensure the Provider<LoginState> is an ancestor to this Login Widget
  * Provide types to Provider<LoginState>
  * Provide types to Consumer<LoginState>
  * Provide types to Provider.of<LoginState>()
  * Ensure the correct `context` is being used.

If none of these solutions work, please file a bug at:
https://github.com/rrousselGit/provider/issues

The relevant error-causing widget was
    Login
When the exception was thrown, this was the stack
Provider.of
buildLoginForm
Login.build
StatelessElement.build
ComponentElement.performRebuild

我是新手,我希望整理我的文件夹以编写简洁的代码。我试图将页面分为三个部分:login_view.dart(此视图将显示为登录名...

flutter dart provider state-management
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.