【问题标题】:Error related to Flutter provider package与 Flutter 提供程序包相关的错误
【发布时间】:2021-09-30 06:12:45
【问题描述】:

我正在我的颤振应用程序中构建一个设置小部件,我收到了这个错误:

错误:在此 SettingsForm 小部件上方找不到正确的提供程序

更新添加整个调试sn-p:

Launching lib\main.dart on AOSP on IA Emulator in debug mode...

════════ Exception caught by widgets library ═══════════════════════════════════
The following ProviderNotFoundException was thrown building SettingsForm(dirty, state: _SettingsFormState#c73b8):
Error: Could not find the correct Provider<MyUser> above this SettingsForm Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that SettingsForm is under your MultiProvider/Provider<MyUser>.
  This usually happens when you are creating a provider and trying to read it immediately.

  For example, instead of:

  ```
  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // Will throw a ProviderNotFoundError, because `context` is associated
      // to the widget that is the parent of `Provider<Example>`
      child: Text(context.watch<Example>()),
    ),
  }
  ```

  consider using `builder` like so:

  ```
  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>()),
      }
    ),
  }
  ```

If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter


The relevant error-causing widget was
SettingsForm
When the exception was thrown, this was the stack
#0      Provider._inheritedElementOf
#1      Provider.of
#2      _SettingsFormState.build
#3      StatefulElement.build
#4      ComponentElement.performRebuild
...
════════════════════════════════════════════════════════════════════════════════

我更新了它并添加了一些额外的代码,以便您能看得更清楚

setting.dart:

class SettingsForm extends StatefulWidget {
  @override
  _SettingsFormState createState() => _SettingsFormState();
}

class _SettingsFormState extends State<SettingsForm> {
  final _formKey = GlobalKey<FormState>();
  final List<String> sugars = ['0', '1', '2', '3', '4'];
  final List<int> strengths = [100, 200, 300, 400, 500, 600, 700, 800, 900];

  // form values
  String? _currentName;
  String? _currentSugars;
  int? _currentStrength;

  @override
  Widget build(BuildContext context) {
    MyUser user = Provider.of<MyUser>(context);

    return StreamBuilder<UserData>(
        stream: DatabaseService(uid: user.uid).userData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            UserData? userData = snapshot.data;
            return Form(
              key: _formKey,
              child: Column(
                children: <Widget>[
                  Text(
                    'Update your brew settings.',
                    style: TextStyle(fontSize: 18.0),
                  ),
                  SizedBox(height: 20.0),
                  TextFormField(
                    initialValue: userData!.name,
                    decoration: textInputDecoration,
                    validator: (val) =>
                        val!.isEmpty ? 'Please enter a name' : null,
                    onChanged: (val) => setState(() => _currentName = val),
                  ),
                  SizedBox(height: 10.0),
                  DropdownButtonFormField<String>(
                    value: _currentSugars ?? userData.sugars,
                    decoration: textInputDecoration,
                    items: sugars.map((sugar) {
                      return DropdownMenuItem(
                        value: sugar,
                        child: Text('$sugar sugars'),
                      );
                    }).toList(),
                    onChanged: (val) => setState(() => _currentSugars = val),
                  ),
                  SizedBox(height: 10.0),
                  Slider(
                    value: (_currentStrength ?? userData.strength).toDouble(),
                    activeColor:
                        Colors.brown[_currentStrength ?? userData.strength],
                    inactiveColor:
                        Colors.brown[_currentStrength ?? userData.strength],
                    min: 100.0,
                    max: 900.0,
                    divisions: 8,
                    onChanged: (val) =>
                        setState(() => _currentStrength = val.round()),
                  ),
                  ElevatedButton(
                      style:
                          ElevatedButton.styleFrom(primary: Colors.pink[400]),
                      child: Text(
                        'Update',
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () async {
                        if (_formKey.currentState!.validate()) {
                          await DatabaseService(uid: user.uid).updateUserData(
                              _currentSugars ?? snapshot.data!.sugars,
                              _currentName ?? snapshot.data!.name,
                              _currentStrength ?? snapshot.data!.strength);
                          Navigator.pop(context);
                        }
                      }),
                ],
              ),
            );
          } else {
            return Loading();
          }
        });
  }
}

