radio-button - 尝试在 Flutter 中使用 Streambuilder 和 Bloc 制作单选按钮。但不工作
问题描述
我尝试使用 Streambuilder 和 Bloc 制作单选按钮。
所以我制作了流控制器,当单击单选按钮时,
我实现了 streamcontrl.add(value),但 Streambuilder 不听
那个流。我测试了收音机的 onchanged 值。和
请弄清楚它有什么问题。
这是完整的代码。
import 'package:flutter/material.dart';
import 'dart:async';
void main(){
runApp(new MaterialApp(
home: new MyApp(),
));
}
class bloc {
StreamController <int> ctrl = StreamController() ;
get blocvalue => ctrl.stream;
void setvalue (value ) {
ctrl.sink.add(value) ; }
}
class MyApp extends StatefulWidget {
@override
_State createState() => new _State();
}
class _State extends State<MyApp>{
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Name here'),
),
body: new Container(
padding: new EdgeInsets.all(15.0),
child: new Center(
child: new Column(
children: <Widget>[
StreamBuilder(
stream: bloc().blocvalue,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot <int> snapshot)
{
List<Widget> list = new List<Widget>();
for(int i = 0; i < 3; i++){
list.add(new RadioListTile(
value: i,
groupValue: snapshot.data,
onChanged: bloc().setvalue,
activeColor: Colors.green,
controlAffinity: ListTileControlAffinity.trailing,
title: new Text('Item: ${i}'),
dense: true,
// subtitle: new Text('sub title'),
));
}
return Column(children: list,); })
],
),
),
),
);
}
}
解决方案
正如评论中的 pksink 所提到的,您正在通过在 StreamBuilder 中将其设置为bloc().blocValue
. 您可以在此处将其final myBloc = bloc();
声明bloc
为myBloc.blocValue
. 这样,每次重建 Widget 构建时都不会创建一个新的 bloc 实例。
推荐阅读
- c - 在 C 中实现 malloc() 时,每个块上的页脚的目的是什么?
- powerbi - 尝试使用 Dax 将当前销售额与 MTD 销售额进行比较
- python - 在字符串中嵌入值时,Python 中的 %s 和 % 有什么区别?
- swift - 如何从组合的 iOS/Watch Xcode 项目中仅将独立的 Apple Watch 应用程序发布到 App Store
- reactjs - 带有 Firebase 托管的 Github CI 上 React 应用程序的绝对路径
- python - Dnspython 无法解决任何问题
- python - 使用open cv在python中画一个圆圈但不了解机制
- time-complexity - 两个数字相乘的时间复杂度
- java - 为什么 Java 使用 -> 而不是 => 来表示 lambda 函数?
- objective-c - 在 Objective C 中启动 NSColorPanel