Widget that acts like an Excel cell (can input a f

2019-08-19 14:52发布

问题:

I would like to create a widget (text field or other) where on clicking on it I can enter some text, but the displayed value is something else. Similar to an Excel cell with a formula: you can edit the formula, but you see the result.

Is that possible ?

Thanks.

回答1:

Definitely possible. In the example below a TextField currently changes some text to uppercase when the editing is completed. When the TextField is tapped it returns to showing the original input. You should be able to modify this to what you need.

import 'package:flutter/material.dart';

class ExcelFormulaField extends StatefulWidget {
  @override
  _ExcelFormulaFieldState createState() => _ExcelFormulaFieldState();
}

class _ExcelFormulaFieldState extends State<ExcelFormulaField> {
  String input;
  String output;
  bool isInputActive;
  TextEditingController controller;

  void updateInput(text) => setState(() {
        input = text;
      });

  void setInputActive() => setState(() {
        if (isInputActive != true) {
          isInputActive = true;

          resetController();

          print("Active");
          print("Input: $input, Output: $output");
        }
      });

  void setInputInactive() => setState(() {
        isInputActive = false;

        // TODO replace with the logic you want
        output = input.toUpperCase();
        controller = TextEditingController(text: output);

        print("InActive");
        print("Input: $input, Output: $output");
      });

  void resetController() {
    controller = TextEditingController(text: input);
    controller.addListener(() => updateInput(controller.text));
  }

  @override
  void initState() {
    super.initState();
    isInputActive = false;
    resetController();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setInputInactive();
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "input",
                  labelText: "Hit enter on keyboard to see change"),
              onTap: () {
                setInputActive();
              },
              onEditingComplete: () {
                setInputInactive();
              },
              controller: controller,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }
}

Hope it helps :-)



标签: dart flutter