sqlite - 当按下发送按钮时,想要在屏幕上的文本字段中显示带有文本的卡片列表
问题描述
我想展示一张卡片,里面有文字。文本值来自 TextField 输入,只要按下按钮,它就会立即在新卡片上显示值。
我创建了两个单独的文件: notestream.dart显示卡片,notetextfield.dart将值发送到数据库
notetextfield.dart
文本域
TextField(
controller: _textEditingController,
textInputAction: TextInputAction.newline,
onChanged: (value) {
messageText = value;
noteText = value;
},
......
......
),
按下
IconButton(
onPressed: () {
_textEditingController.clear();
/Implement send functionality.
final newNote = Note(noteText: noteText);
if (newNote.noteText.isNotEmpty) {
/*Create new Note object and make sure
the Note textis not empty,
because what's the point of saving empty
Note
*/
noteBloc.addNote(newNote);
noteBloc.getNotes();
}
},
notestream.dart
卡片将在包含卡片代码的单独文件的帮助下生成。
final NoteBloc noteBloc = NoteBloc();
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: noteBloc.notes,
builder: (
BuildContext context,
AsyncSnapshot<List<Note>>snapshot
) {
if (snapshot.hasData) {
/*Also handles whenever there's stream
but returned returned 0 records of Note from DB.
If that the case show user that you have empty Notes
*/
return snapshot.data.length != 0
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, itemPosition) {
Note note = snapshot.data[itemPosition];
return NoteCard(
noteText: note.noteText,
noteImagePath: note.noteImagePath,
);
})
块飞镖
class NoteBloc {
//Get instance of the Repository
final _noteRepository = NoteRepository();
final _noteController = StreamController<List<Note>>.broadcast();
get notes => _noteController.stream;
NoteBloc() {
getNotes();
}
getNotes({String query}) async {
//sink is a way of adding data reactively to the stream
//by registering a new event
_noteController.sink.add(await _noteRepository.getAllNotes(query:
query));
}
addNote(Note note) async {
await _noteRepository.insertNote(note);
getNotes();
}
updateTodo(Note note) async {
await _noteRepository.updateNote(note);
getNotes();
}
dispose() {
_noteController.close();
}
}
每当我按下notetextfield.dart文件中的 onPressed 按钮时,卡片列表都不会显示在屏幕上。
解决方案
看起来您NoteBloc
在每个文件上使用了不同的实例,您应该有一个单一的事实来源。
尝试使用提供程序库在父级上提供实例并在其子级上使用它。
你会像这样在父 Widget 上提供 bloc
Provider<NoteBloc>(
builder: (context) => NoteBloc(noteRepository: NoteRepository()),
dispose: (context, value) => value.dispose()
child: ParentWidget(),
)
你可以在任何这样的孩子身上食用它
final bloc = Provider.of<NoteBloc>(BuildContext context)
或者如果您更喜欢包装 Widget
Consumer<NoteBloc>(
builder: (context, bloc, _) => ChildWidget()
推荐阅读
- flutter - 如何使用“未来”的实例
' 作为 json(地图) - javascript - Javascript在里面创建带有var的DIV
- reactjs - 如何使用样式化组件在 reactjs 中设置 svg 样式
- visual-studio-code - Ctrl + k ctrl + f 在 vscode 上无法正常工作
- powerbi - 适用于多条线路的 Power BI SUMIF
- sql-server - 将整数(来自其他表的“多少年”)添加到日期列(日期)
- r - 尝试使用 SVM 预测值时测试数据集中缺少值 - 如何估算?
- java - 在 REST Controller java 中创建多个线程的影响
- javascript - JavaScript 中“const”关键字的范围
- python - python list:保持唯一值