Flutter. How to update text inside GridView which inside PageView?

Viewed 208

I have a Page that contains a PageView and this PageView contains a GridView, and this GridView contains Text. Right now I want to update only one Text, not all the Text, how should I do without reloading all the PageView? For example, right now I only have a Text(), I want to make a widget out of this. How should I do that so I can update the specific Text and not reload all PageView and its children?

PageView.builder(itemBuilder: (context, index) {
  return GridView.builder(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, ), itemBuilder: (context, index) {
    return Text('$index');
  });
}, itemCount: 3,),

)

2 Answers

My answer for you: unnecessary. Because GridView.builder cache your widget. You can change your text comfortably and setState in current Page. GridView will build the widgets have changed.

It depends how you get your updated data.

You can customize the GridView Item with a customized Widget, and call setState in that widget.

But you need a way to know when the data been updated.

class YourGridViewCell extends StatefulWidget {
  final String label;
  const YourGridViewCell({this.label});
  @override
  State<StatefulWidget> createState() => _YourGridViewCellState();
}

class _YourGridViewCellState extends State<YourGridViewCell> {
  String _label;
  @override
  void initState() {
    super.initState();
    _label = widget.label;
  }

  @override
  Widget build(BuildContext context) {
    return Text(widget.label);
  }

  // you can call this to update cell.
  void _updateText(String newLabel) {
    setState(() {
      _label = newLabel;
    });
  }
}

Related