我尝试创建一个基本的笔记应用程序来研究颤动,但我不太了解如何通知NotesContainer
该按钮已被按下。我试图为其创建一个引用,但是添加函数在状态类中,我不确定该如何到达。
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final NotesContainer Notes = new NotesContainer();
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('My Notes'),
backgroundColor: Color.fromRGBO(223, 175, 117, 1),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: (){
Notes.add()
},
)
],
),
body: Notes
);
}
}
class NoteData{
String title;
String content;
NoteData(this.title, this.content);
NoteData.noContent(t){
title = t;
content ='';
}
}
class NotesContainer extends StatefulWidget{
@override
State<StatefulWidget> createState(){
return new _NotesContainer();
}
}
class _NotesContainer extends State<NotesContainer>{
final _notes = <NoteData>[new NoteData('title','thing to do'), new NoteData('title2','thing to do2')];
void add({String title='1'}){ //just to test adding
setState(() {
_notes.add(new NoteData.noContent(title));
});
}
Widget build(BuildContext context){
return _buildNotesContainer();
}
_buildNotesContainer(){
return new ListView.separated(
itemCount: _notes.length,
separatorBuilder: (BuildContext context, int index) => Divider(),
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_notes[index].title),
);
},
padding: const EdgeInsets.all(10.0),
);
}
}
我想解决方案是通过有状态的_NotesContainer
类在NotesContainer
中公开_function。我想知道是否有更优雅的解决方案。
谢谢,或者
答案 0 :(得分:1)
我认为委派在小部件树中进一步添加元素的责任更有意义。我修改了您的代码以显示其工作原理。
但是,如果最终得到一棵深的窗口小部件树,而子窗口小部件需要_notes列表,那么我建议您研究使用继承的窗口小部件并向其中添加_notes列表,这样就可以在不传递声明太多。
import 'package:flutter/material.dart';
// Note the name change
class NotesPage extends StatefulWidget {
@override
_NotesPageState createState() => _NotesPageState();
}
class _NotesPageState extends State<NotesPage> {
final List<NoteData> _notes = <NoteData>[NoteData('title','thing to do'), NoteData('title2','thing to do2')];
void add({String title='1'}){ //just to test adding
setState(() {
_notes.add(NoteData.noContent(title));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('My Notes'),
backgroundColor: Color.fromRGBO(223, 175, 117, 1),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: (){
add();
},
)
],
),
body: NotesContainer(notes: _notes)
);
}
}
class NoteData{
String title;
String content;
NoteData(this.title, this.content);
NoteData.noContent(t){
title = t;
content ='';
}
}
class NotesContainer extends StatelessWidget{
final List<NoteData> notes;
const NotesContainer({Key key, this.notes}) : super(key: key);
@override
Widget build(BuildContext context){
return ListView.separated(
itemCount: notes.length,
separatorBuilder: (BuildContext context, int index) => Divider(),
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(notes[index].title),
);
},
padding: const EdgeInsets.all(10.0),
);
}
}
希望它会有所帮助:-)