Flutter:如何让 TextField 专注于提交? [英] Flutter: How to Keep TextField Focus on Submit?

查看:42
本文介绍了Flutter:如何让 TextField 专注于提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

完整代码

import 'dart:convert';导入包:颤振/material.dart";导入包:flutter/services.dart";导入包:flutter_tags/flutter_tags.dart";无效的主要()=>运行应用程序(我的应用程序());MyApp 类扩展 StatelessWidget {//这个小部件是您的应用程序的根.@覆盖小部件构建(BuildContext 上下文){返回材料应用程序(标题:颤振标签演示",主题:主题数据(primarySwatch:Colors.blueGrey,),主页:MyHomePage(标题:'Flutter 标签'),);}}类 MyHomePage 扩展 StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);最终字符串标题;@覆盖_MyHomePageState createState() =>_MyHomePageState();}类 _MyHomePageState 扩展状态<MyHomePage>与 SingleTickerProviderStateMixin {焦点节点 myFocusNode = 焦点节点();TextEditingController myController = TextEditingController();标签控制器 _tabController;滚动控制器_scrollViewController;最终列表<字符串>_list = ['0','SDK','插件更新','Facebook','哔狗了QP又是了','基尔霍夫','意大利','法国','西班牙','美','镖','SDK',‘福’,'选择','lorem ip','9','星星','颤振可选标签','1',哈勃",'2','输入颤振标签','A B C','8','Android Studio 开发者','欢迎来到丛林',高斯",美术",互联网",'炫舞时代',《阵营火场》,];布尔_对称=假;bool _removeButton = true;布尔 _singleItem = 假;布尔 _startDirection = 假;bool _horizo​​ntalScroll = false;布尔 _withSuggesttions = false;int _count = 0;int _column = 0;双_fontSize = 14;String _itemCombine = 'withTextBefore';字符串 _onPressed = '';列表_icon = [Icons.home,Icons.language,Icons.headset];@覆盖无效初始化状态(){super.initState();_tabController = TabController(长度: 2, vsync: this);_scrollViewController = ScrollController();_items = _list.toList();}列出_items;最终的 GlobalKey<TagsState>_tagStateKey = GlobalKey();@覆盖小部件构建(BuildContext 上下文){//列表<项目>lst = _tagStateKey.currentState?.getAllItem;lst.forEach((f) => print(f.title));返回脚手架(正文:嵌套滚动视图(控制器:_scrollViewController,headerSliv​​erBuilder: (BuildContext context, bool boxIsScrolled) {返回<小部件>[SliverAppBar(标题:文本(颤动标签"),中心标题:真实,固定:真的,扩展高度:0,浮动:真实,forceElevated: boxIsScrolled,底部:标签栏(isScrollable:假,指标大小:TabBarIndicatorSize.label,标签样式:文本样式(字体大小:18.0),标签:[选项卡(文本:演示 1"),选项卡(文本:演示 2"),],控制器:_tabController,),)];},正文:标签栏视图(控制器:_tabController,孩子们: [自定义滚动视图(条子:<小部件>[银名单(委托:SliverChildListDelegate([容器(装饰:盒子装饰(边框:边框(底部:边界边(颜色:Colors.grey[300],宽度:0.5))),利润:EdgeInsets.symmetric(水平:10,垂直:10),孩子:ExpansionTile(标题:文本(设置"),孩子们:<小部件>[排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_removeButton,onChanged: (a) {设置状态((){_removeButton = !_removeButton;});}),Text('删除按钮')],),点按:(){设置状态((){_removeButton = !_removeButton;});},),填充(填充:EdgeInsets.all(5),),手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_对称,onChanged: (a) {设置状态((){_symmetry = !_symmetry;});}),文本('对称')],),点按:(){设置状态((){_symmetry = !_symmetry;});},),填充(填充:EdgeInsets.all(5),),下拉按钮(提示:_column == 0?文本(未设置"):文本(_column.toString()),项目:_buildItems(),onChanged: (a) {设置状态((){_列=一个;});},),],),排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_horizo​​ntalScroll,onChanged: (a) {设置状态((){_horizo​​ntalScroll =!_horizo​​ntalScroll;});}),Text('水平滚动')],),点按:(){设置状态((){_horizo​​ntalScroll = !_horizo​​ntalScroll;});},),手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_singleItem,onChanged: (a) {设置状态((){_singleItem = !_singleItem;});}),文本('单项')],),点按:(){设置状态((){_singleItem = !_singleItem;});},),],),柱子(孩子们:<小部件>[文本('字体大小'),排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[滑块(值:_fontSize,分钟:6,最大:30,onChanged: (a) {设置状态((){_fontSize = (a.round()).toDouble();});},),文本(_fontSize.toString()),填充(填充:EdgeInsets.symmetric(水平:20),),容器(身高:30,宽度:30,//颜色:Colors.blueGrey,孩子:图标按钮(填充:EdgeInsets.all(0),//颜色:颜色.white,图标:图标(图标.add),按下:(){设置状态((){_count++;_items.add(_count.toString());//_items.removeAt(3);_items.removeAt(10);});},),),填充(填充:EdgeInsets.symmetric(水平:5),),容器(身高:30,宽度:30,//颜色:Colors.grey,孩子:图标按钮(填充:EdgeInsets.all(0),//颜色:颜色.white,图标:图标(图标.刷新),按下:(){设置状态((){_items = _list.toList();});},),),],),],),],),),填充(填充:EdgeInsets.all(20),),_tags1,容器(填充:EdgeInsets.all(20),孩子:列(孩子们:<小部件>[分频器(颜色:Colors.blueGrey,),填充(填充:EdgeInsets.symmetric(垂直:20),孩子:文本(_onPressed),),],)),])),],),自定义滚动视图(条子:<小部件>[银名单(委托:SliverChildListDelegate([容器(装饰:盒子装饰(边框:边框(底部:边界边(颜色:Colors.grey[300],宽度:0.5))),利润:EdgeInsets.symmetric(水平:10,垂直:10),孩子:ExpansionTile(标题:文本(设置"),孩子们:<小部件>[排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_withSuggestions,onChanged: (a) {设置状态((){_withSuggestions =!_withSuggestions;});}),文本('建议')],),点按:(){设置状态((){_withSuggesttions = !_withSuggesttions;});},),填充(填充:EdgeInsets.all(20),),下拉按钮(提示:文本(_itemCombine),项目:_buildItems2(),onChanged: (val) {设置状态((){_itemCombine = val;});},),],),排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_horizo​​ntalScroll,onChanged: (a) {设置状态((){_horizo​​ntalScroll =!_horizo​​ntalScroll;});}),Text('水平滚动')],),点按:(){设置状态((){_horizo​​ntalScroll = !_horizo​​ntalScroll;});},),手势检测器(孩子:行(孩子们:<小部件>[复选框(值:_startDirection,onChanged: (a) {设置状态((){_startDirection = !_startDirection;});}),Text('起始方向')],),点按:(){设置状态((){_startDirection = !_startDirection;});},),],),柱子(孩子们:<小部件>[文本('字体大小'),排(mainAxisAlignment: MainAxisAlignment.center,孩子们:<小部件>[滑块(值:_fontSize,分钟:6,最大:30,onChanged: (a) {设置状态((){_fontSize = (a.round()).toDouble();});},),文本(_fontSize.toString()),],),],),],),),填充(填充:EdgeInsets.all(20),),_tags2,容器(填充:EdgeInsets.all(20),孩子:列(孩子们:<小部件>[分频器(颜色:Colors.blueGrey,),填充(填充:EdgeInsets.symmetric(垂直:20),孩子:文本(_onPressed),),],)),文本域(控制器:我的控制器,装饰:输入装饰(图标:图标(Icons.person),labelText: "添加焦点标签",),焦点节点:我的焦点节点,onSubmitted: (val) {设置状态((){_items.add(val);});myController.clear();myFocusNode.requestFocus();},),])),],),],)),);}小部件获取 _tags1 {返回标签(键:_tagStateKey,对称性:_symmetry,列:_列,水平滚动:_horizo​​ntalScroll,//verticalDirection: VerticalDirection.up, textDirection: TextDirection.rtl,heightHorizo​​ntalScroll: 60 * (_fontSize/14),itemCount:_items.length,itemBuilder:(索引){最后一项 = _items[index];返回项目标签(键:键(index.toString()),索引:索引,标题:项目,按下启用:真,activeColor:Colors.blueGrey[600],单项:_单项,splashColor:颜色.绿色,结合:ItemTagsCombine.withTextBefore,图片:索引>0&&指数<5?项目标签图像(//image: AssetImage("img/p$index.jpg"),孩子:Image.network(http://www.clipartpanda.com/clipart_images/user-66327738/download",宽度:16 * _fontSize/14,高度:16 * _fontSize/14,)): (1 == 1?项目标签图像(图片:网络图片(https://d32ogoqmya1dw8.cloudfront.net/images/serc/empty_user_icon_256.v2.png"),): 空值),图标:(项目 == '0' || 项目 == '1' || 项目 == '2')?项目标签图标(图标:_icon[int.parse(item)],): 空值,删除按钮:_removeButton?ItemTagsRemoveButton(onRemoved: () {设置状态((){_items.removeAt(index);});返回真;},): 空值,文本比例因子:utf8.encode(item.substring(0, 1)).length >2 ?0.8:1,文本样式:文本样式(字体大小:_fontSize,),onPressed: (item) =>打印(项目),);},);}//弹出菜单的位置偏移 _tapPosition;小部件获取 _tags2 {//弹出菜单最终渲染框覆盖 = Overlay.of(context).context?.findRenderObject();ItemTagsCombine combine = ItemTagsCombine.onlyText;开关(_itemCombine){案例'onlyText':combine = ItemTagsCombine.onlyText;休息;案例'onlyIcon':combine = ItemTagsCombine.onlyIcon;休息;案例'onlyIcon':combine = ItemTagsCombine.onlyIcon;休息;案例'onlyImage':combine = ItemTagsCombine.onlyImage;休息;案例imageOrIconOrText":combine = ItemTagsCombine.imageOrIconOrText;休息;案例'withTextAfter':combine = ItemTagsCombine.withTextAfter;休息;案例withTextBefore":combine = ItemTagsCombine.withTextBefore;休息;}返回标签(键:键(2"),对称性:_symmetry,列:_列,水平滚动:_horizo​​ntalScroll,垂直方向:_startDirection ?VerticalDirection.up : 垂直方向.down,文本方向:_startDirection ?TextDirection.rtl:TextDirection.ltr,heightHorizo​​ntalScroll: 60 * (_fontSize/14),文本字段:标签文本字段(自动对焦:假,文本样式:文本样式(字体大小:_fontSize,//高度:1),启用:真,约束建议:真,建议:_withSuggesttions?[一个",二",安卓",飞镖",颤抖",测试",测试",机器人",androidsaaa",测试",建议",建议",互联网",最后",不怕",炫舞时代"]: 空值,onSubmitted: (String str) {print("onSubmitted $str");设置状态((){_items.add(str);});},),itemCount:_items.length,itemBuilder:(索引){最后一项 = _items[index];返回手势检测器(孩子:项目标签(键:键(index.toString()),索引:索引,标题:项目,按下启用:假,activeColor:Colors.green[400],结合:结合,图片:索引>0&&指数<5?ItemTagsImage(image: AssetImage("img/p$index.jpg")): (1 == 1?项目标签图像(图片:网络图片(https://image.flaticon.com/icons/png/512/44/44948.png")): 空值),图标:(项目 == '0' || 项目 == '1' || 项目 == '2')?项目标签图标(图标:_icon[int.parse(item)],): 空值,removeButton: ItemTagsRemoveButton(背景颜色:Colors.green[900],onRemoved: () {设置状态((){_items.removeAt(index);});返回真;},),文本比例因子:utf8.encode(item.substring(0, 1)).length >2 ?0.8:1,文本样式:文本样式(字体大小:_fontSize,),),onTapDown:(详细信息)=>_tapPosition = details.globalPosition,长按:(){显示菜单(//语义标签:项目,项目:<PopupMenuEntry>[弹出菜单项(孩子:文本(项目,样式:TextStyle(颜色:Colors.blueGrey)),启用:假,),PopupMenuDivider(),弹出菜单项(值:1,孩子:行(孩子们:<小部件>[图标(图标.content_copy),Text(复制文本"),],),),],上下文:上下文,位置:RelativeRect.fromRect(_tapPosition &尺寸(40, 40),偏移量.zero &覆盖.size)//&RelativeRect.fromLTRB(65.0, 40.0, 0.0, 0.0),).then((值){if (value == 1) Clipboard.setData(ClipboardData(text: item));});},);},);}列表<DropdownMenuItem>_buildItems() {列表<DropdownMenuItem>列表 = [];整数计数 = 19;列表.添加(下拉菜单项(孩子:文本(未设置"),值:0,),);for (int i = 1; i < count; i++)列表.添加(下拉菜单项(孩子:文本(i.toString()),值:我,),);返回列表;}列表<DropdownMenuItem>_buildItems2() {列表<DropdownMenuItem>列表 = [];list.add(DropdownMenuItem(孩子:文本(onlyText"),值:'onlyText',));list.add(DropdownMenuItem(孩子:文本(onlyIcon"),值:'onlyIcon',));list.add(DropdownMenuItem(孩子:文本(onlyImage"),值:'onlyImage',));list.add(DropdownMenuItem(孩子:文本(imageOrIconOrText"),值:'imageOrIconOrText',));list.add(DropdownMenuItem(孩子:文本(withTextBefore"),值:'withTextBefore',));list.add(DropdownMenuItem(孩子:文本(withTextAfter"),值:'withTextAfter',));返回列表;}}

I'm using https://pub.dev/packages/flutter_tags for a tag input. A tag is added to the array of tags by pressing submit on the keyboard and the TextInput Field cleared.

Now I have the problem that with a submit the keyboard also closes. So you have to press into the field again for every tag, which is not the sense of the thing. There are so many instructions on how to close the keyboard, but none on how to leave it open.

When Submit is pressed, the field loses focus and thus the keyboard closes. My idea was, unfortunately without success, to set a new focus on onSubmitted. Unfortunately nothing happens here:

TextField(
    controller: myController,
    focusNode: myFocusNode,
    // more code
    onSubmitted: (String str) {
        myController.clear();
        myFocusNode.requestFocus();
    }
)

Kind regards,

Jakob

解决方案

You can copy paste run full code below
The following code use official example code and modify Demo2
code snippet

    TextField(
      controller: myController,
      decoration: InputDecoration(
        icon: Icon(Icons.person),
        labelText: "add tag with focus",
      ),
      focusNode: myFocusNode,
      onSubmitted: (val) {
        setState(() {
          _items.add(val);
        });
        myController.clear();
        myFocusNode.requestFocus();
      },
    ),

working demo

full code

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_tags/flutter_tags.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tags Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: MyHomePage(title: 'Flutter Tags'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  FocusNode myFocusNode = FocusNode();
  TextEditingController myController = TextEditingController();

  TabController _tabController;
  ScrollController _scrollViewController;

  final List<String> _list = [
    '0',
    'SDK',
    'plugin updates',
    'Facebook',
    '哔了狗了QP又不够了',
    'Kirchhoff',
    'Italy',
    'France',
    'Spain',
    '美',
    'Dart',
    'SDK',
    'Foo',
    'Select',
    'lorem ip',
    '9',
    'Star',
    'Flutter Selectable Tags',
    '1',
    'Hubble',
    '2',
    'Input flutter tags',
    'A B C',
    '8',
    'Android Studio developer',
    'welcome to the jungle',
    'Gauss',
    '美术',
    '互联网',
    '炫舞时代',
    '篝火营地',
  ];

  bool _symmetry = false;
  bool _removeButton = true;
  bool _singleItem = false;
  bool _startDirection = false;
  bool _horizontalScroll = false;
  bool _withSuggesttions = false;
  int _count = 0;
  int _column = 0;
  double _fontSize = 14;

  String _itemCombine = 'withTextBefore';

  String _onPressed = '';

  List _icon = [Icons.home, Icons.language, Icons.headset];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _scrollViewController = ScrollController();

    _items = _list.toList();
  }

  List _items;

  final GlobalKey<TagsState> _tagStateKey = GlobalKey<TagsState>();

  @override
  Widget build(BuildContext context) {
    //List<Item> lst = _tagStateKey.currentState?.getAllItem; lst.forEach((f) => print(f.title));
    return Scaffold(
      body: NestedScrollView(
          controller: _scrollViewController,
          headerSliverBuilder: (BuildContext context, bool boxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                title: Text("flutter tags"),
                centerTitle: true,
                pinned: true,
                expandedHeight: 0,
                floating: true,
                forceElevated: boxIsScrolled,
                bottom: TabBar(
                  isScrollable: false,
                  indicatorSize: TabBarIndicatorSize.label,
                  labelStyle: TextStyle(fontSize: 18.0),
                  tabs: [
                    Tab(text: "Demo 1"),
                    Tab(text: "Demo 2"),
                  ],
                  controller: _tabController,
                ),
              )
            ];
          },
          body: TabBarView(
            controller: _tabController,
            children: [
              CustomScrollView(
                slivers: <Widget>[
                  SliverList(
                      delegate: SliverChildListDelegate([
                    Container(
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  color: Colors.grey[300], width: 0.5))),
                      margin:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      child: ExpansionTile(
                        title: Text("Settings"),
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _removeButton,
                                        onChanged: (a) {
                                          setState(() {
                                            _removeButton = !_removeButton;
                                          });
                                        }),
                                    Text('Remove Button')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _removeButton = !_removeButton;
                                  });
                                },
                              ),
                              Padding(
                                padding: EdgeInsets.all(5),
                              ),
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _symmetry,
                                        onChanged: (a) {
                                          setState(() {
                                            _symmetry = !_symmetry;
                                          });
                                        }),
                                    Text('Symmetry')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _symmetry = !_symmetry;
                                  });
                                },
                              ),
                              Padding(
                                padding: EdgeInsets.all(5),
                              ),
                              DropdownButton(
                                hint: _column == 0
                                    ? Text("Not set")
                                    : Text(_column.toString()),
                                items: _buildItems(),
                                onChanged: (a) {
                                  setState(() {
                                    _column = a;
                                  });
                                },
                              ),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _horizontalScroll,
                                        onChanged: (a) {
                                          setState(() {
                                            _horizontalScroll =
                                                !_horizontalScroll;
                                          });
                                        }),
                                    Text('Horizontal scroll')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _horizontalScroll = !_horizontalScroll;
                                  });
                                },
                              ),
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _singleItem,
                                        onChanged: (a) {
                                          setState(() {
                                            _singleItem = !_singleItem;
                                          });
                                        }),
                                    Text('Single Item')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _singleItem = !_singleItem;
                                  });
                                },
                              ),
                            ],
                          ),
                          Column(
                            children: <Widget>[
                              Text('Font Size'),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Slider(
                                    value: _fontSize,
                                    min: 6,
                                    max: 30,
                                    onChanged: (a) {
                                      setState(() {
                                        _fontSize = (a.round()).toDouble();
                                      });
                                    },
                                  ),
                                  Text(_fontSize.toString()),
                                  Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 20),
                                  ),
                                  Container(
                                    height: 30,
                                    width: 30,
                                    //color: Colors.blueGrey,
                                    child: IconButton(
                                      padding: EdgeInsets.all(0),
                                      //color: Colors.white,
                                      icon: Icon(Icons.add),
                                      onPressed: () {
                                        setState(() {
                                          _count++;
                                          _items.add(_count.toString());
                                          //_items.removeAt(3); _items.removeAt(10);
                                        });
                                      },
                                    ),
                                  ),
                                  Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 5),
                                  ),
                                  Container(
                                    height: 30,
                                    width: 30,
                                    //color: Colors.grey,
                                    child: IconButton(
                                      padding: EdgeInsets.all(0),
                                      //color: Colors.white,
                                      icon: Icon(Icons.refresh),
                                      onPressed: () {
                                        setState(() {
                                          _items = _list.toList();
                                        });
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(20),
                    ),
                    _tags1,
                    Container(
                        padding: EdgeInsets.all(20),
                        child: Column(
                          children: <Widget>[
                            Divider(
                              color: Colors.blueGrey,
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 20),
                              child: Text(_onPressed),
                            ),
                          ],
                        )),
                  ])),
                ],
              ),
              CustomScrollView(
                slivers: <Widget>[
                  SliverList(
                      delegate: SliverChildListDelegate([
                    Container(
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  color: Colors.grey[300], width: 0.5))),
                      margin:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      child: ExpansionTile(
                        title: Text("Settings"),
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _withSuggesttions,
                                        onChanged: (a) {
                                          setState(() {
                                            _withSuggesttions =
                                                !_withSuggesttions;
                                          });
                                        }),
                                    Text('Suggestions')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _withSuggesttions = !_withSuggesttions;
                                  });
                                },
                              ),
                              Padding(
                                padding: EdgeInsets.all(20),
                              ),
                              DropdownButton(
                                hint: Text(_itemCombine),
                                items: _buildItems2(),
                                onChanged: (val) {
                                  setState(() {
                                    _itemCombine = val;
                                  });
                                },
                              ),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _horizontalScroll,
                                        onChanged: (a) {
                                          setState(() {
                                            _horizontalScroll =
                                                !_horizontalScroll;
                                          });
                                        }),
                                    Text('Horizontal scroll')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _horizontalScroll = !_horizontalScroll;
                                  });
                                },
                              ),
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Checkbox(
                                        value: _startDirection,
                                        onChanged: (a) {
                                          setState(() {
                                            _startDirection = !_startDirection;
                                          });
                                        }),
                                    Text('Start Direction')
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _startDirection = !_startDirection;
                                  });
                                },
                              ),
                            ],
                          ),
                          Column(
                            children: <Widget>[
                              Text('Font Size'),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Slider(
                                    value: _fontSize,
                                    min: 6,
                                    max: 30,
                                    onChanged: (a) {
                                      setState(() {
                                        _fontSize = (a.round()).toDouble();
                                      });
                                    },
                                  ),
                                  Text(_fontSize.toString()),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(20),
                    ),
                    _tags2,
                    Container(
                        padding: EdgeInsets.all(20),
                        child: Column(
                          children: <Widget>[
                            Divider(
                              color: Colors.blueGrey,
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 20),
                              child: Text(_onPressed),
                            ),
                          ],
                        )),
                    TextField(
                      controller: myController,
                      decoration: InputDecoration(
                        icon: Icon(Icons.person),
                        labelText: "add tag with focus",
                      ),
                      focusNode: myFocusNode,
                      onSubmitted: (val) {
                        setState(() {
                          _items.add(val);
                        });
                        myController.clear();
                        myFocusNode.requestFocus();
                      },
                    ),
                  ])),
                ],
              ),
            ],
          )),
    );
  }

  Widget get _tags1 {
    return Tags(
      key: _tagStateKey,
      symmetry: _symmetry,
      columns: _column,
      horizontalScroll: _horizontalScroll,
      //verticalDirection: VerticalDirection.up, textDirection: TextDirection.rtl,
      heightHorizontalScroll: 60 * (_fontSize / 14),
      itemCount: _items.length,
      itemBuilder: (index) {
        final item = _items[index];

        return ItemTags(
          key: Key(index.toString()),
          index: index,
          title: item,
          pressEnabled: true,
          activeColor: Colors.blueGrey[600],
          singleItem: _singleItem,
          splashColor: Colors.green,
          combine: ItemTagsCombine.withTextBefore,
          image: index > 0 && index < 5
              ? ItemTagsImage(
                  //image: AssetImage("img/p$index.jpg"),
                  child: Image.network(
                  "http://www.clipartpanda.com/clipart_images/user-66327738/download",
                  width: 16 * _fontSize / 14,
                  height: 16 * _fontSize / 14,
                ))
              : (1 == 1
                  ? ItemTagsImage(
                      image: NetworkImage(
                          "https://d32ogoqmya1dw8.cloudfront.net/images/serc/empty_user_icon_256.v2.png"),
                    )
                  : null),
          icon: (item == '0' || item == '1' || item == '2')
              ? ItemTagsIcon(
                  icon: _icon[int.parse(item)],
                )
              : null,
          removeButton: _removeButton
              ? ItemTagsRemoveButton(
                  onRemoved: () {
                    setState(() {
                      _items.removeAt(index);
                    });
                    return true;
                  },
                )
              : null,
          textScaleFactor:
              utf8.encode(item.substring(0, 1)).length > 2 ? 0.8 : 1,
          textStyle: TextStyle(
            fontSize: _fontSize,
          ),
          onPressed: (item) => print(item),
        );
      },
    );
  }

  // Position for popup menu
  Offset _tapPosition;

  Widget get _tags2 {
    //popup Menu
    final RenderBox overlay = Overlay.of(context).context?.findRenderObject();

    ItemTagsCombine combine = ItemTagsCombine.onlyText;

    switch (_itemCombine) {
      case 'onlyText':
        combine = ItemTagsCombine.onlyText;
        break;
      case 'onlyIcon':
        combine = ItemTagsCombine.onlyIcon;
        break;
      case 'onlyIcon':
        combine = ItemTagsCombine.onlyIcon;
        break;
      case 'onlyImage':
        combine = ItemTagsCombine.onlyImage;
        break;
      case 'imageOrIconOrText':
        combine = ItemTagsCombine.imageOrIconOrText;
        break;
      case 'withTextAfter':
        combine = ItemTagsCombine.withTextAfter;
        break;
      case 'withTextBefore':
        combine = ItemTagsCombine.withTextBefore;
        break;
    }

    return Tags(
      key: Key("2"),
      symmetry: _symmetry,
      columns: _column,
      horizontalScroll: _horizontalScroll,
      verticalDirection:
          _startDirection ? VerticalDirection.up : VerticalDirection.down,
      textDirection: _startDirection ? TextDirection.rtl : TextDirection.ltr,
      heightHorizontalScroll: 60 * (_fontSize / 14),
      textField: TagsTextField(
        autofocus: false,
        textStyle: TextStyle(
          fontSize: _fontSize,
          //height: 1
        ),
        enabled: true,
        constraintSuggestion: true,
        suggestions: _withSuggesttions
            ? [
                "One",
                "two",
                "android",
                "Dart",
                "flutter",
                "test",
                "tests",
                "androids",
                "androidsaaa",
                "Test",
                "suggest",
                "suggestions",
                "互联网",
                "last",
                "lest",
                "炫舞时代"
              ]
            : null,
        onSubmitted: (String str) {
          print("onSubmitted $str");
          setState(() {
            _items.add(str);
          });
        },
      ),
      itemCount: _items.length,
      itemBuilder: (index) {
        final item = _items[index];

        return GestureDetector(
          child: ItemTags(
            key: Key(index.toString()),
            index: index,
            title: item,
            pressEnabled: false,
            activeColor: Colors.green[400],
            combine: combine,
            image: index > 0 && index < 5
                ? ItemTagsImage(image: AssetImage("img/p$index.jpg"))
                : (1 == 1
                    ? ItemTagsImage(
                        image: NetworkImage(
                            "https://image.flaticon.com/icons/png/512/44/44948.png"))
                    : null),
            icon: (item == '0' || item == '1' || item == '2')
                ? ItemTagsIcon(
                    icon: _icon[int.parse(item)],
                  )
                : null,
            removeButton: ItemTagsRemoveButton(
              backgroundColor: Colors.green[900],
              onRemoved: () {
                setState(() {
                  _items.removeAt(index);
                });
                return true;
              },
            ),
            textScaleFactor:
                utf8.encode(item.substring(0, 1)).length > 2 ? 0.8 : 1,
            textStyle: TextStyle(
              fontSize: _fontSize,
            ),
          ),
          onTapDown: (details) => _tapPosition = details.globalPosition,
          onLongPress: () {
            showMenu(
                    //semanticLabel: item,
                    items: <PopupMenuEntry>[
                  PopupMenuItem(
                    child: Text(item, style: TextStyle(color: Colors.blueGrey)),
                    enabled: false,
                  ),
                  PopupMenuDivider(),
                  PopupMenuItem(
                    value: 1,
                    child: Row(
                      children: <Widget>[
                        Icon(Icons.content_copy),
                        Text("Copy text"),
                      ],
                    ),
                  ),
                ],
                    context: context,
                    position: RelativeRect.fromRect(
                        _tapPosition & Size(40, 40),
                        Offset.zero &
                            overlay
                                .size) // & RelativeRect.fromLTRB(65.0, 40.0, 0.0, 0.0),
                    )
                .then((value) {
              if (value == 1) Clipboard.setData(ClipboardData(text: item));
            });
          },
        );
      },
    );
  }

  List<DropdownMenuItem> _buildItems() {
    List<DropdownMenuItem> list = [];

    int count = 19;

    list.add(
      DropdownMenuItem(
        child: Text("Not set"),
        value: 0,
      ),
    );

    for (int i = 1; i < count; i++)
      list.add(
        DropdownMenuItem(
          child: Text(i.toString()),
          value: i,
        ),
      );

    return list;
  }

  List<DropdownMenuItem> _buildItems2() {
    List<DropdownMenuItem> list = [];

    list.add(DropdownMenuItem(
      child: Text("onlyText"),
      value: 'onlyText',
    ));

    list.add(DropdownMenuItem(
      child: Text("onlyIcon"),
      value: 'onlyIcon',
    ));
    list.add(DropdownMenuItem(
      child: Text("onlyImage"),
      value: 'onlyImage',
    ));
    list.add(DropdownMenuItem(
      child: Text("imageOrIconOrText"),
      value: 'imageOrIconOrText',
    ));
    list.add(DropdownMenuItem(
      child: Text("withTextBefore"),
      value: 'withTextBefore',
    ));
    list.add(DropdownMenuItem(
      child: Text("withTextAfter"),
      value: 'withTextAfter',
    ));

    return list;
  }
}

这篇关于Flutter:如何让 TextField 专注于提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