skip to Main Content

im trying to convert my text from TextFormField to an integer for example i insert ‘3’ as string but i need to convert it to Int
here is my code
just focus on duration variable thats what i want it to be as int

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:social_sharing/LifeStyle_Health_Gym/models/Home%20model/AddPlan/PlanQsModel.dart';
import '../../../../Social_Sharing/shared/styles/icon_broken.dart';
import '../../../layout/cubit/cubit.dart';
import '../../../layout/cubit/states.dart';
import 'PlanDetailsScreen.dart';

class PlanQScreen extends StatefulWidget {

  @override
  State<PlanQScreen> createState() => _PlanQScreenState();
}

class _PlanQScreenState extends State<PlanQScreen> {

  var formKey = GlobalKey<FormState>();
  var planName = TextEditingController();
  var description = TextEditingController();
  var duration = TextEditingController();
  int? week = int.tryParse(duration); // Error here under duration
  dynamic goal = 'Muscle Building';
  List goalList =['Muscle Building','Fat Loss','Keep Fit'];
  dynamic levelChoose ='Beginner';
  List levelList =['Beginner','Expert','SuperMan'];

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LifeStyleCubit,LifeStates>(
      listener: (context,state){},
      builder: (context,state)
      {
        PlanQsModel? model = PlanQsModel(
            planName: planName.text,
            description: description.text,
            duration: duration.text,
            goal: goal,
            level: levelChoose
        );
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              onPressed: ()
              {
                Navigator.pop(context);
              },icon: Icon(IconBroken.Arrow___Left_2),
            ),
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Form(
                key: formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Plan Name*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                    SizedBox(height: 10,),
                    TextFormField(
                      controller: planName,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'fill the information';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        hintText: 'type here',
                      ),
                    ),
                    SizedBox(height: 20,),
                    Text('Description',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                    SizedBox(height: 10,),
                    TextFormField(
                      controller: description,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'fill the information';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        hintText: 'Plan Description',
                      ),
                    ),
                    SizedBox(height: 20,),
                    Text('Duration(Weeks)*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                    SizedBox(height: 10,),
                    TextFormField(
                      controller: duration,
                      keyboardType:TextInputType.number,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'fill the information';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        hintText: 'type here',
                      ),
                    ),
                    SizedBox(height: 20,),
                    Text('Goal',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                    SizedBox(height: 10,),
                    DropdownButtonFormField(
                      value: goal,
                      items: goalList
                          .map((item) => DropdownMenuItem(
                        value: item,
                        child: Text(item),
                      )).toList(),
                      onChanged: (value){
                        setState(() {
                          goal = value ;
                        });
                      },
                    ),
                    SizedBox(height: 20,),
                    Text('Level*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                    SizedBox(height: 10,),
                    DropdownButtonFormField(
                      value: levelChoose,
                      items: levelList
                        .map((item) => DropdownMenuItem(
                        value: item,
                        child: Text(item),
                      )).toList(),
                      onChanged: (value){
                        setState(() {
                          levelChoose = value ;
                        });
                      },
                    ),
                    SizedBox(height: 40,),
                    Center(
                      child: Container(
                        height: 60,
                        width: 160,

                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Colors.orange.shade900,
                        ),
                        child: MaterialButton(onPressed: ()
                        {
                          if(formKey.currentState!.validate())
                          {
                            LifeStyleCubit.get(context).createPlanQAnswers(
                                planName: planName.text,
                                description: description.text,
                                duration: duration.text,
                                goal: goal,
                                level: levelChoose
                            );
                            Navigator.push(context, MaterialPageRoute(
                                builder: (context)=>PlanDetailsScreen(model)));
                          }
                        },
                          child: Text('ADD PLAN',style: TextStyle(color: Colors.white,
                          fontSize: 17),),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

i tried to use another variable to convert my duration variable to int as follow

int week = int.tryParse(duration); but still not working

3

Answers


  1. convert a string to an integer

    String myString = "123";
    int myInt = int.parse(myString);
    print(myInt); // Output: 123
    

    If you’re not sure whether the string can be safely parsed as an integer, you can use the int.tryParse() method instead. The int.tryParse() method returns null if the string cannot be parsed as an integer, instead of throwing an exception.

    String myString = "123";
    int myInt = int.tryParse(myString);
    if (myInt != null) {
      print(myInt); // Output: 123
    } else {
      print("Invalid integer string");
    }
    
    Login or Signup to reply.
  2. You can do lazy initialization

    var duration = TextEditingController();
      late int? week = int.tryParse(duration.text);
    

    Or can assign value on initState.

      var duration = TextEditingController();
      int? week;
    
      @override
      void initState() {
        super.initState();
        week = week = int.tryParse(duration.text);
      }
    
    Login or Signup to reply.
  3. The problem is that you initialized week with a variable that’s also initialized in the same class so the solution is to add initState() function and initialize week with duration.toInt() .

    here is the solution copy and paste it and if you face any issue give me an update :

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_bloc/flutter_bloc.dart';
    import 'package:social_sharing/LifeStyle_Health_Gym/models/Home%20model/AddPlan/PlanQsModel.dart';
    import '../../../../Social_Sharing/shared/styles/icon_broken.dart';
    import '../../../layout/cubit/cubit.dart';
    import '../../../layout/cubit/states.dart';
    import 'PlanDetailsScreen.dart';
    
    class PlanQScreen extends StatefulWidget {
    
      @override
      State<PlanQScreen> createState() => _PlanQScreenState();
    }
    
    class _PlanQScreenState extends State<PlanQScreen> {
    
      var formKey = GlobalKey<FormState>();
      var planName = TextEditingController();
      var description = TextEditingController();
      var duration = TextEditingController();
      int week = 0; // Error here under duration
      dynamic goal = 'Muscle Building';
      List goalList =['Muscle Building','Fat Loss','Keep Fit'];
      dynamic levelChoose ='Beginner';
      List levelList =['Beginner','Expert','SuperMan'];
    
    
       @override
      void initState() {
        // TODO: implement initState
        super.initState();
        week = int.tryParse(duration);
      }
    
      @override
      Widget build(BuildContext context) {
        return BlocConsumer<LifeStyleCubit,LifeStates>(
          listener: (context,state){},
          builder: (context,state)
          {
            PlanQsModel? model = PlanQsModel(
                planName: planName.text,
                description: description.text,
                duration: duration.text,
                goal: goal,
                level: levelChoose
            );
            return Scaffold(
              appBar: AppBar(
                leading: IconButton(
                  onPressed: ()
                  {
                    Navigator.pop(context);
                  },icon: Icon(IconBroken.Arrow___Left_2),
                ),
              ),
              body: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Form(
                    key: formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('Plan Name*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                        SizedBox(height: 10,),
                        TextFormField(
                          controller: planName,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'fill the information';
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: 'type here',
                          ),
                        ),
                        SizedBox(height: 20,),
                        Text('Description',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                        SizedBox(height: 10,),
                        TextFormField(
                          controller: description,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'fill the information';
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: 'Plan Description',
                          ),
                        ),
                        SizedBox(height: 20,),
                        Text('Duration(Weeks)*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                        SizedBox(height: 10,),
                        TextFormField(
                          controller: duration,
                          keyboardType:TextInputType.number,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'fill the information';
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: 'type here',
                          ),
                        ),
                        SizedBox(height: 20,),
                        Text('Goal',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                        SizedBox(height: 10,),
                        DropdownButtonFormField(
                          value: goal,
                          items: goalList
                              .map((item) => DropdownMenuItem(
                            value: item,
                            child: Text(item),
                          )).toList(),
                          onChanged: (value){
                            setState(() {
                              goal = value ;
                            });
                          },
                        ),
                        SizedBox(height: 20,),
                        Text('Level*',style: TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
                        SizedBox(height: 10,),
                        DropdownButtonFormField(
                          value: levelChoose,
                          items: levelList
                            .map((item) => DropdownMenuItem(
                            value: item,
                            child: Text(item),
                          )).toList(),
                          onChanged: (value){
                            setState(() {
                              levelChoose = value ;
                            });
                          },
                        ),
                        SizedBox(height: 40,),
                        Center(
                          child: Container(
                            height: 60,
                            width: 160,
    
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.orange.shade900,
                            ),
                            child: MaterialButton(onPressed: ()
                            {
                              if(formKey.currentState!.validate())
                              {
                                LifeStyleCubit.get(context).createPlanQAnswers(
                                    planName: planName.text,
                                    description: description.text,
                                    duration: duration.text,
                                    goal: goal,
                                    level: levelChoose
                                );
                                Navigator.push(context, MaterialPageRoute(
                                    builder: (context)=>PlanDetailsScreen(model)));
                              }
                            },
                              child: Text('ADD PLAN',style: TextStyle(color: Colors.white,
                              fontSize: 17),),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          },
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search