我创建了一个颤动的应用程序,我在应用程序管理todolist数组 . 我可以通过添加按钮添加文本 .
我创建了一个小部件以显示在列表中 . 我的问题是我应该如何管理个人的用户界面 .
码:
import 'package:flutter/material.dart';
class TodoList extends StatefulWidget {
_TodoListState createState() => new _TodoListState();
}
class _TodoListState extends State<TodoList> {
List _list = new List();
Widget listTile({String data: '[Empty data]'}) {
bool _writable = false;
TextEditingController _textController = new TextEditingController(text: data);
String _text = _textController.text;
if(!_writable){
return new Row(
children: <Widget>[
new Expanded(
child: new Text(data)
),
new IconButton(icon: new Icon(Icons.edit),
onPressed: () {
// setState(() {
_writable = ! _writable;
print(_writable.toString());
// });
}),
new IconButton(icon: new Icon(Icons.remove_circle), onPressed: null),
],
);
} else {
return new Row(
children: <Widget>[
new Expanded(
child: new TextField( controller: _textController )
),
new IconButton(icon: new Icon(Icons.done), onPressed: null),
],
);
}
}
void addInList(String string) {
print(string);
setState(() {
_list.add(string);
});
print(_list);
}
void removeFromList(int index){
}
static final TextEditingController _textController = new TextEditingController();
String get _text => _textController.text;
@override
Widget build(BuildContext context) {
Widget adderTile = new Row(
children: <Widget>[
new Expanded(
child:
new TextField(
textAlign: TextAlign.center,
controller: _textController ,
decoration: new InputDecoration( hintText: 'New item.!' ),
),
),
new IconButton(icon: new Icon(Icons.add), onPressed: (){addInList(_text);}),
],
);
return new MaterialApp(
title: 'TodoList',
home: new Scaffold(
appBar: new AppBar(title: new Text('TodoList'),),
body: new Column(
children: <Widget>[
adderTile,
new ListView.builder(
shrinkWrap: true,
itemCount: _list.length,
itemBuilder: (context, int index){
return listTile(data: _list[index]);
}
),
],
),
),
);
}
}
如果我在setState中更改_writable然后它重新呈现widget,_writable再次变为false . 如果我没有setState这样做,那么_writable变为true,但widget不会重新渲染 .
P.S . :我不想添加另一个数组来管理哪个是可写的,哪个不是 . 提前致谢 .
1 回答
变量
在方法
listTile()
中声明为局部变量,但应在List _list = new List();
旁边移动以成为成员变量 . 然后使用setState()
进行设置并重建视图 .Edit: 您应该创建一个专用的
StatefulWidget
(TodoListEntry
),其成员如上所述_writable
. 将listTile(...)
的整个方法体几乎移动到TodoListEntryState
的build()
-method,使参数String data
也成为成员并通过构造函数传递该值 .