Как обернуть функцию виджета потребителем и установить его функцию onPressed с помощью провайдера? - PullRequest
0 голосов
/ 12 июля 2020

Я новичок в флаттере и учусь на провайдера. Мое приложение предназначено для того, чтобы сделать много кнопок, каждая кнопка меняет цвет чего-то определенного c в пользовательском интерфейсе приложения (панель приложения, фон, ящик и т. Д. c ..). Итак, чтобы упростить код, я должен сделать функцию виджета кнопки следующим образом:

Widget colorButton( Color c){
  return RaisedButton(
    onPressed: (){},
    color: c,
  );
}

Но я заметил, что я не могу назначить функцию onPressed, когда я вызываю эту кнопку, чтобы изменить цвет чего-либо. Итак (я не знаю, лучший ли это способ сделать это или есть другой способ) я изменил функцию на:

Widget colorButton( Color c, Function f){
  return RaisedButton(
    onPressed: (){f();},
    color: c,
  );
}

Затем я передаю функцию модели, которую я сделал ранее в модели вот так:

class bG_Vairables extends ChangeNotifier{
  Color bG;
  Function setBG(Color c){
    bG = c;
    notifyListeners();
  }
}

Я делаю такой экземпляр:

Consumer<bG_Vairables>(builder: (context, v, child){
                            return colorButton(Color.fromRGBO(240, 230, 255,1) , v.setBG(Color.fromRGBO(240, 230, 255,1)));
                          },
                        ),

Но я получаю эту ошибку:

The following ProviderNotFoundException was thrown building Consumer<bG_Vairables>(dirty):
Error: Could not find the correct Provider<bG_Vairables> above this Consumer<bG_Vairables> Widget

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

- 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 Consumer<bG_Vairables> is under your MultiProvider/Provider<bG_Vairables>.
  This usually happen when you are creating a provider and trying to read it immediatly.

  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: 
  Consumer<bG_Vairables> file:///C:/Users/Mu'men/AndroidStudioProjects/provider_project/lib/main.dart:46:18
When the exception was thrown, this was the stack: 
#0      Provider._inheritedElementOf (package:provider/src/provider.dart:269:7)
#1      Provider.of (package:provider/src/provider.dart:221:30)
#2      Consumer.buildWithChild (package:provider/src/consumer.dart:177:16)
#3      SingleChildStatelessWidget.build (package:nested/nested.dart:260:41)
#4      StatelessElement.build (package:flutter/src/widgets/framework.dart:4576:28)
...
...