InheritedWidget共享数据学习

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ShareDataWidget extends InheritedWidget {
  ShareDataWidget({Key? key, required this.child, required this.data})
      : super(key: key, child: child);

  final Widget child;
  final T data;

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

class ChangeNotifierProvider extends StatefulWidget {
  ChangeNotifierProvider({Key? key, required this.child, required this.creater})
      : super(key: key);
  final T Function(BuildContext context) creater;
  final Widget child;
  //添加一个listen参数,表示是否建立依赖关系
  static T of(BuildContext context, {bool listen = true}) {
    final provider = listen
        ? context.dependOnInheritedWidgetOfExactType>()
        : context
            .getElementForInheritedWidgetOfExactType>()
            ?.widget as ShareDataWidget;
    return provider!.data;
  }

  // 需要使用_ChangeNotifierProviderState 不然后会provider会是null
  // @override
  // State createState() =>
  //     _ChangeNotifierProviderState();
  _ChangeNotifierProviderState createState() =>
      _ChangeNotifierProviderState();
}

class _ChangeNotifierProviderState
    extends State {
  late T data;
  @override
  void initState() {
    data = widget.creater(context) as T;
    data.addListener(update);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ShareDataWidget(child: widget.child, data: data);
  }

  @override
  void dispose() {
    data.removeListener(update);
    super.dispose();
  }

  update() {
    setState(() {});
  }
}

class Consumer extends StatelessWidget {
  const Consumer({Key? key, required this.builder}) : super(key: key);
  final Widget Function(BuildContext context, T value) builder;

  @override
  Widget build(BuildContext context) {
    return builder(context, ChangeNotifierProvider.of(context));
  }
}

class ThemeState extends ChangeNotifier {
  late int settingThemeCoror;
  ThemeState({required this.settingThemeCoror});
  void changeTheme(int thmeColor) {
    this.settingThemeCoror = thmeColor;
    notifyListeners();
  }
}

class InheritedWidgetTestRoute extends StatefulWidget {
  @override
  _InheritedWidgetTestRouteState createState() =>
      _InheritedWidgetTestRouteState();
}

class _InheritedWidgetTestRouteState extends State {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      creater: (context) => ThemeState(settingThemeCoror: 222),
      child: Consumer(builder: (context, value) {
        return Column(
          children: [
            Container(
              child: Text(value.settingThemeCoror.toString()),
            ),
            CupertinoButton(
                child: Text("新增"),
                onPressed: () {
                  value.changeTheme(12345);
                })
          ],
        );
      }),
    );
  }
}

你可能感兴趣的:(InheritedWidget共享数据学习)