Я новичок в flutter, и я пытаюсь обновить переменную в моем main.dart из customWidget в другом файле. Я ищу по inte rnet, но немного потерялся.
Как обновить мою переменную userDistance значением, введенным пользователем? Правильная ли структура моего виджета? или он должен быть без состояния или с сохранением состояния?
Main.dart:
class HomeController extends StatefulWidget {
HomeController({Key key, this.title}) : super(key: key);
final String title;
@override
_HomeControllerState createState() => _HomeControllerState();
}
class _HomeControllerState extends State<HomeController> {
// ************************************
// Variable
// ************************************
int userDistance = null;
final _formKey = GlobalKey<FormState>();
// ************************************
// Initialisation
// ************************************
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (() => FocusScope.of(context).requestFocus(FocusNode())),
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: loadJson(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return SingleChildScrollView(
padding: EdgeInsets.all(24),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FormValidatorWidgets.buildDistance(), // => Here I call my external widget
...
И мой customWidget:
import 'package:flutter/material.dart';
class FormValidatorWidgets{
static buildDistance() {
return TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Distance",
hintText: "Enter a distance",
),
keyboardType: TextInputType.number,
validator: (String value) {
int distance = int.tryParse(value);
if (distance == null) {
return "Distance is required";
}
if (distance <= 0) {
return "Distance must be greater than zero";
}
},
onSaved: (String value) {
userDistance = int.tryParse(value);
},
);
}
}
Как обновить мою переменную userDistance?