美文网首页
Flutter TextField 设置文字并把光标放置末尾

Flutter TextField 设置文字并把光标放置末尾

作者: 林祖朋 | 来源:发表于2021-05-26 16:07 被阅读0次

这里是查源码得的结果

/// Setting this will notify all the listeners of this [TextEditingController]
  /// that they need to update (it calls [notifyListeners]). For this reason,
  /// this value should only be set between frames, e.g. in response to user
  /// actions, not during the build, layout, or paint phases.
  ///
  /// This property can be set from a listener added to this
  /// [TextEditingController]; however, one should not also set [selection]
  /// in a separate statement. To change both the [text] and the [selection]
  /// change the controller's [value].
  set text(String newText) {
    value = value.copyWith(
      text: newText,
      selection: const TextSelection.collapsed(offset: -1),
      composing: TextRange.empty,
    );
  }

具体代码实现

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _contentController = TextEditingController();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('首页初始化');

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('首页销毁');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          padding: EdgeInsets.all(20),
          child: TextField(
            controller: _contentController,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()  {
           _contentController.value=TextEditingValue(
             text: "ABC",
             selection: const TextSelection.collapsed(offset: "ABC".length),
             composing: TextRange.empty,
           );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

相关文章

网友评论

      本文标题:Flutter TextField 设置文字并把光标放置末尾

      本文链接:https://www.haomeiwen.com/subject/pjiksltx.html