【发布时间】:2021-05-21 12:59:28
【问题描述】:
我有一个流,它提供键入为“客户端”的项目列表。我也有一个搜索栏,用户写一些名字,列表应该过滤搜索结果,当点击其他名为“清除”的按钮时,它应该将列表重置为默认值。所以,我写了这些方法:
//called when tap search button (if it has a text typed)
void setSearch(String search) {
_search = search;
_streamController.add(null);//the error throws here
load(clean: true);
}
//called when tap 'clear' button
void clearSearch() {
_search = '';
_offset = 1;
_clients.clear();
_streamController.stream.drain();
_streamController.add(null); //the error throws here
load(clean: true);
}
但是当我点击搜索或清除时,它会抛出这个错误:
接收者:空。 NoSuchMethodError:在 null 上调用了方法“map”。尝试调用:map(Closure: (Map
) => Client)
我该如何处理?还有另一种清理流的方法吗?如果您需要更多代码,我可以更新问题
更新 这是我的构建方法
Scaffold(
appBar: appBar(),
body: Column(
children: [
Container(
padding: EdgeInsets.all(5.0),
width: MediaQuery.of(context).size.width,
height: 60.0,
child: Card(
elevation: 3,
child: Container(
child: TextField(
style: TextStyle(
color: AppColorSecondary,
),
cursorColor: Theme.of(context).primaryColor,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search, color: AppColorSecondary,),
hintStyle: TextStyle(color: AppColorSecondary),
filled: true,
fillColor: AppColorPrimary,
border: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
suffixIcon: GestureDetector(
onTap: (){
searchController.clear();
clientsController.loadMore();
},
child: FittedBox(
alignment: Alignment.center,
fit: BoxFit.fitHeight,
child: IconTheme(
data: IconThemeData(),
child: Icon(
Icons.clear,
color: Colors.black,
),
),
),
),
),
controller: searchController,
onSubmitted: (value) {
clientsController.setSearch(searchController.text);
},
),
),
),
),
Expanded(
child: StreamBuilder(
stream: clientsController.stream,
builder: (ctx, snapshot) {
if (snapshot.error != null) {
print(snapshot.error.toString());
return Center(
child: Text(snapshot.error.toString()),
);
} else if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.data.length == 0) {
return Center(
child: Text('0clients'),
);
} else {
return RefreshIndicator(
onRefresh: clientsController.refresh,
child: ListView.builder(
controller: scrollController,
itemCount: snapshot.data.length + 1,
itemBuilder: (ctx, i) {
if (i < snapshot.data.length) {
return ClientsWidget(snapshot.data[i]);
} else if (clientsController.hasMore) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 32.0),
child: Center(child: CircularProgressIndicator()),
);
} else {
return SizedBox(
height: 30,
);
}
},
),
);
}
},
),
)
],
),
);
}
【问题讨论】:
-
也许你可以给你的streamController添加一个事件?在那里您可以将搜索设置为清除。也许做一个内联 if 语句,你有地图来显示一个空的占位符
-
你能用一个例子写一个答案吗?我没有正确理解
-
我现在知道我错了,对不起。我习惯于 bloc 并且处理不同的 .add 函数。但是您不能将搜索设置为默认值吗?所以给流默认而不是null?
-
如果有办法我不知道
-
如何处理来自流的数据?