0

hello I'm trying to update a list from another file and I imported it with its function but for some reason, it's not correct I'll show you the code

import 'package:flutter/material.dart';

class Data {
  List<String> list = [
    '0',
    '1','3',
  ];

  void add(String name){
    list.add(name);
    print('should work');
  }
}

that was the class it's is in a separate file I named it data.dart and in the main fail there's an import for if

import 'package:flutter/material.dart';

import './data.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var list = Data().list;

  // List<String> newlist = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          body: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  itemCount: list.length,
                  itemBuilder: (ctx, index){
                    return Text(list[index]);
                  },
                ),
              ),
              TextButton(onPressed: () => setState(() {
                Data().list.add('new');
              }), child: Text('add'))
            ],
          ),
        ));
  }
}

now there is no response for the function it's getting triggered but not update the list please help me :)

1 Answers1

0

You should use static field in your case. I am not sure what you are trying to achieve and its truth, but change your code with this:

class Data {
  static List<String> list = [
    '0',
    '1','3',
  ];

  static void add(String name){
    list.add(name);
    print('should work');
  }
}

//in build method
TextButton(
    onPressed: () => setState(() {
        Data.list.add('new');
    }),
),

In addition, you dont need to use setState method, because you are not updating any widget in widget tree. You just change the value of a static field. In this case you also dont need add() method.

aedemirsen
  • 92
  • 1
  • 10
  • I've added a static word as you mentioned but I got error from "list.add" that says Instance members can't be accessed from static method, also I am trying to update the widget on the main by using a listview that depends on that list I hope it's clear now and thank you :) – realhassan97 Apr 21 '22 at 18:04
  • Just remove the add method in Data class. You dont need that. When you add something to the list. Just do Data.list.add('some string'); – aedemirsen Apr 21 '22 at 18:33
  • it's working :) i did just as you told me remove the method and use it with a static word before the list – realhassan97 Apr 21 '22 at 19:17