首页 > 解决方案 > 尝试在 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,); })
         ],
        ),
      ),
     ),
    );
   }
   }

标签: radio-buttonflutter

解决方案


正如评论中的 pksink 所提到的,您正在通过在 StreamBuilder 中将其设置为bloc().blocValue. 您可以在此处将其final myBloc = bloc();声明blocmyBloc.blocValue. 这样,每次重建 Widget 构建时都不会创建一个新的 bloc 实例。


推荐阅读