Flutter Radio Button example

In this tutorial, we’re gonna build a Flutter App that uses Radio Button to select between a number of options.

Overview

Flutter App

Our example is Currency Converter App that can convert USD to Euro, Pound or Yen:

flutter-radio-button-example

To do this, we are going to add 3 Radio Buttons that allow users to select Currency they want to convert from USD.

Radio Button

When one radio button in a group is selected, the others are un-selected. This means only one option is accepted at the same time.

Radio Button itself does not maintain any state. Instead, when the state of the radio button changes, the widget calls the onChanged callback.
=> listen for the onChanged callback and rebuild the Radio Button with groupValue to update state variables.

Practice

Project Structure

flutter-radio-button-example-project-structure

Add Image to Project

Under Project folder level, create images directory, then add currencies.png (you will find this image in the Source Code below).

Open pubspec.yaml, add assets:

Create a Custom StatefulWidget

Create new currency.dart file at lib/ui/ for Currency class:

– Radio Button onChanged callback points to _handleRadioValueChange() method.
– Inside _handleRadioValueChange(), we use setState() to set the Widget’s state, and _textResult state variable will be updated to show the result.
– We create a TextEditingController (_currencyController) to get input Amount value (TextField), and we also use onChanged callback of TextField class to update the result everytime the text changes.

Inflate and attach stateful widget to screen

main.dart

Source Code

currency_converter

By JavaSampleApproach | July 6, 2018.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*