'my list in flutter is not updating the problem in my code

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 :)



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aedemirsen