状态管理

2019-10-14  本文已影响0人  有一种感动叫做丶只有你懂

1.局部状态管理

局部状态管理实际上是替代了setState带来的没必要的渲染

1.状态管理

按照个人的理解来看,bloc其实是数据与ui分离的一种方案,也就是说每个页面都可以有bloc

2.StreamBuilder(不使用setDate,实现声明式渲染,)
import 'dart:async';
import 'package:app/blocs/test_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class TestModel {
  String name;
  int age;
  TestModel({this.name,this.age});
}
class ListPage extends StatefulWidget {
  @override
  _ListPage createState() {
    // TODO: implement createState
    return _ListPage();
  }
}

class _ListPage extends State<ListPage> {
  final StreamController<TestModel> streamController = StreamController<TestModel>();
  TestModel testModel = TestModel(name: '张三',age: 12);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return StreamBuilder<TestModel>(
      stream: streamController.stream,
      initialData: testModel,
      builder: (BuildContext context, AsyncSnapshot<TestModel> asyncSnapshot) {
        return Scaffold(
          appBar: AppBar(
            title: Text('榜单'),
          ),
          body: ListView(
            children: <Widget>[
              Text('名字${testModel.name},年龄${testModel.age}'),
              RaisedButton(onPressed: () => streamController.sink.add(testModel = TestModel(name: '杨志强',age: 22)),child: Text('增加'),)
            ],
          ),
        );
      },
    );
  }
}

2.全局状态管理

需要使用BlocProvider,要接收这个bloc的必须是BlocProvider的child,并且全局的状态的管理肯定是多页面共享的,需要使用支持多监听的控制器BehaviorSubject(),而不是StreamController(),使用多监听控制器的时候需要import 'package:rxdart/rxdart.dart';

BlocProvider.dart

import 'package:flutter/widgets.dart';

abstract class BlocBase {
  void dispose();
}

class BlocProvider<T extends BlocBase> extends StatefulWidget{
  BlocProvider({
    Key key,
    @required this.bloc,
    @required this.child

  }):super(key:key);

  final T bloc;
  final Widget child;
  static T of<T extends BlocBase>(BuildContext context){
    final type = _typeOf<BlocProvider<T>>();
    BlocProvider<T> provider = context.ancestorWidgetOfExactType(type);
    return provider.bloc;
  }

  ///获取类型
  static Type _typeOf<T>() => T;


  @override
  State<StatefulWidget> createState() => _BlocProvider();
}

class _BlocProvider extends State<BlocProvider<BlocBase>>{
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    widget.bloc.dispose();//自动销毁
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

userBloc.dart

import 'dart:async';
import 'package:app/blocs/provider_bloc.dart';
import 'package:rxdart/rxdart.dart';
class UserBloc implements BlocBase {
  int counter = 0;
  // 容器的控制器
  StreamController<int> _counterController = BehaviorSubject();

  Stream<int> get outCounter => _counterController.stream; //出口

  StreamSink get actionSink => _counterController.sink; //操作
  UserBloc() {
    // _counterController.sink.add(++counter);
  }
  @override
  void dispose() {
    // TODO: implement dispose
    _counterController.close();
  }
}

父容器实际使用BlocProvider

  @override
  Widget build(BuildContext context) {
    return BlocProvider<UserBloc>(bloc: UserBloc(),child: MaterialApp(
      routes: Application.router.toJson(),
      // routes: {
      //   '/login':(BuildContext context) =>new LoginPage()
      // },
      home: _buildHome(context),
    ),)
    ;
  }

子容器A接收并改变值

@override
  Widget build(BuildContext context) {
    // TODO: implement build
    // final IncrementBloc bloc = BlocProvider.of<IncrementBloc>(context);
    final UserBloc userBloc = BlocProvider.of<UserBloc>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('列表'),
      ),
      body: Column(
        children: <Widget>[
          StreamBuilder(
            stream: userBloc.outCounter,
            initialData: 0,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              return Center(
                child: Text('这是数据${snapshot.data}'),
              );
            },
          ),
          RaisedButton(
            onPressed: () => userBloc.actionSink.add(5),
          )
        ],
      ),
    );
  }

子容器B接收

@override
  Widget build(BuildContext context) {
    final UserBloc userBloc = BlocProvider.of<UserBloc>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('发圈'),
      ),
      body: Column(
      children: <Widget>[
        StreamBuilder(
          stream: userBloc.outCounter,
          initialData: 0,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            return Text('这是数据${snapshot.data}');
          },
        )
      ],
    ),
    );
  }
上一篇 下一篇

猜你喜欢

热点阅读