Flutter入门13 -- 状态管理

2021-12-03  本文已影响0人  YanZi_33

状态管理分类

image.png

共享状态管理

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

main() => runApp(SFMyApp());

class SFCounterWidget extends InheritedWidget {
  final int counter;

  SFCounterWidget({this.counter, Widget child}) : super(child:child);

  static SFCounterWidget of(BuildContext ctx) {
    //沿着Element树 去找到最近的SFCounterWidgetElement,然后从element中取出widget对象
    return ctx.dependOnInheritedWidgetOfExactType();
  }

  //返回true:依赖当前SFCounterWidget的widget的state类 会执行didChangeDependencies()方法
  @override
  bool updateShouldNotify(SFCounterWidget oldWidget) {
    return oldWidget.counter != counter;
  }
}

class SFMyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SFHomePage(),
    );
  }
}

class SFHomePage extends StatefulWidget {
  @override
  _SFHomePageState createState() => _SFHomePageState();
}

class _SFHomePageState extends State<SFHomePage> {
  int _counter = 1000;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter测试共享数据"),
      ),
      body: SFCounterWidget(
        counter: _counter,
        child: Column(
          children: [
            SFShowData01(),
            SFShowData02(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: (){
          setState(() {
            _counter++;
          });
        },
      ),
    );
  }
}

class SFShowData01 extends StatefulWidget {
  @override
  _SFShowData01State createState() => _SFShowData01State();
}

class _SFShowData01State extends State<SFShowData01> {

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("_SFShowData01State 执行了 didChangeDependencies方法");
  }

  @override
  Widget build(BuildContext context) {
    int counter = SFCounterWidget.of(context).counter;
    return Card(
      color: Colors.red,
      child: Text("当前计数: $counter"),
    );
  }
}

class SFShowData02 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int counter = SFCounterWidget.of(context).counter;
    return Card(
      color: Colors.green,
      child: Text("当前计数: $counter"),
    );
  }
}
image.png
static SFCounterWidget of(BuildContext ctx) {
    //沿着Element树 去找到最近的SFCounterWidgetElement,
    //然后从element中取出widget对象
    return ctx.dependOnInheritedWidgetOfExactType();
  }
@override
  bool updateShouldNotify(SFCounterWidget oldWidget) {
    return oldWidget.counter != counter;
  }
Provider
dependencies:
  provider: ^4.0.4
Provider.of的使用
import 'package:flutter/material.dart';

//创建共享数据模型
class SFCounterViewModel extends ChangeNotifier{
  int _counter = 1000;

  int get counter => _counter;

  set counter(int value) {
    _counter = value;
    notifyListeners();
  }
}
import 'package:flutter/material.dart';
import 'package:learn_flutter_01/day02/viewmodel/SFCounterViewModel.dart';
import 'package:provider/provider.dart';

void main() {
  //2.在应用程序的顶层 包装一个ChangeNotifierProvider
  runApp(
    ChangeNotifierProvider(
      create: (ctx) => SFCounterViewModel(),
      child: SFMyApp(),
    )
  );
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SFHomePage(),
    );
  }
}

class SFHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFHomePage build");
    return Scaffold(
        appBar: AppBar(
          title: Text("商品列表"),
        ),
        body: Column(
          children: [
            SFShowData01()
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: (){
            ///更改共享数据模型中的数据 发送通知 本质是调用共享数据模型的setter方法
            context.read<SFCounterViewModel>().counter+=1;
            ///Provider.of<SFCounterViewModel>(context, listen: false).counter+=1;
          },
          child: Icon(Icons.add),
        )
    );
  }
}
///子组件一
class SFShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFShowData01 build");
    ///通知回调 更新数据 本质是调用共享数据模型的getter方法 获取数据
    int counter = Provider.of<SFCounterViewModel>(context).counter;
    return Card(
      color: Colors.red,
      child: Text("当前计数: $counter"),
    );
  }
}
image.png
Consumer的使用
class SFShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFShowData01 build");
    ///通知回调 更新数据 本质是调用共享数据模型的getter方法 获取数据
    return Card(
        color: Colors.red,
        child: Consumer<SFCounterViewModel>(
          builder: (ctx, viewModel, child) {
            return Text("当前计数: ${viewModel.counter}");
          }
        )
    );
  }
}
selector的使用
import 'package:flutter/cupertino.dart';

class SFCounterViewModel extends ChangeNotifier {

  int _counter = 1000;
  int _number = 50;

  int get counter => _counter;

  set counter(int value) {
    _counter = value;
    ///发送通知 给观察者
    notifyListeners();
  }

  int get number => _number;

  set number(int value) {
    _number = value;

    notifyListeners();
  }
}
import 'package:SFLayout/provider/counter_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

main() {
  runApp(
      ///App顶层包装ChangeNotifierProvider组件
      ChangeNotifierProvider(
    create: (context) => SFCounterViewModel(),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SFHomePage(),
    );
  }
}

class SFHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFHomePage build");
    return Scaffold(
        appBar: AppBar(
          title: Text("商品列表"),
        ),
        body: Column(
          children: [
            SFShowData01(),
            SFShowData02()
          ],
        ),
        floatingActionButton: FloatingActionButton(
           onPressed: () {
             ///更改共享数据模型中的数据 发送通知 本质是调用共享数据模型的setter方法
             Provider.of<SFCounterViewModel>(context,listen: false).counter+=1;
             // context.read<SFCounterViewModel>().counter+=1;
           },
           child: Icon(Icons.add),
        )
    );
  }
}

