如何在 Flutter 的单独页面上将项目添加到列表中

How to add an item to a list on a separate page in Flutter

我是 Flutter 的新手,目前正在构建一个应用程序来记录因痉挛而发生的痉挛。这在结构上有点像 ToDo 风格的应用程序。所以我在我的 home.dart 文件中有一个列表,一个 ListViewBuilder 来显示我的 Spasm 对象。我想要做的是在 recordSpasm.dart 中创建一个 Spasm 对象并将其添加到 home.dart 中的列表中。我怎么做?我会 post 我的代码在这里:

home.dart

import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:spasmlogger/classses/spasm.dart';


class Home extends StatefulWidget {
  const Home({ Key? key }) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  List<Spasm> Spasms = [
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm"),
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm")
  ];
  
  

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SpasmLogger"),
        actions: <Widget>[
          IconButton(
            icon: Icon(MdiIcons.help),
            onPressed: () {
              Navigator.pushNamed(context, '/about');
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(MdiIcons.plus),
        onPressed: () {
          Navigator.pushNamed(context, "/recordSpasm");
        }
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        child: ListView.builder(
          itemCount: Spasms.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(Spasms[index].strength + " spasm detected in " + Spasms[index].bodyPart),
                subtitle: Text(Spasms[index].comment)
            )
            );
          },
        )
      ),
    );
  }
}

recordSpasm.dart

import 'package:flutter/material.dart';
import 'package:spasmlogger/classses/spasm.dart';


class RecordSpasm extends StatefulWidget {
  const RecordSpasm({ Key? key }) : super(key: key);

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

class _RecordSpasmState extends State<RecordSpasm> {
  @override

  String Strength = "Regular strength";
  List<String> Strengths = ["Regular strength", "Mildly stronger", "Severely Strong", "Extremely strong"];
  String BodyPart = "Lower body";
  List<String> BodyParts = ["Lower body", "Upper body", "Head"];
  TextEditingController comment = new TextEditingController();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Record spasm")
      
      ),
      body: 
      Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget> [
              Text("Spasm strength"),
              DropdownButton(
                value: Strength,
                items: Strengths.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
        );
      }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    Strength = value!;

                  });
                  
                },
                ),
                Text("Part of body"),
                DropdownButton(
                  value: BodyPart,
                  items: BodyParts.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                  );
                }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    BodyPart = value!;

                  });
                  
                },
                ),
                Text("Comments"),
                TextFormField(
                  maxLines: 5,
                  controller: comment,
                  
                ),
                ElevatedButton(
                  onPressed: () {
                    // Add object to the list in home.dart
                    print(Strength);
                    print(BodyPart);
                    print(comment.text);

                     

                  }, 
                  child: Text("Record spasm")
                  )


          ]
        )
      )
      )
    );
  }
}

首先您需要访问您的列表。你有 2 种方法可以做到这一点

  1. 像这样使列表静态化static List yourListName = [];
  2. 换句话说,您现在不需要做任何事情

因此,如果您使用方式 1,则可以像这样向列表中添加内容:

import 'thePathFromTheFileThatHaveTheListIn';

...

// here we add something to your list without building the whole class again
TheClassWhereTheListWasIn.yourListName.add(...);

如果您使用方式 2,则可以像这样向列表中添加内容:

import 'thePathFromTheFielThatHaveTheListIn';

...

// here we add something to your list but here we build the whole class again 
// and then add something to your list
TheClassWhereTheListIsIn().yourListName.add(...);

Navigator.push returns 弹出推送页面时的Future。所以你只需要在 recordSpasm.dart:

中添加 Spasm 对象
ElevatedButton(
    onPressed: () {
       Navigator.pop(context,Spasm(Strength, BodyPart, comment.text));
                   },
       child: Text("Record spasm")
              )

并检索对象并“刷新”home.dart

中的页面
floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.pushNamed(context, "/recordSpasm").then((value) {
              if (value != null && value is Spasm) {
                setState(() {
             // if this doesn't work add the value to the list then call setState
                  Spasms.add(value);
                });
              }
            });
          }),

提示,在 dart 中变量名应该是小写的(例如:字符串强度):)