【问题标题】:get data by string with bloc in flutter在颤动中通过字符串获取数据
【发布时间】:2020-08-14 03:13:42
【问题描述】:

我是 Flutter 的新手。我需要帮助。 我有服务。我通过从 Ui 传递的字符串搜索数据。

Future<List<MyEntity>> getByString(String s) async {
    final CollectionReference _dbs = Firestore.instance.collection(_baseUrl);
    QuerySnapshot query =
        await _dbs.where("string", isEqualTo: s).getDocuments();
    List<MyEntity> products = query.documents
        .map((doc) => MyEntity.fromSnapshotJson(doc))
        .toList();
    return products;
  }

我有 bloc。我不知道如何将字符串从 Ui 传递给 sink?

class MyBloc extends BlocBase {

  final MyService _productService;

  MyBloc(this._productService) {
    listEvent.add(await _productService.getByString(// i should pass string from Ui));
  }

  final BehaviorSubject<List<MyEntity>> _controller =
      new BehaviorSubject<List<MovieEntity>>.seeded(List<MyEntity>());

  Observable<List<MovieEntity>> get listFlux => _controller.stream;
  Sink<List<MovieEntity>> get listEvent => _controller.sink;

  @override
  void dispose() {
    _controller?.close();
    super.dispose();
  }
}

在 bloc 构造函数中初始化服务是个好主意吗?你能给我同样的建议吗?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore bloc


    【解决方案1】:

    如果你想要块的接收器,你需要在你的服务类中创建一个块的实例,并在那里在接收器中添加值。 因此,例如,你有你的服务类而不是在初始化状态下实例化块,并记得在 dispose() 中关闭它,如下所示:

    class Service extends StatefullWidget{
    @override
      _ServiceState createState() => _ServiceState();
    }
    
    class _ServiceState extends State<Service> {
      MyBloc _myBloc;
    
      @override
      void initState() {
        _myBloc = MyBloc();
        super.initState();
      }
    
     @override
      void dispose() {
        _myBloc?.close();
        super.dispose();
      }
    
    Future<List<MyEntity>> getByString(String s) async {
        final CollectionReference _dbs = Firestore.instance.collection(_baseUrl);
        QuerySnapshot query =
            await _dbs.where("string", isEqualTo: s).getDocuments();
        List<MyEntity> products = query.documents
            .map((doc) => MyEntity.fromSnapshotJson(doc))
            .toList();
        return products;
      }
    

    现在在服务类中,只要你想传递字符串就调用

    List<MyEntity> products = await getByString("search string");
    _myBloc.listEvent.add(products);
    

    只需修改您的 MyBloc 代码,因为它不需要在其构造函数中提供服务,例如:

    class MyBloc extends BlocBase {
    
      final BehaviorSubject<List<MyEntity>> _controller =
          new BehaviorSubject<List<MovieEntity>>.seeded(List<MyEntity>());
    
      Observable<List<MovieEntity>> get listFlux => _controller.stream;
      Sink<List<MovieEntity>> get listEvent => _controller.sink;
    
      @override
      void dispose() {
        _controller?.close();
        super.dispose();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多