状态管理

2020-01-31  本文已影响0人  梦幽辰

InheritedWidget

// 爷爷组件
class StateManagementDemo extends StatefulWidget {
  @override
  _StateManagementDemoState createState() => _StateManagementDemoState();
}

class _StateManagementDemoState extends State<StateManagementDemo> {
  int _count = 0;

  void _transform() {
    setState(() {
      _count += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return CounterProvider(
      count: _count,
      transform: _transform,
      child: Scaffold(
          appBar: AppBar(
            title: Text('StateManagementDemo'),
            elevation: 0,
          ),
          body: CounterWrapper()),
    );
  }
}
// 父亲组件
class CounterWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Counter();
  }
}
// 孙组件
class Counter extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final int count = CounterProvider.of(context).count;
    final VoidCallback transform = CounterProvider.of(context).transform;
    return Center(
      child: ActionChip(label: Text('$count'), onPressed: transform),
    );
  }
}
// 状态管理组件
class CounterProvider extends InheritedWidget {
  final int count;
  final VoidCallback transform;
  final Widget child;

  CounterProvider({this.count, this.transform, this.child}) : super(child: child);

  static CounterProvider of(BuildContext context) => context.inheritFromWidgetOfExactType(CounterProvider);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}

ScopedModel(第三方库)

// 爷爷组件
class StateManagementDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScopedModel(
      model: CounterModel(),
      child: Scaffold(
        appBar: AppBar(
          title: Text('StateManagementDemo'),
          elevation: 0,
        ),
        body: CounterWrapper(),
        floatingActionButton: ScopedModelDescendant<CounterModel>(
          rebuildOnChange: false,
          builder: (context, _, model) => FloatingActionButton(
            child: Icon(Icons.add), 
            onPressed: model.transform
          ),
        ),
      ),
    );
  }
}
// 父亲组件
class CounterWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Counter();
  }
}
// 孙组件
class Counter extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<CounterModel>(
      builder: (context, _, model)=>ActionChip(
        label: Text('${model.count}'),
        onPressed: model.transform,
      ),
    );
  }
}
// 状态管理组件
class CounterModel extends Model {
  int _count = 0;
  int get count => _count;

  void transform() {
    _count += 1;
    notifyListeners();
  }
}
上一篇下一篇

猜你喜欢

热点阅读