如何使用使用者包装小部件函数并使用提供者将其设置为onPressed函数?

时间:2020-07-12 19:42:04

标签: flutter flutter-provider state-management

我是新手,正在学习提供者。我的应用程序是要使许多按钮每个按钮更改应用程序ui中特定的颜色(应用程序栏,背景,抽屉等)。因此,为了使代码更容易,我应该使按钮小部件功能如下:

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)
...

1 个答案:

答案 0 :(得分:0)

您必须在编写from selenium import webdriver browser = webdriver.Chrome() # We go to the webpage here and wait 2 seconds for fully load browser.get('https://someURL') time.sleep(2) # Where to save the picture directory = '/home' # Video title title = 'Hello world' try: # We try to get the top-level component in which all out page is its children # This is different for each website elem = browser.find_element_by_id('main-layout-content') # Get the height of the element, and adding some height just to be sage total_height = elem.size['height'] + 1000 # Set the window size - what is the size of our screenshot # The width is hardcoded because the screensize is fixed for each computer browser.set_window_size(1920, total_height) # Wait for 2 seconds time.sleep(2) # Take the screenshot browser.find_element_by_id( 'main-layout-content').screenshot(f'./{directory}/{title}.png') except SystemError as err: print('Take screenshot error at' + title) 的小部件的祖先上添加ChangeNotifierProvider

例如

当前,如果您要像这样进入colorButton()的StatefulWidget页面(将其命名为ColorButtonPage):

colorButton()

将其更改为此:

Navigator.of(context).push(MaterialPageRoute(builder:(context)=>ColorButtonPage()))

这样,消费者将能够找到bG_Vairables对象。