Why the String Value didn't update even though I'm pressed the button, I don't know which part is wrong. can you guys help me?
The way it works is that let's say I have an initial value of 100. If I input a value in the text field, for example, 5, then it will become 105, and so on.
import 'dart:ffi';
import 'package:flutter/material.dart';
class InitialValue extends StatefulWidget{
InitialValue({Key? key}):super(key: key);
@override
_InitialValue createState()=> _InitialValue();
}
class _InitialValue extends State<InitialValue>{
String Value = "100";
final TextEditingController ivalue = TextEditingController();
int value = 0;
void hitungtambah(){
String Ivalue = ivalue.text;
int Fvalue = int.tryParse(Ivalue)?? 0;
int value = int.tryParse(Value)??0;
setState(() {
value+=Fvalue;
});
}
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text("Initial Value"),
),
body: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
child: Text("$value",
style: TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.only(left: 20,right: 20,top: 20),
child:
TextField(
decoration: InputDecoration(
hintText: 'Input Value',),
controller: ivalue,),
),
TextButton(onPressed: (){
hitungtambah();
}, child: Text("Plus"))
],
) ,
);
}
}
To set initial text on TextEditingController
you can use
TextEditingController.fromValue(TextEditingValue(text: "100"));
Now use the controller to get text when button is pressed,
class InitialValue extends StatefulWidget {
InitialValue({Key? key}) : super(key: key);
@override
_InitialValue createState() => _InitialValue();
}
class _InitialValue extends State<InitialValue> {
final TextEditingController controller =
TextEditingController.fromValue(TextEditingValue(text: "100"));
int value = 0; ///you can change this value to 100
void hitungtambah() {
int inputValue = int.tryParse(controller.text) ?? 0;
setState(() {
value += inputValue;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Initial Value"),
),
body: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
child: Text(
"$value",
style: TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.only(left: 20, right: 20, top: 20),
child: TextField(
decoration: InputDecoration(
hintText: 'Input Value',
),
controller: controller,
),
),
TextButton(
onPressed: () {
hitungtambah();
},
child: Text("Plus"))
],
),
);
}
}
You can check /effective-dart/style and get-started/codelab.