Skip to content

ValueNotifier does not notify listeners when modifying a list #29958

@mikuhl-dev

Description

@mikuhl-dev
import 'dart:math';

import 'package:flutter/material.dart';

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

ValueNotifier<List<String>> numbers = ValueNotifier(['123']);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ValueListenableBuilder(
          valueListenable: numbers,
          builder: (BuildContext context, List<String> nums, Widget child) {
            return ListView.builder(
              itemCount: numbers.value.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(nums[index]),
                );
              },
            );
          },
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.star),
          onPressed: () {
            numbers.value.add(Random().nextInt(1000).toString());
          },
        ),
      ),
    );
  }
}

It looks like because the reference is the same, the notifiers are not called, for example, this works:

numbers.value = []..addAll(numbers.value)..add(Random().nextInt(1000).toString());

Metadata

Metadata

Assignees

Labels

P2Important issues not at the top of the work listd: api docsIssues with https://api.flutter.dev/frameworkflutter/packages/flutter repository. See also f: labels.r: fixedIssue is closed as already fixed in a newer version

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions