简体   繁体   English

StreamBuilder 可以在构建方法之外吗?

[英]Can a StreamBuilder be outside the build method?

I can't find any information on where the StreamBuilder needs to be within the code so I am asking here.我找不到任何关于 StreamBuilder 需要在代码中的位置的信息,所以我在这里问。

I have a screen in my flutter app that has a lot of input textfields.我的 flutter 应用程序中有一个屏幕,它有很多输入文本字段。 Each textfield has this code structure:每个文本字段都具有以下代码结构:

TextField(
                  keyboardType: TextInputType.text,
                  controller: clientLNameController,
                  textAlign: TextAlign.center,
                  onChanged: (value) {
                    trxnProvider.changeclientLName(value);
                  },
                  decoration: kTextFieldDecoration.copyWith(
                      hintText: 'Client Last Name',
                      labelText: 'Client Last Name'),
                ),

In the initState() function I call a method that pulls data from a Firestore collection and populates the TextEditingController associated with each textfield.在 initState() 函数中,我调用了一个方法,该方法从 Firestore 集合中提取数据并填充与每个文本字段关联的 TextEditingController。

@override
  void initState() {
    getTrxn();
  }

It is in this function that I try to get the data using a StreamBuilder.我正是在这个函数中尝试使用 StreamBuilder 获取数据。 Here is the code.这是代码。

getTrxn() async {
    StreamBuilder (
        stream: _db.collection('agency').doc(globals.agencyId).
        collection('trxns').doc(globals.currentTrxnId).snapshots(),
        builder: (BuildContext context, AsyncSnapshot trxnSnapshot) {
          if (trxnSnapshot.hasData) {
            clientFNameController.text = trxnSnapshot.data['clientFName'] ?? "";
          }
    )
    return SizedBox.shrink();
}

The problem I am having is when I run the code through the debugger and try to step through the code I get to the line StreamBuilder and then I am taken out of the function.我遇到的问题是当我通过调试器运行代码并尝试单步执行代码时,我到达了 StreamBuilder 行,然后我被带出了函数。 None of the code inside the StreamBuilder gets executed but there is no error either. StreamBuilder 中的任何代码都不会被执行,但也没有错误。

I am thinking that I can not use a StreamBuilder outside the "build" function.我想我不能在“构建”功能之外使用 StreamBuilder。

@override
  Widget build(BuildContext context) {

Is this correct or am I missing something else?这是正确的还是我错过了其他东西?

Do it like this像这样做

  late final StreamSubscription myStream;

  @override
  void initState() {
    myStream = _db
        .collection('agency')
        .doc(globals.agencyId)
        .snapshots()
        .listen((snapshot) => clientFNameController.text = snapshot.data()?['clientFName'] ?? "");
    super.initState();
  }

Make sure to dispose the stream once done确保在完成后处理流

  @override
  void dispose() {
    myStream.cancel();
    super.dispose();
  }

Throwaway expressions一次性表达

Let's suppose you have a Printer class, where you can display a message and do something whenever a message is displayed:假设您有一个Printer类,您可以在其中显示消息并在显示消息时执行某些操作:

class Printer {
  final void Function(String) callback;
  
  const Printer({required this.callback});
  
  void show(String message) {
    print(message);
    callback(message);
  }
}

Now, let's use it:现在,让我们使用它:

void main() {
  Printer(callback: (message) {
    print("Message $message was printed.");
  });
}

If you run this code, nothing will happen because you didn't call the show method.如果你运行这段代码,什么都不会发生,因为你没有调用show方法。 The above is an example of what I call throwaway expression , because nothing happens besides Dart creating an object and clearing it from memory.上面是一个我称之为一次性表达式的例子,因为除了 Dart 创建一个对象并从内存中清除它之外,没有其他任何事情发生。

The below snippet will work:以下代码段将起作用:

void main() {
  Printer(callback: (message) {
    print("Message '$message' was printed.");
  }).show("Hello, world!");
}

This will output这将输出

Hello, world!
Message 'Hello, world!' was printed.

The build method build方法

Generally, when you start a Flutter app by creating a MaterialApp , Flutter looks into its home argument (which is a Widget) and calls its build method.通常,当您通过创建MaterialApp启动 Flutter 应用程序时,Flutter 会查看其home参数(这是一个 Widget)并调用其build方法。 This widget will go through all its children declared inside its build method and will call their build methods.这个小部件将遍历在其build方法中声明的所有子项,并将调用它们的build方法。 This process repeats until there is no more children.这个过程重复,直到没有更多的孩子。

When a Widget's build method is called, some logic is executed.当调用 Widget 的build方法时,会执行一些逻辑。 Therefore, if you place a Widget A outside the build method, A's logic will not be executed (unless you explicitely call A's build method, but for this you will need a BuildContext ) and it'll be a throwaway expression .因此,如果您将 Widget A 放在build方法之外,A 的逻辑将不会被执行(除非您明确调用 A 的build方法,但为此您将需要一个BuildContext )并且它将是一个一次性表达式 So you're correct when you say所以你说的对

None of the code inside the StreamBuilder gets executed but there is no error either. StreamBuilder 中的任何代码都不会被执行,但也没有错误。

The solution解决方案

  1. Put your StreamBuilder inside your build method.将您的StreamBuilder放在您的build方法中。

  2. Use a StreamSubscription .使用StreamSubscription

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter BLoC:在 build() 方法中的 StreamBuilder 中的 Navigator.pop - Flutter BLoC: Navigator.pop in StreamBuilder in build() method 将方法移动到流构建器 - Move method to streambuilder 使用 StreamBuilder 为 CustomScrollView 构建 SliverList - Using a StreamBuilder to build a SliverList for a CustomScrollView 提供者:如何在 `StreamBuilder()` 中`notifyListener()`? 它会导致错误“setState() 或 markNeedsBuild() 在构建期间调用” - Provider: How can I `notifyListener()` within a `StreamBuilder()`? It causes the error `setState() or markNeedsBuild() called during build` Flutter:可以使用 StreamBuilder 检测 bool 变量发生的变化吗? 如果是,如何? 如果没有,我可以使用什么方法? - Flutter : Can use StreamBuilder to detect changes happens to a bool variable? If yes, how ? If no, what method can I use? StreamBuilder 可以返回列表吗<widget></widget> - Can a StreamBuilder return List<Widget> StreamBuilder 在构建时被多次调用 - StreamBuilder being called numerous times when in build Flutter:从构建方法外部访问Bloc数据 - Flutter: Accessing Bloc data from outside a build method 如何使用 FutureBuilder 在 Build 方法之外增加一个变量 - How to use FutureBuilder to increment a variable outside Build method Flutter:是否可以在构建方法之外的 Widget 实例变量中存储依赖项? - Flutter: Is it ok to store dependencies in Widget instance variables outside of the build method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM