我在应用程序中使用了全屏对话框,以使用户在文本字段中输入值。这些值中有些是字符串,有些是整数。因此,我想相应地更改键盘,以使不必要的键消失。这是我的实现:

import 'package:flutter/material.dart';
import 'package:meal_tracker/model/food_model.dart';

class AddFoodDialog extends StatelessWidget {
  TextEditingController nameController = TextEditingController(),
      carbsController = TextEditingController(),
      fatController = TextEditingController(),
      proteinController = TextEditingController(),
      amountController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Add Food"),
        actions: <Widget>[
          FlatButton(
            child: Text(
              "SAVE",
              style: TextStyle(color: Colors.white),
            ),
            onPressed: () {
              _handleSave(context);
            },
          )
        ],
      ),
      body: Form(
          child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextFormField(
              decoration: InputDecoration(labelText: "Name"),
              controller: nameController,
            ),
            TextFormField(
              decoration: InputDecoration(labelText: "Carbs per 100g"),
              controller: carbsController,
              keyboardType: TextInputType.number,
            ),
            TextFormField(
              decoration: InputDecoration(labelText: "Fat per 100g"),
              controller: fatController,
              keyboardType: TextInputType.number,
            ),
            TextFormField(
              decoration: InputDecoration(labelText: "Protein per 100g"),
              controller: proteinController,
              keyboardType: TextInputType.number,
            ),
            TextFormField(
              decoration: InputDecoration(labelText: "Amount in g"),
              controller: amountController,
              keyboardType: TextInputType.number,
            ),
          ],
        ),
      )),
    );
  }

  void _handleSave(BuildContext context) {
    print("Dialog text: " + nameController.text);
    Navigator.of(context).pop(Food(
        name: nameController.text,
        carbsPer100g: double.parse(carbsController.text),
        fatPer100g: double.parse(fatController.text),
        proteinPer100g: double.parse(proteinController.text),
        amount: double.parse(amountController.text)));
  }
}

问题是,当我在具有TextInputType.text的“名称”文本字段中输入内容,然后点击另一个具有TextInputType.number的文本字段时,“名称”字段会被清除,没有明显的原因。反之亦然。

最佳答案

我不得不将TextEditingControllers放入一个有状态的小部件中,这确实可以正常工作。感谢乔纳·威廉姆斯的快速回复!

关于dart - 在TextInputType更改后使用 Controller 重置的Flutter TextField,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51518321/

10-10 14:42