Home > Software design >  how to accept multiple variables in result?
how to accept multiple variables in result?

Time:05-04

I have an argument passed from one screen to the previous screen using pop().When I pass one variable, then everything is fine, but when I pass several, the application does not work. How can I fix this and pass inputText and the value of two variables _privacy and _terms_of_use to me and output them? How can they be added to pop() and received in setState as a result? My screen with arg:

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

  @override
  State<TextScreen> createState() => _TextScreenState();
}

class _TextScreenState extends State<TextScreen> {
  // initial values for checkboxes
  bool _privacy = false;
  bool _termsOfUse = false;

  // text controller for message input
  TextEditingController textController = TextEditingController();

  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }

  void _getResult(BuildContext context) {
    String inputText = textController.text;
    Navigator.of(context).pop(inputText);
  }

  @override
  Widget build(BuildContext context) {
    void _onChangePrivacy(value) {
      setState(() {
        _privacy = value!;
      });
    }

    void _onChangeTermsOfUse(value) {
      setState(() {
        _termsOfUse = value!;
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('Enter data'),
      ),
      body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: textController,
                decoration: const InputDecoration(labelText: 'Message'),
              ),
              const SizedBox(height: 20),
              CheckboxListTile(
                title: const Text('Privacy'),
                controlAffinity: ListTileControlAffinity.leading,
                value: _privacy,
                onChanged: (value) {
                  _onChangePrivacy(value);
                },
                contentPadding: EdgeInsets.zero,
              ),
              CheckboxListTile(
                title: const Text('Terms of use'),
                controlAffinity: ListTileControlAffinity.leading,
                value: _termsOfUse,
                onChanged: (value) {
                  _onChangeTermsOfUse(value);
                },
                contentPadding: EdgeInsets.zero,
              ),
              ElevatedButton(
                  onPressed: () {
                    _getResult(context);
                  },
                  child: const Text('Display result'))
            ],
          )),
    );
  }
}

My Result Screen:

class ResultScreen extends StatefulWidget {
  @override
  State<ResultScreen> createState() => _ResultScreenState();
}

class _ResultScreenState extends State<ResultScreen> {
  String? _valueText = '';

  @override
  Widget build(BuildContext context) {
    // navigation to next screen
    void _navToNextScreen(BuildContext context) async {
      final result = await Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const TextScreen()),
      );
      setState(() {
        _valueText = result;
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('Results'),
      ),
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(
              onPressed: () {
                _navToNextScreen(context);
              },
              child: const Text('Enter data')),
          const SizedBox(height: 50),
          Text('Message: $_valueText'),
          const SizedBox(height: 20),
          Text('Checkboxes: '),
        ],
      )),
    );
  }
}

CodePudding user response:

You can pass them in an array like that:

List<String> data = ['str1', 'str2', 'str3'];
Navigator.of(context).pop(data);

And Receive them like that:

List<String> result = await Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => const TextScreen()),
);
setState(() {
   _value1 = result[0];
   _value2 = result[1];
   _value3 = result[2];
});

CodePudding user response:

If we look at the implementation of the pop method it looks like this:

  @optionalTypeArgs
  static void pop<T extends Object?>(BuildContext context, [ T? result ]) {
    Navigator.of(context).pop<T>(result);
  }

This means we can optionally pass one generic object (T? result). In your case just passing a List containing multiple objects is the easiest solution.

The screen calling pop therefore could look like this:

 Navigator.of(context).pop([inputText, inputText2]);

And your receiving screen could do something like this:

 final results = await Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const TextScreen()),
      );
 var textOne = results[0];
 var textTwo = results[1];
 ...
  • Related