首页 > 解决方案 > How to add Strings to a List from a TextFormField in Flutter

问题描述

I don't have a code yet but i want to be able to save data from a textformfield to a list.

I want to get String from a textformfield whenever a comma is detected, eg, adding tags to a post or video

标签: flutterdart

解决方案


我写了一个简单的程序,当它检测到你的文本中有逗号时,它会将文本添加TextFormField到a 中。ListView

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<String> _data = List.empty(growable: true);
  final TextEditingController _textFieldController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Add to the list!")),
        body: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _textFieldController,
                decoration: InputDecoration(
                  labelText: 'Enter your text',
                ),
                style: TextStyle(fontSize: 20),
                onChanged: (value) {
                  if (value.contains(','))
                    Future.delayed(
                      Duration.zero,
                      () => setState(() {
                        final str = value.replaceAll(',', '');
                        _textFieldController.text = '';
                        if (str.isNotEmpty) _data.add(str);
                      }),
                    ).then(
                      (value) => _scrollController.animateTo(
                        _scrollController.position.maxScrollExtent + 30,
                        duration: const Duration(milliseconds: 250),
                        curve: Curves.easeInOut,
                      ),
                    );
                },
              ),
              SizedBox(height: 20),
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  itemExtent: 30,
                  cacheExtent: 30,
                  itemCount: _data.length,
                  itemBuilder: (context, index) => Text(
                    _data[index],
                    style: TextStyle(
                      fontSize: 20,
                      fontStyle: FontStyle.italic,
                      color: Colors.blue[900],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

推荐阅读