Fluent implements nested state management using provider

Preface

Last one Use MultiProvider Share status data with multiple pages in , We introduced the use of Provider Modify the dynamic module to complete the logic of deletion and detail page . In fact, there are some awkward places in the transformation process , such as :

  • We are DynamicModel Class added a _currentDynamic For details page , And this object has nothing to do with the list , Just for the details page .
  • updateViewCount This method is also related to a single dynamic class .

This leads to the coupling of the business of our list page and the business of details , If we add 、 Update and other dynamic related businesses are lost, which leads to the arrival of this state management class , In turn, the state management class will be very bloated , It also violates the principle of single responsibility . What to do at this time ?

Naturally we think of splitting , Yes , At this time, we need to split the states of different interfaces . In this article, we take adding pages as an example , Talk about nested state management .

Add the status management of the page

Let's first add a state management class for adding pages DynamicAddModel, Then move the business code of the previously added page into . The specific attributes and definition methods are as follows :

  • Map<String, Map<String, Object>> _formData: Form configuration Map, A form used to dynamically configure and add pages .
  • File_imageFile: Selected image file .
  • DynamicEntity _currentDynamic: Dynamic object after successful addition , Used to add to the list after successful addition , This prevents the list from refreshing again .
  • handleTextFieldChanged(String formKey, String value): After the content of the input box changes , Processing callback method for updating form data ;
  • handleClear(String formKey): Processing callback method when the input box clear button is clicked ;
  • handleImagePicked(File imageFile): Processing callback method after successful image selection ;
  • Future<bool> handleSubmit(): Form submission method , What's coming back here is a Future<bool> object , When successful, return true, Return... On failure false. So that the interface can be processed later , Here is the data to be added to the dynamic list after success , And return to the list page .

Add page transformation

With state management , Adding pages is extremely simple , The difference is that we need to use a DynamicAddWrapper The component package adds a real page , In order to use... In the upper level of the added page Provider Realize the state management of adding pages . The code is as follows :

class _DynamicAdd extends StatelessWidget {
  _DynamicAdd({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final watchState = context.watch<DynamicAddModel>();
    final readState = context.read<DynamicAddModel>();
    return Scaffold(
      appBar: AppBar(
        title: Text(' Add dynamic '),
        brightness: Brightness.dark,
      ),
      body: DynamicForm(
        watchState.formData,
        readState.handleTextFieldChanged,
        readState.handleClear,
        ' Submit ',
        () {
          readState.handleSubmit().then((success) {
            if (success) {
              context.read<DynamicModel>().add(readState.currentDynamic);
              Navigator.of(context).pop();
            }
          });
        },
        readState.handleImagePicked,
        imageFile: watchState.imageFile,
      ),
    );
  }
}

class DynamicAddWrapper extends StatelessWidget {
  DynamicAddWrapper({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => DynamicAddModel(),
      child: _DynamicAdd(),
    );
  }
}

Note that here we add the page _DynamicAdd It becomes an internal class of the file , This is because after adding state management , You must have a superior status management package component to use . Encapsulation as an internal class can avoid external direct use of the component to report errors . about _DynamicAdd class , We have made the following modifications :

  • Move the business code to the state management class ;
  • The components are StatefulWidget Change it to StatelessWidget;
  • Replace the callback processing method of the form with the corresponding method of the status management object ;

Use of nested states

Add pages dynamically , Our processing code after successful submission is as follows :

readState.handleSubmit().then((success) {
  if (success) {
    context.read<DynamicModel>().add(readState.currentDynamic);
    Navigator.of(context).pop();
  }
});

The first thing here is to call DynamicAddModel Of handleSubmit Method , And then in Future Of then The callback method calls the state management object of the dynamic list DynamicModel, That is, the above level of state management is used , It is equivalent to that we use different levels of state management at the same time , That is, nesting uses . This is because Provider It's right in itself InheritedWidget Encapsulation , Therefore, multi-level nesting is actually the same as Widget Nested like , It can be used like this .

By pulling out the status of the added page , Does it feel like the whole UI The code of layer is refreshing a lot ? And for teamwork , After we agreed UI Layer interface , The development work can be divided into business code and UI Look at the code , So as to realize division of labor and cooperation —— however , Which boss will let me do App What about the development of business only or interface only ? What they want is such a great God !

image.png
image.png

summary

The code has been submitted to : State management chapter source code . The first mock exam can further manage the state management of different business modules in the same module. , This avoids the bloated state management code , Make the code conform to the principle of single responsibility . however , Let's go back to the code for dynamically adding and updating pages , You'll find... In it 90% The code is similar , This feeling is a little repeated , What should I do if I want to share it ? In the next article, we will introduce it through the dynamic update page Provider Reuse of state management objects .

Please bring the original link to reprint ,thank
Similar articles

2021-11-25

2021-11-25

2021-11-25

2021-11-25