Flutter:从DropDownMenu和日期选取器获取TextFormField内的文本

pokxtpni  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(129)

在从DropDownMenu和DatePicker中选择一些值之后,是否有办法在TextFormField中获得一些文本?
在我的应用程序中,我有TextFormField,我想在那里通过键盘输入一些文本,或者从DropDownMenu和DatePicker中选择。
按下按钮将文本插入TextFormField后,值将显示在屏幕上。
我可以在从drodownmenu和datepicker中选择并按下按钮后将其显示在scree上。
但我希望选定的下拉菜单和日期选择器值首先进入TextFormField,然后按下按钮,它将显示在屏幕上。
提前寻求帮助。
遵循代码:

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() async {
  Get.put(SpringTesterController());
  runApp(const GetMaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: GetBuilder<SpringTesterController>(
            init: SpringTesterController(),
            builder: (gtxs1) {
              return const MyHomePage();
            }),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SpringTesterController>(
        init: SpringTesterController(),
        builder: (gtxs1) {
          return Column(
            children: [
              Row(
                children: [
                  const Text(
                    'Name:',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                      color: Colors.blue,
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(
                    gtxs1.displayedValue,
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFFEF6C00),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  IconButton(
                    icon: const Icon(
                      Icons.calendar_month_outlined,
                    ),
                    onPressed: () async {
                      await gtxs1.selectDate(context);
                    },
                  ),
                  DropdownButton(
                    value: gtxs1.selectedValue,
                    onChanged: (value) {
                      gtxs1.onSelectedDropdown(value.toString());
                    },
                    items: const [
                      DropdownMenuItem(
                        value: '1',
                        child: Text('1'),
                      ),
                      DropdownMenuItem(
                        value: '2',
                        child: Text('2'),
                      ),
                      DropdownMenuItem(
                        value: '3',
                        child: Text('3'),
                      ),
                      DropdownMenuItem(
                        value: '4',
                        child: Text('4'),
                      ),
                    ],
                  ),
                ],
              ),
              Form(
                key: _formKey,
                child: Row(
                  children: [
                    SizedBox(
                      height: 40,
                      width: 250,
                      child: TextFormField(
                        onChanged: gtxs1.onTextFieldChanged,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(
                        Icons.save,
                      ),
                      onPressed: () {
                        gtxs1.setName();
                      },
                    ),
                  ],
                ),
              ),
            ],
          );
        });
  }
}

class SpringTesterController extends GetxController {
  static SpringTesterController get to => Get.find();
  String? selectedValue;
  String enteredValue = '';
  String displayedValue = '';
  DateTime _selectedDate = DateTime.now();

  void onSelectedDropdown(String newValue) {
    selectedValue = newValue;
    update();
  }

  void onTextFieldChanged(String newValue) {
    enteredValue = newValue;
    update();
  }

  void setName() {
    if (enteredValue.isNotEmpty) {
      displayedValue = enteredValue;
    } else {
      if (selectedValue != null) {
        displayedValue = '${selectedValue!} $_selectedDate';
      } else {
        displayedValue = _selectedDate.toString();
      }
    }
    update();
  }

  Future<void> selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2015),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != _selectedDate) {
      _selectedDate = picked;
    }
    update();
  }
}

已修改完成的代码。

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  await GetStorage.init();
  Get.put(SpringTesterController());
  runApp(const GetMaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: GetBuilder<SpringTesterController>(
            init: SpringTesterController(),
            builder: (gtxs1) {
              return const MyHomePage();
            }),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  TextEditingController textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SpringTesterController>(
        init: SpringTesterController(),
        builder: (gtxs1) {
          return Column(
            children: [
              Row(
                children: [
                  const Text(
                    'JSON File Name2:  ',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                      color: Colors.blue,
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(
                    gtxs1.displayedValue,
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFFEF6C00),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  IconButton(
                    icon: const Icon(
                      Icons.calendar_month_outlined,
                    ),
                    onPressed: () async {
                      await gtxs1._selectDate(context).then((selectedDate) {
                        textController.text = selectedDate.toString();
                      });
                    },
                  ),
                  DropdownButton(
                    value: gtxs1.selectedValue,
                    onChanged: (value) {
                      gtxs1.onSelectedDropdown(value.toString());
                      textController.text = value.toString();
                    },
                    items: const [
                      DropdownMenuItem(
                        value: '1',
                        child: Text('1'),
                      ),
                      DropdownMenuItem(
                        value: '2',
                        child: Text('2'),
                      ),
                      DropdownMenuItem(
                        value: '3',
                        child: Text('3'),
                      ),
                      DropdownMenuItem(
                        value: '4',
                        child: Text('4'),
                      ),
                    ],
                  ),
                ],
              ),
              Form(
                key: _formKey,
                child: Row(
                  children: [
                    SizedBox(
                      height: 40,
                      width: 250,
                      child: TextFormField(
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Please enter some text';
                          }
                          return null;
                        },
                        onChanged: gtxs1.onTextFieldChanged,
                        controller: textController,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(
                        Icons.save,
                      ),
                      onPressed: () {
                        gtxs1.setName();
                      },
                    ),
                  ],
                ),
              ),
            ],
          );
        });
  }
}

class SpringTesterController extends GetxController {
  static SpringTesterController get to => Get.find();
  String? selectedValue;
  String enteredValue = '';
  String displayedValue = '';
  DateTime _selectedDate = DateTime.now();

  void onSelectedDropdown(String newValue) {
    selectedValue = newValue;
    update();
  }

  void onTextFieldChanged(String newValue) {
    enteredValue = newValue;
    update();
  }

  void setName() {
    if (enteredValue.isNotEmpty) {
      displayedValue = enteredValue;
    } else {
      if (selectedValue != null) {
        displayedValue = '${selectedValue!} $_selectedDate';
      } else {
        displayedValue = _selectedDate.toString();
      }
    }
    update();
  }

  Future<DateTime> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2015, 8),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != _selectedDate) {
      _selectedDate = picked;
    }
    update();
    return _selectedDate;
  }
}
xzv2uavs

xzv2uavs1#

MyHomePageState类中定义控制器,如下所示:
TextEditingController textController = TextEditingController();
TextFormField中分配控制器,如下所示:

TextFormField(
                        onChanged: gtxs1.onTextFieldChanged,
                        controller: textController,
                      ),

当您点击DropdownMenu时,将文本分配给控制器,如下所示:
textController.text = 'your data from Dropdown/DatePicker' ;
有关详细信息,请参阅TextEditingController的官方文档

相关问题