2017-06-12 123 views
2

我需要偶尔禁用TextFormField。我无法在窗口小部件中找到标志,或者只是将控制器设置为只读或禁用。 做什么是最好的方法?禁用文本编辑字段晃动

+0

提起https://github.com/flutter/flutter/issues/10645 –

回答

4

这不是框架当前提供的功能,但您可以使用FocusScope防止TextFormField请求关注。

下面是禁用时的样子。

(与提示文本) empty and readonly

(具有只读值) readonly

这里是什么样子时的启用它像。

(具有焦点) focused

(不聚焦) editable

代码这是以下:

import 'package:flutter/material.dart'; 

void main() { 
    runApp(new MaterialApp(
    home: new HomePage(), 
)); 
} 

class HomePage extends StatefulWidget { 
    HomePageState createState() => new HomePageState(); 
} 

class HomePageState extends State<HomePage> { 

    TextEditingController _controller = new TextEditingController(); 
    bool _enabled = false; 

    @override 
    Widget build(BuildContext context) { 
    ThemeData theme = Theme.of(context); 
    return new Scaffold(
     appBar: new AppBar(
     title: new Text('Disabled Text'), 
    ), 
     floatingActionButton: new FloatingActionButton(
     child: new Icon(Icons.free_breakfast), 
     onPressed:() { 
      setState(() { 
      _enabled = !_enabled; 
      }); 
     } 
    ), 
     body: new Center(
     child: new Container(
      margin: const EdgeInsets.all(10.0), 
      child: _enabled ? 
      new TextFormField(controller: _controller) : 
      new FocusScope(
      node: new FocusScopeNode(), 
      child: new TextFormField(
       controller: _controller, 
       style: theme.textTheme.subhead.copyWith(
       color: theme.disabledColor, 
      ), 
       decoration: new InputDecoration(
       hintText: _enabled ? 'Type something' : 'You cannot focus me', 
      ), 
      ), 
     ), 
     ), 
    ), 
    ); 
    } 
} 
1

还有另一种方法可以做到这一点也不会引起this issue。希望这可能有助于某人。

创建AlwaysDisabledFocusNode并将其传递给focusNode属性TextField

class AlwaysDisabledFocusNode extends FocusNode { 
    @override 
    bool get hasFocus => false; 
} 

然后

new TextField(
    focusNode: new AlwaysDisabledFocusNode(), 
    ... 
    ... 
)