Ad

Flutter | The Argument Type 'Object?' Can't Be Assigned To The Parameter Type 'int'

I am getting the error in my code . As i am passing the int value index to the function. Here is my code which might help you out to solve my query.

import 'package:flutter/material.dart';
class Gratitude extends StatefulWidget {
  final int radioGroupValue;
  const Gratitude({required Key key, required this.radioGroupValue}) : super(key: key);
  @override
  _GratitudeState createState() => _GratitudeState();
}
class _GratitudeState extends State<Gratitude> {
final List<String> _gratitudeList = [];
  late String _selectedGratitude;
  late int _radioGroupValue;
void _radioOnChanged(int index) {
    setState(() {
      _radioGroupValue = index;
      _selectedGratitude = _gratitudeList[index];
      print('_selectedRadioValue $_selectedGratitude');
    });
  }
  @override
  void initState() {
    super.initState();
    _gratitudeList..add('Family')..add('Friends')..add('Coffee');
    _radioGroupValue = widget.radioGroupValue;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Gratitude'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: () => Navigator.pop(context, _selectedGratitude),
          ),
        ],
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: <Widget>[
              Radio(
                value: 0,
                groupValue: _radioGroupValue,
                onChanged: (index) => _radioOnChanged(index),
              ),
              const Text('Family'),
              Radio(
                value: 1,
                groupValue: _radioGroupValue,
                onChanged: (index) => _radioOnChanged(index),
              ),
              const Text('Friends'),
              Radio(
                value: 2,
                groupValue: _radioGroupValue,
                onChanged: (index) => _radioOnChanged(index),
              ),
              const Text('Coffee'),
            ],
          ),
        ),
      ),
    );
  }
}

Error is :The argument type 'Object?' can't be assigned to the parameter type 'int'. pointing to all 3 lines with the following code. onChanged: (index) => _radioOnChanged(index)

Ad

Answer

Try this: onChanged: (index) => _radioOnChanged(index as int) in order to tell dart to cast the Object as an int.

Ad
source: stackoverflow.com
Ad