-1

// I cant find a way to pass a string from a class to another. They are both in the same screen and i want to pass the index from a pageview on class to another. Any help would be grateful!

//on the first class//


            onPageChanged: (int index) {
            _sendDataToAnotherClass(context, index);
            _currentPageNotifier.value = index;
          }),
      ),
    );
}


  void _sendDataToAnotherClass(BuildContext context, int index) {
    final String texttosend = index.toString();
    Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) {
              return new personaname(text: texttosend);
            }

        ));
  }


//on the second class//

 final String text ;
 personaname({Key key, @required this.text}) : super(key: key);

1 Answers1

0

if your personaname is a class (just fyi if that is indeed a class the proper format is to capitalize the first letters of each word - PersonaName), and that class is a stateful widget you could pass the data down to it and do a call within the state to override the didUpdateWidget method to setState on data changes. This would mean you don't need the value notifier.

Something like this might do what you're looking for:

class PageViewHolder extends StatelessWidget{

  PersonaName name = PersonaName(text: 'text',);

  @override
  Widget build(BuildContext context) {

    return PageView(
      onPageChanged: (p){
        var textToSend = 'do logic to decide name';
        name.text = textToSend;
      },
    );
  }

}


class PersonaName extends StatefulWidget{
  String text;

  PersonaName({Key key, this.text}) : super(key: key);

  @override
  State<StatefulWidget> createState() =>_PersonaName();
}

class _PersonaName extends State<PersonaName>{



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

  @override
  void didUpdateWidget(PersonaName oldWidget) {
    super.didUpdateWidget(oldWidget);
    if(widget.text != oldWidget.text){
      setState(() {});
    }
  }
}
Adrian Murray
  • 2,170
  • 1
  • 13
  • 15