///子组件一
class SFShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFShowData01 build");
    ///通知回调 更新数据 本质是调用共享数据模型的getter方法 获取数据
    return Card(
        color: Colors.red,
        child: Consumer<SFCounterViewModel>(
          builder: (ctx, viewModel, child) {
            print("counter");
            return Text("当前计数counter: ${viewModel.counter}");
          }
        )
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return  Card(
        color: Colors.green,
        child: Consumer<SFCounterViewModel>(
            builder: (ctx, viewModel, child) {
              print("number");
              return Text("当前计数number: ${viewModel.number}");
            }
        )
    );
  }
}
image.png
import 'package:SFLayout/provider/counter_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

main() {
  runApp(
      ///App顶层包装ChangeNotifierProvider组件
      ChangeNotifierProvider(
    create: (context) => SFCounterViewModel(),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SFHomePage(),
    );
  }
}

class SFHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFHomePage build");
    return Scaffold(
        appBar: AppBar(
          title: Text("商品列表"),
        ),
        body: Column(
          children: [
            SFShowData01(),
            SFShowData02()
          ],
        ),
        floatingActionButton: FloatingActionButton(
           onPressed: () {
             ///更改共享数据模型中的数据 发送通知 本质是调用共享数据模型的setter方法
             Provider.of<SFCounterViewModel>(context,listen: false).counter+=1;
             // context.read<SFCounterViewModel>().counter+=1;
           },
           child: Icon(Icons.add),
        )
    );
  }
}

///子组件一
class SFShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFShowData01 build");
    ///通知回调 更新数据 本质是调用共享数据模型的getter方法 获取数据
    return Card(
        color: Colors.red,
        child: Consumer<SFCounterViewModel>(
          builder: (ctx, viewModel, child) {
            print("counter");
            return Text("当前计数counter: ${viewModel.counter}");
          }
        )
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return  Card(
        color: Colors.green,
        child: Selector<SFCounterViewModel,int>(
          selector: (ctx,viewModel) => viewModel.number,
          builder: (ctx,numberValue,child) {
            print("number");
            return Text("当前计数number: ${numberValue}");
          },
        )
    );
  }
}
多个数据模型的共享
class SFUserInfoModel {
  String name;
  int level;
  String imageUrl;

  SFUserInfoModel(this.name,this.level,this.imageUrl);
}
import 'package:flutter/material.dart';
import 'package:learn_flutter_01/day02/model/SFUserInfoModel.dart';

class SFUserInfoViewModel extends ChangeNotifier {
  SFUserInfoModel _userInfo;

  SFUserInfoViewModel(this._userInfo);

  SFUserInfoModel get userInfo => _userInfo;

  set userInfo(SFUserInfoModel value) {
    _userInfo = value;
    notifyListeners();
  }
}
import 'package:flutter/material.dart';
import 'package:learn_flutter_01/day02/model/SFUserInfoModel.dart';
import 'package:learn_flutter_01/day02/viewmodel/SFCounterViewModel.dart';
import 'package:learn_flutter_01/day02/viewmodel/SFUserInfoViewModel.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (ctx) => SFCounterViewModel()),
        ChangeNotifierProvider(create: (ctx) => SFUserInfoViewModel(SFUserInfoModel("yanzi",20,"haha"))),
      ],
      child: SFMyApp(),
    )
  );
}

class SFMyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SFHomePage(),
    );
  }
}

class SFHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("SFHomePage build");
    return Scaffold(
      appBar: AppBar(
        title: Text("商品列表"),
      ),
      body: Column(
        children: [
          SFShowData01(),
          SFShowData02(),
          SFShowData03(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
           onPressed: () {
             ///更改共享数据模型中的数据 发送通知 本质是调用共享数据模型的setter方法
             // Provider.of<SFCounterViewModel>(context,listen: false).counter+=1;
             context.read<SFCounterViewModel>().counter+=1;
           },
           child: Icon(Icons.add),
        )
    );
  }
}

class SFShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    print("SFShowData01 build");

    //3.在需要使用共享数据的位置调用Provider.of方法
    int counter = Provider.of<SFCounterViewModel>(context).counter;
    return Card(
      color: Colors.red,
      child: Text("当前计数: $counter",style: TextStyle(fontSize: 25)),
    );
  }
}

class SFShowData02 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //int counter = Provider.of<SFCounterViewModel>(context).counter;
    print("SFShowData02 build");
    return Card(
      color: Colors.green,
      child: Consumer<SFCounterViewModel> (
        builder: (ctx,counterViewModel,child) {
          print("Consumer builder");
          return Text("当前计数: ${counterViewModel.counter}",style: TextStyle(fontSize: 25));
        },
      )
    );
  }
}

class SFShowData03 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer2<SFCounterViewModel,SFUserInfoViewModel>(
        builder: (ctx,countViewModel,userInfoViewModel,child){
          return Text(
              "nickname=${userInfoViewModel.userInfo.name} counter = ${countViewModel.counter}",
              style: TextStyle(fontSize: 25)
          );
        }
    );
  }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读