flutter 抖动/将TextEditingController文本转换为整数

mklgxw1f  于 2023-03-03  发布在  Flutter
关注(0)|答案(4)|浏览(121)

我试图将文本从TextFormField转换为整数,例如,我将"3"作为字符串插入,但我需要将其转换为Int,这是我的代码,只关注持续时间变量,这就是我希望它成为的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),),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

我尝试使用另一个变量将duration变量转换为int,如下所示
intweek = int.tryParse(持续时间);但还是不行

kd3sttzy

kd3sttzy1#

您可以执行延迟初始化

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

或者可以在initState上赋值。

var duration = TextEditingController();
  int? week;

  @override
  void initState() {
    super.initState();
    week = week = int.tryParse(duration.text);
  }
ff29svar

ff29svar2#

将字符串转换为整数

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

如果你不确定字符串是否可以被安全地解析为整数,你可以使用int.tryParse()方法,如果字符串不能被解析为整数,int.tryParse()方法返回null,而不是抛出异常。

String myString = "123";
int myInt = int.tryParse(myString);
if (myInt != null) {
  print(myInt); // Output: 123
} else {
  print("Invalid integer string");
}
dluptydi

dluptydi3#

我看到duration是你的控制器,当你说duration.text的时候,它会输出一个字符串。int。tryParse不会返回一个int。

lnvxswe2

lnvxswe24#

问题是你用一个变量初始化了week,这个变量也是在同一个类中初始化的,所以解决方案是添加initState()函数并用duration.toInt()初始化week
这里是解决方案复制粘贴它,如果你面临任何问题给予我一个更新:

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),),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

相关问题