Home > Blockchain >  how to display the value that came from valueNotifier?
how to display the value that came from valueNotifier?

Time:05-11

I have a valueNotifier that generates a list of events and takes a random string every 5 seconds and sends it to the screen. It lies in inheritedWidget. How can I display in the ListView the event that came with the valueNotifier? What is the correct way to print the answer? My code:

class EventList extends StatelessWidget {
  const EventList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return EventInherited(
      child: EventListScreen(),
    );
  }
}

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

  @override
  State<EventListScreen> createState() => _EventListScreenState();
}

class _EventListScreenState extends State<EventListScreen> {
  @override
  Widget build(BuildContext context) {
    final eventNotifier = EventInherited.of(context).eventNotifier;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Event List'),
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(30),
        child: ValueListenableBuilder(
          valueListenable: eventNotifier,
          builder: (BuildContext context, List<String> value, Widget? child) {
            return ListView(
              children: [
                
              ],
            );
          },
        ),
      ),
    );
  }
}

class EventNotifier extends ValueNotifier<List<String>> {
  EventNotifier(List<String> value) : super(value);
  final List<String> events = ['add', 'delete', 'edit'];
  final stream = Stream.periodic(const Duration(seconds: 5));
  late final streamSub = stream.listen((event) {
    value.add(
      events[Random().nextInt(4)],
    );
  });
}

class EventInherited extends InheritedWidget {
  final EventNotifier eventNotifier = EventNotifier([]);

  EventInherited({required Widget child}) : super(child: child);

  static EventInherited of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType()!;
  }

  @override
  bool updateShouldNotify(EventInherited oldWidget) {
    return oldWidget.eventNotifier.streamSub != eventNotifier.streamSub;
  }
}

CodePudding user response:

If you have correct value, you can return listview like this:

return ListView.builder(
  itemCount: value.length,
  itemBuilder: (context, index) {
    return Text(value[index]);
  },
);

CodePudding user response:

After having a quick look at ValueNotifier,

It says the following:

When the value is replaced with something that is not equal to the old value as evaluated by the equality operator ==, this class notifies its listeners.

In your case, the value is an array. By adding items to the array, it wont recognise a change. Also see other Stacko post.

Try something like:

value = [...value].add(...)
  • Related