我们创建了一个flutter应用程序,它从一系列项目中显示一个列表视图。我们希望能够根据用户的喜好来更新这些项目。就像如果您有一个待办事项清单,想要使用模态框或对话框来更正或更新列表中的某个项目。
我一直在尝试使用对话框更新列表视图中的单个项目,用户在对话框上键入后并在提交时关闭。到目前为止,我没有成功,但我感觉我离成功很近了。如何在提交时更新瓷砖上的名称并重新呈现页面?我缺少什么呢?
我一直在尝试使用对话框更新列表视图中的单个项目,用户在对话框上键入后并在提交时关闭。到目前为止,我没有成功,但我感觉我离成功很近了。如何在提交时更新瓷砖上的名称并重新呈现页面?我缺少什么呢?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Animal> animals = new List();
String newName;
TextEditingController nctrl = TextEditingController();
@override
void initState() {
super.initState();
animals = [
Animal(id: 1, name: 'cat'),
Animal(id: 2, name: 'dog'),
Animal(id: 3, name: 'mouse'),
Animal(id: 4, name: 'horse'),
Animal(id: 5, name: 'frog'),
];
}
_changePetName() {
newName = nctrl.text;
Navigator.pop(context);
return newName;
}
_showDialog(String name) {
nctrl.text = name;
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
elevation: 5,
backgroundColor: Colors.blue,
title: Text(
"Rename this pet",
),
content: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: nctrl,
onChanged: (e) {
setState(() {});
},
),
],
)),
actions: <Widget>[
// usually buttons at the bottom of the dialog
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
color: Colors.green,
child: Text(
"Submit",
),
onPressed: () {
var updateName = _changePetName();
return updateName;
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: animals.length,
itemBuilder: (BuildContext context, int index) {
var pet = animals[index];
return ListTile(
key: ValueKey(pet.id),
enabled: true,
onTap: () async {
var rename = await _showDialog(pet.name);
if (rename != null) {
pet.name = rename;
setState(() {});
}
// setState(() {
// pet.name = 'bob';
// });
},
title: Text(pet.name),
);
},
),
],
),
),
);
}
}
class Animal {
final int id;
String name;
Animal({this.id, this.name});
factory Animal.fromJson(Map<dynamic, dynamic> json) {
return new Animal(
id: json['id'],
name: json['name'],
);
}
Map<dynamic, dynamic> toJson() {
final Map<dynamic, dynamic> data = new Map<dynamic, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}