使用showdialog和textfield更新Flutter中的单个Listview项目

时间:2019-12-18 04:12:54

标签: listview flutter mobile dart uitextfield

我们创建了一个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;
  }
}

3 个答案:

答案 0 :(得分:1)

尝试一下

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'),
    ];
  }

  _showDialog(int index) {
    nctrl.text = animals[index].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: () {
                  setState(() {
                    animals[index].name = nctrl.text;
                  });
                  Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  @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(index);

                    if (rename != null) {
                      animals[index].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;
  }
} 

答案 1 :(得分:0)

在“警报的Onpress方法”对话框中,只需粘贴此代码

Navigator.pushReplacement(
  context,
  MaterialPageRoute(builder: (_) => MyHomePage()));

它会将您的页面导航到相同的页面。

答案 2 :(得分:0)

很少有会使您的代码正常工作的更正:

  1. 显示对话框应为String类型,以便其返回的结果为String类型。
  2. 在弹出对话框时,您必须在pop()中传递数据。
  3. 等待showDialog方法接收其结果。

以下是工作代码供您参考:

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, newName);
    return newName;
  }

  Future<String> _showDialog(String name) async {
    nctrl.text = name;
    return await showDialog<String>(
      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(nctrl.text);
              },
            ),
            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;
  }
}

如果该解决方案适合您,请接受并投票给答案。