gpt4 book ai didi

Flutter StreamBuilder在初始化时称为两次

转载 作者:行者123 更新时间:2023-12-03 02:41:43 25 4
gpt4 key购买 nike

StreamBuilder是否总是被调用两次?一次用于初始数据,然后一次用于输入流?

初始化以下StreamBuilder,显示build方法被调用两次。第二个通话是在第一个通话后的0.4秒。

流:内部版本1566239814897

流:内部版本1566239815284

import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:nocd/utils/bloc_provider.dart';

void main() =>
runApp(BlocProvider<MyAppBloc>(bloc: MyAppBloc(), child: MyApp()));

class MyAppBloc extends BlocBase {
String _page = window.defaultRouteName ?? "";

/// Stream for [getPage].
StreamController<String> pageController = StreamController<String>();

/// Observable navigation route value.
Stream get getPage => pageController.stream;

MyAppBloc() {}

@override
void dispose() {
pageController.close();
}
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyAppBloc myAppBloc = BlocProvider.of<MyAppBloc>(context);
return StreamBuilder(
stream: myAppBloc.getPage,
initialData: "Build",
builder: (context, snapshot) {
print("Stream: " +
snapshot.data +
DateTime.now().millisecondsSinceEpoch.toString());
return Container();
},
);
}
}

为什么StreamBuilder被调用两次?

最佳答案

Streambuilder将被调用2次,第一次是Initial,第二次是Stream。并且仅当状态为 ConnectionState.active时才更改数据。
请参见官方文档示例。

    StreamBuilder<int>(
//stream:fire, // a Stream<int> or null
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Select lot');
case ConnectionState.waiting:
return Text('Awaiting bids...');
case ConnectionState.active:
return Text('\$${snapshot.data}');
case ConnectionState.done:
return Text('\$${snapshot.data} (closed)');
}
return null; // unreachable
},
);

StreamBuilder documentation

The initial snapshot data can be controlled by specifying initialData. This should be used to ensure that the first frame has the expected value, as the builder will always be called before the stream listener has a chance to be processed.



initialData

Providing this value (presumably obtained synchronously somehow when the Stream was created) ensures that the first frame will show useful data. Otherwise, the first frame will be built with the value null, regardless of whether a value is available on the stream: since streams are asynchronous, no events from the stream can be obtained before the initial build.

关于Flutter StreamBuilder在初始化时称为两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57562407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com