user10053723
user10053723

Reputation:

notify child that somewhere in parent onTap happened

could you please show me how can I notify my statefull child widget that somewhere in parent user clicks on button?

I have two separate .dart files

in the first file I described main screen widget with FAB
and in the second one I have ListWidget (like RecyclerView)

If user tap on FAB I want notify my ListWidget about it so it can e.g. add one more item.

I have java/android background but it's quite hard for me to change my mind flow.

Upvotes: 1

Views: 3010

Answers (1)

chemamolins
chemamolins

Reputation: 20558

The first option would be to build the child widget each time you add an item to the list, passing the list as a parameter to the child.

But using streams is a nice way to avoid rebuilding the child widget each time. I think the following code is a good starting point (You could also use a StreamBuilder to build the list leveraging the stream).

In main.dart

import 'dart:async';

import 'package:base_test_project/expanding_list.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  StreamController<int> _controller = StreamController<int>();

  int _number = 0;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new ExpandingList(stream: _controller.stream),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {_controller.add(_number++);},
        child: new Icon(Icons.add),
      ),
    );
  }
}

In expanding_list.dart

import 'dart:async';

import 'package:flutter/material.dart';

class ExpandingList extends StatefulWidget {
  Stream<int> stream;

  ExpandingList({this.stream});

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

class _ExpandingListState extends State<ExpandingList> {
  List<int> _myList = [];

  @override
  void initState() {
    super.initState();

    widget.stream.listen((number) {
      setState(() { _myList.add(number); });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: _myList.length,
        itemBuilder: (context, index) {
          return Padding(
              padding: EdgeInsets.all(15.0), child: Text("Item ${_myList[index]}"));
        });
  }
}

Upvotes: 3

Related Questions