Jon
Jon

Reputation: 115

Passing Arguments Though a named route Android App made with Flutter

I have been taking a course at AppBrewery on flutter and really this is my introduction to programming so it has been alot to take in.

I was working on a module to make a BMI body mass index calculator and was being taught about routes named and mapped..we were given a challenge to create a route in our app and I chose the mapped route approach. and it worked fine.

When I watched the video she used named routes because it was only 2 screens but since it worked I just left it at that.

later on in the module I had to pass some arguments to the second page and it is clear how to do it with named routes but I have had no luck with my code.

can someone show me why I keep passing null arguments even though I have no errors in my code currently.

here are my files.

main.dart

 import 'package:bmi_calculator/results_page.dart';
import 'package:flutter/material.dart';
import 'input_page.dart';

void main() => runApp(BMICalculator());

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        primaryColor: Color(0XFF0A0E21),
        scaffoldBackgroundColor: Color(0XFF0A0E21),
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => InputPage(),
        '/results': (context) => ResultsPage(),
      },
    );
  }
}

My Input Page the part that matters anyways

    Gender selectedGender;
  int initialHeight = 180;
  int initialWeight = 60;
  int initialAge = 30;

          BottomButton(
            buttonTitle: 'CALCULATE',
            onPress: () {
              CalculatorBrain calc =
                  CalculatorBrain(height: initialHeight, weight: initialWeight);
              Navigator.pushNamed(
                context,
                '/results',
                arguments: ResultsPage(
                  bmiResults: calc.calculateBMI(),
                  resultText: calc.getResult(),
                  resultSummary: calc.getResultSummary(),
                ),
              );
              //Navigate to ResultsPage
            },
          ),
        ],
      ),
    );
  }
}

and the the Calculator class

   import 'dart:math';

class CalculatorBrain {
  CalculatorBrain({this.height, this.weight});

  final int height;
  final int weight;
  double _bmi;

  String calculateBMI() {
    double _bmi = weight / pow(height / 100, 2);
    return _bmi.toStringAsFixed(1);
  }

  String getResult() {
    if (_bmi >= 25) {
      return 'OVERWEIGHT';
    } else if (_bmi > 18.5) {
      return 'NORMAL';
    } else {
      return 'UNDERWEIGHT';
    }
  }

  String getResultSummary() {
    if (_bmi >= 25) {
      return 'You have a higher than normal body weight.  Try to exercise more.';
    } else if (_bmi > 18.5) {
      return 'You have a normal body weight.  Good Job';
    } else {
      return 'You have a lower than normal body weight.  You can eat a bit more.';
    }
  }
}

Your insights would be appreciated by this newbie I did see a decent doc in the flutter cookbook but it still hard for me to understand.

Upvotes: 1

Views: 990

Answers (3)

Eishon
Eishon

Reputation: 1324

For passing argument

Navigator.pushNamed(
            context,
            '/results',
            arguments: {
              'bmiResults': calc.calculateBMI(),
              'resultText': calc.getResult(),
              'resultSummary': calc.getResultSummary(),
            },
          );

In routes section

class BMICalculator extends StatelessWidget {


@override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        primaryColor: Color(0XFF0A0E21),
        scaffoldBackgroundColor: Color(0XFF0A0E21),
      ),
      initialRoute: '/',
      onGenerateRoute: RouteManager.generateRoute,
    );
  }
}

RouteManager

class RouteManager {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    final args = settings.arguments;

    switch (settings.name) {
      case '/':
        return getRouteFor(
          InputPage(),
        );

      case '/results':
        if (args is Map) {
          return getRouteFor(
            ResultsPage(
              bmiResults: args['bmiResults'],
              resultText: args['resultText'],
              resultSummary: args['resultSummary'],
            ),
          );
        }

        return _underConstructionRoute();

      default:
        return _underConstructionRoute();
    }
  }

  static Route<dynamic> getRouteFor(Widget widget) {
    return Platform.isIOS
        ? CupertinoPageRoute(builder: (_) => widget)
        : MaterialPageRoute(builder: (_) => widget);
  }

  static Route<dynamic> _underConstructionRoute() {
    return getRouteFor(
      Scaffold(
        appBar: AppBar(
          title: Text(title),
          centerTitle: true,
        ),
        body: Center(
          child: Text(
            'Under Construction',
            style: TextStyle(
              fontSize: 40,
            ),
          ),
        ),
      ),
    );
  }
}

Check the detailed tutorial from ResoCoder. And add necessary imports.

Upvotes: 3

Preet Shah
Preet Shah

Reputation: 1047

Flutter Navigator 2.0 is very good with respect to what you need. Here is an article for the same.

Upvotes: 0

fartem
fartem

Reputation: 2541

You need to work with arguments by ScreenArguments class:

Put to screen:

Navigator.pushNamed(
  context,
  '/results',
  // Your arguments
  arguments: ScreenArguments(),
);

Get on new screen:

@override
Widget build(BuildContext context) {
  final ScreenArguments args = ModalRoute.of(context).settings.arguments;
  // Your code
}

Also, you can find all possible ways to provide routing by Flutter SDK in Official Documentation.

Upvotes: 0

Related Questions