Как добавить элемент в уже существующий список из другого класса? - PullRequest
0 голосов
/ 23 октября 2019

Я хочу создать приложение со списком задач с флаттером, но у меня возникают проблемы с сохранением ввода текста в список, уже созданный в другом отображаемом классе.

Я попытался создать объектв другом классе с установщиком, но поскольку я использую виджет с сохранением состояния, это не сработает, особенно потому, что я использую Lists () (представление списка) в теле скаффолда для отображения элементов списка

это мой класс просмотра списка

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

class TodoListS extends StatefulWidget {
  @override
  TodoList createState() => TodoList();
}
 class TodoList extends State<TodoListS> {
   List<Todo> todos = [Todo(title:'Checktheicon'), Todo(title: 'help me')];
   void setTodo(Todo todo)
   {
     todos.add(todo);
   }
      @override
      Widget build(BuildContext context) {

        return myListView(context,todos );
      }
    }

Widget myListView(BuildContext context, List<Todo> todos) {

      // backing data

      return ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(todos[index].title),
            leading: Icon(todos[index].icons),
          );
        },
      );

    }

Здесь я отображаю список

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          backgroundColor: Colors.pink[100], title: new Text('Todo List')),
      body: TodoListS(),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add), onPressed: () =>  _displayDialog(context)),
    );
  }

Здесь я хочу получить ввод текста и сохранить его

_displayDialog(BuildContext context) {
      return showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('Insert Your to do'),
              content: TextField(
                controller: _textFieldController,
                decoration: InputDecoration(hintText: "ie. Wash dishes"),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('CANCEL'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                new FlatButton(
                  child: new Text('ADD'),
                  onPressed: () {
                  var todo = new Todo(title: _textFieldController.value.text);
                  todol.setTodo(todo);
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          });
    }

Итак, сейчас ничего не сохраняется, отображается только моя ранее созданная задача, мой текстовый ввод необходимо добавить в список, чтобы его можно было отобразить.

Ответы [ 2 ]

1 голос
/ 23 октября 2019

Чтобы вызвать функцию из другого класса, вы можете использовать GlobalKey

Шаг 1: определить final GlobalKey<TodoList> _key = GlobalKey();
Шаг 2: В onPressed использовать _key.currentState.setTodo(Todo(title: _textFieldController.text));
Шаг 3: Добавить ключ к классу

class TodoListS extends StatefulWidget {
  TodoListS({Key key}) : super(key: key);

Шаг 4: Ключ доступа TodoListS

body: TodoListS(
        key: _key,
      ),

полный рабочий код

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  final _textFieldController = TextEditingController();
  final GlobalKey<TodoList> _key = GlobalKey();

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.
    _textFieldController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          AppBar(backgroundColor: Colors.pink[100], title: Text('Todo List')),
      body: TodoListS(
        key: _key,
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add), onPressed: () => _displayDialog(context)),
    );
  }

  _displayDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Insert Your to do'),
            content: TextField(
              controller: _textFieldController,
              decoration: InputDecoration(hintText: "ie. Wash dishes"),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('CANCEL'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('ADD'),
                onPressed: () {
                  /*var todo =  Todo(title: _textFieldController.value.text);
                  todol.setTodo(todo);*/

                  _key.currentState
                      .setTodo(Todo(title: _textFieldController.text));
                  setState(() {

                  });
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }
}

class Todo {
  String title;

  Todo({
    this.title,
  });

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
        title: json["title"] == null ? null : json["title"],
      );

  Map<String, dynamic> toJson() => {
        "title": title == null ? null : title,
      };
}

class TodoListS extends StatefulWidget {
  TodoListS({Key key}) : super(key: key);
  @override
  TodoList createState() => TodoList();
}

class TodoList extends State<TodoListS> {
  List<Todo> todos = [Todo(title: 'Checktheicon'), Todo(title: 'help me')];

  void setTodo(Todo todo) {
    todos.add(todo);
  }

  @override
  Widget build(BuildContext context) {
    return myListView(context, todos);
  }
}

Widget myListView(BuildContext context, List<Todo> todos) {
  // backing data
  return ListView.builder(
    itemCount: todos.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text(todos[index].title),
        //leading: Icon(todos[index].icons),
      );
    },
  );
}

полная рабочая демонстрация

enter image description here

0 голосов
/ 23 октября 2019

Здесь вам нужно использовать провайдера для вашего приложения, который сохраняет состояние вашего приложения для вас.

  • В провайдере вы можете сохранить класс, который содержит методы для обновления, и вставить TODO.

  • Я привел для вас несколько базовых примеров, с которых вы можете начать. И некоторые ссылки.

  • основной виджет

import 'package:provider/provider.dart';

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]);
    Provider.debugCheckInvalidValueType = null;

    return app();
  }
}


Widget app() {
  Controller controller = new Controller();
  return ChangeNotifierProvider(
    builder: (context) => controller,
    child: MaterialApp(
      routes: {
        controller.UnitConverter: (context) =>
            Page(
              title: "title",
              controller: Provider.of<Controller>(context),
            ),
         },
      ),
    );
 }
  • pubspec.yaml
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  provider: ^3.1.0
  • Теперь получаем контроллер
  Page({Key key, this.title, this.controller})
      : super(key: key);
  final String title;
  final Controller controller;

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

class PageState extends State<Page> {
  @override
  Widget build(BuildContext context) { return Container(); }
}
  • В контроллере
 class Controller extends ChangeNotifier {

   List<Todo> todos = List();
   List<Todo> getList(){
      return todo;
   }
   void updateList(List<Todo> todos){
     this.todos = todos;
   }
}
  • ссылки

провайдер & Состояние виджета

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...