Imperative Flutter

使用命令式编程概念管理小部件状态。

设置

在pubspec.yaml中安装 imperative_flutter 包

dependencies:
  imperative_flutter: ^0.0.2

然后在你的代码中导入即可

import 'package:imperative_flutter/imperative_flutter.dart';

用法

ImperativeProvider 负责存储和处理 ImperativeBuilder 的引用,它可以是 全局范围MaterialApp 是其子组件时,也可以是 局部范围Scaffold 是你的子组件时。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ImperativeProvider(
      child: MaterialApp(
        title: 'Imperative Flutter Demo',
        home: MyHomePage(),
      ),
    );
  }
}

ImperativeBuilder 负责存储我们组件的状态并在该状态更改时重建它,请注意,id 必须在每个 ImperativeProvider 作用域内唯一。

// Inside StatelessWidget

ImperativeBuilder<int>(
    id: 'count',
    initialData: 0,
    /* the builder method will be called every time the state changes,
    updating only the widget within the scope */
    builder: (context, snapshot) {
        return Container(
            height: 48,
            width: 48,
            color: Colors.pink,
            child: Center(
                child: Text(
                    '${snapshot.data}',
                    style: TextStyle(color: Colors.white),
                  ),
            ),
        );
    },
),

// ...

class Whatever extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Get instance of ImperativeProvider
    final imperative = ImperativeProvider.of(context);

    return ElevatedButton.icon(
            onPressed: () {
                // Get current state of ImperativeBuilder where id equal 'count'
                final value = imperative.getState<int>('count');
                // Set state of ImperativeBuilder where id equal 'count' and rebuild
                imperative.setState('count', value + 1);
            },
            icon: Icon(Icons.add),
            label: Text('plus'),
    ),
  }

GitHub

https://github.com/JunioJsv/imperative-flutter