oleM
oleM

Reputation: 25

List for a class clears out after making new widget

Im trying to learn flutter, but i have stumbled upon a problem i can't solve. I have a class MyApp/MyAppState that has a list of widgets (ovelser), that is used in a listVeiw.builder.


import './barbutton.dart';

import './ovelser.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

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

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  List<Widget> ovelser = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("progresjon"),
        backgroundColor: Colors.blue,
        actions: <Widget>[AddButton(nameOvelse)],
      ),
      body: ListView.builder(
        itemCount: ovelser.length,
        itemBuilder: (context, index) {
          final Widget ovelse = ovelser[index]; // lagrer bare ovelse objektet
          return Dismissible(
            // dismissible gjør det mulig å slette ting i listView
            key: UniqueKey(),
            onDismissed: (direction) {
              //hva som skjer når man skal slette
              setState(() {
                ovelser.removeAt(index);
              });
            },
            background: Container(
              color: Colors.red,
            ),
            //child er hva som skal være objektet som kan slettes
            child: ovelse,
          );
        },
      ),
    );
  }

  void addOvelse(String name) {
    setState(() {
      ovelser.add(Ovelser(name));
    });
    print(ovelser.length);
  }

  nameOvelse(BuildContext context) {
    TextEditingController custumcontroller = TextEditingController();
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("new activity"),
          content: TextField(
            controller: custumcontroller,
          ),
          actions: <Widget>[
            FlatButton(
              child: Text("create"),
              onPressed: () {
                String activityName = "  " + custumcontroller.text;
                addOvelse(activityName);
                Navigator.of(context).pop();
              },
            )
          ],
        );
      },
    );
  }
}

the list ovelser takes in Ovelser objects. these objects have a class that has a list that takes in integers (progresjonsList) that i can add to via an AlertDialog. Code for the class with progresjonList in int:


import './ovleseraddbutton.dart';

class Ovelser extends StatefulWidget {
  final String name;

  Ovelser(this.name);

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

class OvelserState extends State<Ovelser> {
  List<int> progresjonList = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          border: Border(
        top: BorderSide(width: 0.5, color: Colors.grey),
        bottom: BorderSide(width: 0.5, color: Colors.grey),
      )),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Flexible(
                child: Container(
              child: Text(widget.name,
                  overflow: TextOverflow.fade,
                  softWrap: false,
                  maxLines: 1,
                  style: TextStyle(
                      fontStyle: FontStyle.italic,
                      fontSize: 20,
                      fontWeight: FontWeight.bold)),
            )),
            OvelserAddbutton(addvalue)
          ]),
    );
  }

  void insertValue(int value) {
    setState(() {
      this.progresjonList.add(value);
    });
  }

  addvalue(BuildContext context) {
    TextEditingController custumcontroller = TextEditingController();
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("add new value"),
          content: TextField(
            controller: custumcontroller,
            keyboardType: TextInputType.number,
          ),
          actions: <Widget>[
            FlatButton(
              child: Text("add"),
              onPressed: () {
                String stringnumber = custumcontroller.text;
                int number = int.parse(stringnumber);
                insertValue(number);
                print(number);
                print(progresjonList.length);
                print(this.progresjonList);
                Navigator.of(context).pop();
              },
            )
          ],
        );
      },
    );
  }
}

the problem is every time i create a new widget in ovelser (the list that is used in ListView) the lists with integers (progresjonList) clears out so they are empty and dont retain the values previously added by the AlertDialog. I dont understand how i can keep that from happening, so that i keep the integers added. Can anyone help me? thank you in advance:)

there are tow other small files that only have icon widgets in them that i dont think are the problem, but if you need them here they are:)


class AddButton extends StatelessWidget {
  final Function setInFunction;

  AddButton(this.setInFunction);

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.add),
      onPressed: () => setInFunction(context),
    );
  }
}
import 'package:flutter/material.dart';

class OvelserAddbutton extends StatelessWidget {
  final Function setInFunction;

  OvelserAddbutton(this.setInFunction);

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.add),
      onPressed: () => setInFunction(context),
    );
  }
}
```

Upvotes: 1

Views: 25

Answers (1)

returnVoid
returnVoid

Reputation: 644

progessjonList is local to Ovelser class. You need to pass overserList to Ovelser class.

class Ovelser extends StatefulWidget {
  final String name;
  final List<int> list;

  Ovelser(this.name, this.list);

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

Then when you want to add to the list in OvelserState just use

widget.list.add(/*add int here*/);

Which I see is in your insertValue function

void insertValue(int value) {
  setState(() {
    widget.list.add(value);
  });
}

The list you pass in will be a reference to the ovelser list from the original class.

Upvotes: 1

Related Questions