更新:我正在包含包含“设置表单”小部件的 HOME.DART 文件 home.dart:

class Home extends StatelessWidget {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {

    void _showSettingsPanel() {
      showModalBottomSheet(context: context, builder: (context) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 60.0),
          child: SettingsForm(), <-- Here
        );
      });
    }

    return StreamProvider<List<Brew>?>.value(
      value: DatabaseService(uid: '').brews,
      initialData: null,
      child: Scaffold(
        backgroundColor: Colors.brown[50],
        appBar: AppBar(
          title: Text('Brew Crew'),
          backgroundColor: Colors.brown[400],
          elevation: 0.0,
          actions: <Widget>[
            TextButton.icon(
              icon: Icon(Icons.person),
              label: Text('logout'),
              onPressed: () async {
                await _auth.signOut();
              },
            ),
            TextButton.icon(
              icon: Icon(Icons.settings),
              label: Text('settings'),
              onPressed: () => _showSettingsPanel(),
            )
          ],
        ),
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/coffee_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: BrewList()
        ),
      ),
    );
  }
}

user.dart:

class MyUser {

  final String uid;
  
  MyUser({ required this.uid });

}

class UserData {

  final String uid;
  final String name;
  final String sugars;
  final int strength;

  UserData({ required this.uid, required this.sugars, required this.strength, required this.name });

}

Update Update 2 Error

【问题讨论】:

  • 你为什么在构建中定义那个方法?
  • 如果您的意思是提供程序类,它们是在小部件中构建的。
  • 我的意思是_showSettingsPanel方法。

标签: android flutter mobile flutter-layout


【解决方案1】:

因为你必须在你使用它的类上面声明提供者类,如果你发现这个 ans crt 将它标记为 crt

 @override
Widget build(BuildContext context) {
return MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (ctx) => MyUser(),),
    
  ],
  child: MaterialApp());

【讨论】:

  • 您能简单解释一下造成问题的原因吗?
  • 如果您在小部件中使用提供程序类,那么您必须在该类之上声明它,因此最好将其声明在所有小部件之上,因此在 MaterialApp 之上声明它
  • 我没有在 main.dart 中使用它,我在 setting_form.dart 中使用它
【解决方案2】:

您必须使用您在内部使用的提供程序类来扭曲父类。为此,最简单的方法是在具有MaterialPageRoute 的小部件中添加一个静态方法,这有助于导航到SettingsForm 屏幕。

class SettingsForm extends StatefulWidget {

  static Widget getWidget() {
    return new Provider(
        create: (_) => MyUser(),
        child: ChangeNotifierProvider(
          create: (BuildContext context) => MyUser(),
          builder: (_,_) => SettingsForm()
        ),
     );
  }

  @override
  _SettingsFormState createState() => _SettingsFormState();
}

要打开SettingsForm 屏幕,只需在按下按钮时调用getRoute 函数。检查下面的代码。

从主屏幕打开 SettingsForm 屏幕

 void _showSettingsPanel() {
      showModalBottomSheet(context: context, builder: (context) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 60.0),
          child: SettingsForm.getWidget(), <-- Here
        );
      });
    }

【讨论】:

  • 感谢回复我也更新了我的代码
  • 我最近遇到了一些问题
  • 更新我正在使用流提供程序,设置栏位于应用程序的主屏幕(home.dart)中
  • @Alphamerc 在更改通知提供程序上出现错误,请在我的 q 中查看更新截图
  • MyUser 类是否扩展了ChangeNotifier 类?
猜你喜欢
  • 2021-10-01
  • 2021-12-15
  • 2021-11-07
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多