Home > OS >  I have a problem with creating Radio Button in flutter
I have a problem with creating Radio Button in flutter

Time:07-30

No matter how many websites I visit and how many codes I copy, I still get a error in Android Studio when I am trying to create a basic Radio Button.

import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
  home: Home(),
));
class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);
  @override
  State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
  @override
  int _value = 1;
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Rent'),
      ),
      body: Column(
        children: [
          Radio(
            value: 1,
            groupValue: _value,
            onChanged: (value){
              setState(() {
                _value = value;
              });
            },
          ),
          Radio(
            value: 2,
            groupValue: _value,
            onChanged: (value){
              setState(() {
                _value = value;
              });
            },
          ),
          Radio(
            value: 3,
            groupValue: _value,
            onChanged: (value){
              setState(() {
                _value = value;
              });
            },
          ),
        ],
      ),
    );
  }
}

I don't know how to solve this, I have copied countless number of code in my compiler and nothing works related to Radio Buttons. Error is

lib/main.dart:43:26: Error: A value of type 'Object?' can't be assigned to a variable of type 'int'.
 - 'Object' is from 'dart:core'.
                _value = value;
                         ^

CodePudding user response:

You need to specify the type of Radio Button, here Radio widget as Radio<int> .

CodePudding user response:

The value parameter from onChanged is nullable. You can use bang operator if you are sure that value will never be null to make the compiler happy.

          Radio<int>(
            value: 2,
            groupValue: _value,
            onChanged: (value){
              setState(() {
                _value = value!;   // <--- use bang operator
              });
            },
          ),
  • Related