Редактировать элемент списка при редактировании Нажмите, используя диалог - PullRequest
0 голосов
/ 08 апреля 2020

Я хочу редактировать элемент при нажатии кнопки «Редактировать». Когда пользователь нажимает на кнопку редактирования, я хочу, чтобы появилось диалоговое окно с TextField, чтобы пользователь мог ввести в него текст и заменить его на введенный текст. Я пытался, но я не могу найти какие-либо решения. Пожалуйста, помогите мне с этим. Я приложил скриншот моего макета, а также опубликовал некоторый код.

enter image description here

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(
    items: List<String>.generate(100, (i) => "List item $i"),
  ));
}

Future<String> _asyncInputDialog(BuildContext context) async {
  String sampleText = '';
  return showDialog<String>(
    context: context,
    barrierDismissible:
    false, // dialog is dismissible with a tap on the barrier
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Enter Text'),
        content: new Row(
          children: <Widget>[
            new Expanded(
                child: new TextField(
                  autofocus: true,
                  decoration: new InputDecoration(
                      labelText: 'Text Here', hintText: 'eg. ABCD'),
                  onChanged: (value) {
                    sampleText = value;
                  },
                ))
          ],
        ),
        actions: <Widget>[
          FlatButton(
            child: Text('Ok'),
            onPressed: () {
              Navigator.of(context).pop(sampleText);
            },
          ),
        ],
      );
    },
  );
}

class MyApp extends StatefulWidget {
  final List<String> items;

  MyApp({Key key, @required this.items}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    final title = 'Long List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView.builder(
          itemCount: widget.items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text('${widget.items[index]}'),
              trailing: RaisedButton(
                child: Text('Edit'),
                color: Colors.pinkAccent,
                onPressed: () async {
                  final String newText = await _asyncInputDialog(context);
                  setState(() {

                  });
                  Scaffold.of(context).showSnackBar(new SnackBar(content: new Text("$newText"),));
                },
              ),
            );
          },
        ),
      ),
    );
  }
}

1 Ответ

1 голос
/ 08 апреля 2020

В вашем ListTile положите items[index] = newText; в setState((){});, чтобы я выглядел следующим образом.

ListTile(
              title: Text('${items[index]}'),
              trailing: RaisedButton(
                child: Text('Edit'),
                color: Colors.pinkAccent,
                onPressed: () async {
                  final String newText = await _asyncInputDialog(context);
                  setState(() {
                    items[index] = newText;
                  });
                  Scaffold.of(context).showSnackBar(new SnackBar(
                    content: new Text("$newText"),
                  ));
                },
              ),
            );
...