在Flutter上添加行号到TextField的方法如下:
下面是一个示例代码:
import 'package:flutter/material.dart';
class LineNumberTextField extends StatefulWidget {
@override
_LineNumberTextFieldState createState() => _LineNumberTextFieldState();
}
class _LineNumberTextFieldState extends State<LineNumberTextField> {
TextEditingController _controller;
List<int> _lineNumbers = [1];
@override
void initState() {
super.initState();
_controller = TextEditingController();
_controller.addListener(_updateLineNumbers);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _updateLineNumbers() {
String text = _controller.text;
int lines = text.split('\n').length;
setState(() {
_lineNumbers = List.generate(lines, (index) => index + 1);
});
}
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: _lineNumbers.map((lineNumber) {
return Text(
lineNumber.toString(),
style: TextStyle(fontSize: 12),
);
}).toList(),
),
SizedBox(width: 8),
Expanded(
child: ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
TextField(
controller: _controller,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter text here...',
),
),
],
),
),
],
);
}
}
使用方式如下:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Line Number TextField')),
body: Padding(
padding: EdgeInsets.all(16),
child: LineNumberTextField(),
),
),
);
}
}
这样,就能在TextField上方显示行号了。每次文本改变时,行号会自动更新。
对于推荐的腾讯云产品和产品介绍链接地址,请参考腾讯云官方文档和网站,以获取最新的产品信息和链接地址。
领取专属 10元无门槛券
手把手带您无忧上云