Home > front end >  How to get radio button value to int and calculate in flutter
How to get radio button value to int and calculate in flutter

Time:04-23

Here is the output of this exerciseI just started to learn Flutter/Dart as my lecturer ask me to do some simple mobile app of e-ticket where the user need to choose from the radio button the movie that have value price for each radio button . Then the user need to input quantity value then click the submit button where the result of calculation need to be shown in another result page. Below is the picture of the assignment and some code that i have done. But i got stuck in the calculation part where i did not find any solution to this. hope anyone can help me with this.

main dart main dart

import 'package:flutter/material.dart';
import 'result.dart';
import 'customer.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
enum SingingCharacter { avengers, batman, kimetsu }

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final txtName= TextEditingController();
  final txtEmail = TextEditingController();
  final txtQuantity = TextEditingController();
  SingingCharacter? _character = SingingCharacter.avengers;

  void _gotoResultScreen(){

    Customer c= Customer(txtName.text, txtEmail.text, int.parse(txtQuantity.text));

    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => ResultPage(
            title:"Result Screen",
            content:"Congratulation! You've reached this page",
            customer: c,)
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Name'),
            TextField(
              controller: txtName,
            ),
            Text('Email'),
            TextField(
              controller: txtEmail,
            ),

            Text('Choose a movie:'),
            ListTile(
              title: const Text('AVENGERS(RM20)'),
              leading: Radio<SingingCharacter>(
                value: SingingCharacter.avengers,
                groupValue: _character,
                onChanged: (SingingCharacter? value) {
                  setState(() {
                    _character = value;
                  });
                },
              ),
            ),
            ListTile(
              title: const Text('BATMAN(RM10)'),
              leading: Radio<SingingCharacter>(
                  value: SingingCharacter.batman,
                  groupValue: _character,
                  onChanged: (SingingCharacter? value) {
                    setState(() {
                      _character = value;
                    });
                  }
              ),
            ),

            ListTile(
              title: const Text('KIMETSU NO YAIBA(RM12)'),
              leading: Radio<SingingCharacter>(
                  value: SingingCharacter.kimetsu,
                  groupValue: _character,
                  onChanged: (SingingCharacter? value) {
                    setState(() {
                      _character = value;
                    });
                  }
              ),
            ),

            Text('quantity'),
            TextField(
              controller: txtQuantity,
            ),

            RaisedButton(
              onPressed:_gotoResultScreen,
              //do something
              child: new Text('Calculate'),
            ),
          ],
        ),
      ),
    );
  }
}

result.dart

import 'package:flutter/material.dart';
import 'customer.dart';

class ResultPage extends StatefulWidget {
  const ResultPage({Key? key, required this.title, required this.content, required this.customer}) : super(key: key);

  final String title;
  final String content;
  final Customer customer;

  @override
  State<ResultPage> createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(widget.content,),
            Text("Name:"   widget.customer.name),
            Text("Email: "   widget.customer.email),
            Text("Quantity:"   widget.customer.quantity.toString()),
          ],
        ),
      ),
    );
  }
}

customer.dart

  class Customer {
  final String name;
  final String email;
  final int quantity;



  const Customer(this.name, this.email, this.quantity);
}

CodePudding user response:

You can calculate the price like this.

Let's say your _character value is SingingCharacter.avengers

int price = getPriceFromCharacter(_character) * int.parse(txtQuantity.text);

getPriceFromCharacter(SingingCharacter? character) {
 switch(character) { 
   case SingingCharacter.avengers: { 
     return 20;
   } 
   case SingingCharacter.batman: { 
     return 10;
   } 
   case SingingCharacter.kimetsu: { 
     return 12;
   } 
  } 
}

CodePudding user response:

You can use Map<String, int> to store the movie name and its price. Then create the List<Map<String, int>> and use the .map() function on this list to covert the list into listTile.

CodePudding user response:

You should pass necessary arguments to result page. You passed Customer, that is ok. But movie info is missing. For example:

Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) => ResultPage(
        title:"Result Screen",
        content:"Congratulation! You've reached this page",
        customer: c,
        movieName: ...,
        price: ...,
      )
  ),
);

And of course you should edit Result page accordingly.

After go to result page. Use price data and multiply quantity. This is gonna be final price.

However, this is not a good approach, Instead of using this kind of solutions, I recommend create a Movie class like Customer. Also quantity info should not be a field of Customer, it should be field of Movie class.

  • Related